java - Cassandra 分页

标签 java cassandra pagination bigdata database

我在 Cassandra 中有一张表,其中包含 100 万条记录。我想一次抓取100条记录,所以如果我抓取前100条,下一次抓取应该从第101条开始。我如何获得这种分页?我也使用了 PagingState 但它没有用。

我的代码如下:

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.datastax.driver.core.PagingState;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.Statement;

/**
 * 
 * The solution of skipping rows is that use page state rather than iterator
 * rows one by one.
 *
 */
public class CassandraPaging {

    private Session session;

    public CassandraPaging(Session session) {
        this.session = session;
    }

    /**
     * Retrieve rows for the specified page offset.
     * 
     * @param statement
     * @param start
     *            starting row (>1), inclusive
     * @param size
     *            the maximum rows need to retrieve.
     * @return List<Row>
     */
    public List<Row> fetchRowsWithPage(Statement statement, int start, int size) {
        ResultSet result = skipRows(statement, start, size);
        return getRows(result, start, size);
    }

    private ResultSet skipRows(Statement statement, int start, int size) {
        ResultSet result = null;
        int skippingPages = getPageNumber(start, size);
        String savingPageState = null;
        statement.setFetchSize(size);
        boolean isEnd = false;
        for (int i = 0; i < skippingPages; i++) {
            if (null != savingPageState) {
                statement = statement.setPagingState(PagingState
                        .fromString(savingPageState));
            }
            result = session.execute(statement);
            PagingState pagingState = result.getExecutionInfo()
                    .getPagingState();
            if (null != pagingState) {
                savingPageState = result.getExecutionInfo().getPagingState()
                        .toString();
            }

            if (result.isFullyFetched() && null == pagingState) {
                // if hit the end more than once, then nothing to return,
                // otherwise, mark the isEnd to 'true'
                if (true == isEnd) {
                    return null;
                } else {
                    isEnd = true;
                }
            }
        }
        return result;
    }

    private int getPageNumber(int start, int size) {
        if (start < 1) {
            throw new IllegalArgumentException(
                    "Starting row need to be larger than 1");
        }
        int page = 1;
        if (start > size) {
            page = (start - 1) / size + 1;
        }
        return page;
    }

    private List<Row> getRows(ResultSet result, int start, int size) {
        List<Row> rows = new ArrayList<>(size);
        if (null == result) {
            return rows;
        }
        int skippingRows = (start - 1) % size;
        int index = 0;
        for (Iterator<Row> iter = result.iterator(); iter.hasNext()
                && rows.size() < size;) {
            Row row = iter.next();
            if (index >= skippingRows) {
                rows.add(row);
            }
            index++;
        }
        return rows;
    }
}

这是主要方法:

public static void main(String[] args) {
    Cluster cluster = null;
    Session session = null;

    try {
        cluster = Cluster.builder().addContactPoint("localhost").withPort(9042).build();
        session = cluster.connect("mykeyspace");

        Statement select = QueryBuilder.select().all().from("mykeyspace", "Mytable");

        CassandraPaging cassandraPaging = new CassandraPaging(session);
        System.out.println("*************First Page1 **************");
        List<Row> firstPageRows = cassandraPaging.fetchRowsWithPage(select, 1, 5);
        printUser(firstPageRows);

        System.out.println("*************Second Page2 **************");
        List<Row> secondPageRows = cassandraPaging.fetchRowsWithPage(select, 6, 5);
        printUser(secondPageRows);

        System.out.println("*************Third Page3 **************");
        List<Row> thirdPageRows = cassandraPaging.fetchRowsWithPage(select, 6, 5);
        printUser(thirdPageRows);

        cluster.close();
        session.close();

    } catch(Exception exp) {
        exp.printStackTrace();
    } finally {
        cluster.close();
        session.close();
    }
}

private static void printUser(final List<Row> inRows) {
    for (Row row : inRows) {
        System.out.println("Id is:" + row.getUUID("id"));
        System.out.println("Name is:" + row.getInt("name"));
        System.out.println("account is:" + row.getString("account"));
    }
}

最佳答案

  /*First, get the number of page states with page limit size (in my case 25):*/

 int n=0;
 PagingState pageStates=null;
 Map<Integer, PagingState> stringMap=new HashMap<Integer, PagingState>();
 do{
    Statement select = QueryBuilder.select().all().from("keyspace", "tablename").setFetchSize(25).setPagingState(pageStates);
    ResultSet resultSet=session.execute(select);
    pageStates=resultSet.getExecutionInfo().getPagingState();
    stringMap.put(++n,pageStates);
 }while (pageStates!=null);


 /*Then, find page index -> get the exact page state -> pass it in query
 ========================================================================
 1.Get the page number
 2.calculate the offset with pagelimit(in my case 25)
 3.get the pageindex
 4. pass pagestate of appropriate page index in query */


 int pagenumber ;                      
 int offset = (pagenumber * 25) - 25;  
 int pageindex=(offset/25)-1;        
 Statement selectq = QueryBuilder.select().all().from("keyspace", "tablename").setPagingState(stringMap.get(pageindex));  
 ResultSet resultSet = session.execute(selectq);
 fourthPageRows=cassandraPaging.getRows(resultSet,offset,25);

关于java - Cassandra 分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44254428/

相关文章:

java - 单击 JFrame 中的 JButton 时如何更改现有图像? ( java )

java - spring Kafka模型不在可信包中

pagination - 通过 Boto3 进行 DynamoDB 分页,NextToken 不存在但 LastEvaluatedKey 存在?

php - 如何在 PHP 中对 JSON 数据进行分页?

amazon-s3 - S3 NextContinuationToken/ContinuationToken : does it expire?

java - 如何在最快的时间内对接近排序的数组进行排序? ( java )

java - Brian Goetz 的不当出版

Cassandra 2.1 : how to model for the N most recently active users?

java - Node.js API 通过 SQS 将数据发送给 Java Worker,并通过 SQS 将 Worker 的结果返回给 API

python - Cassandra 。默认列值