通过分页读取卡桑德拉数据不起作用

时间:2018-10-16 03:55:33

标签: java cassandra

我尝试通过分页读取cassandra数据,但是它不起作用。我的代码如下。每个页面都有相同的内容。我错过了什么吗?

  // Persist the entity objects
    for (int i=0; i<1000; i++) {
        // change person1's id
        personObj1.setPersonId("haofan" + i);
        dataServiceClient.persist(personObj1);
    }

    Query query;
    List<Person> personList;

    // Create and execute SELECT * query
    for (int i =0; i<10; i++) {
        String cqlString = "Select p from Person p";
        // String cqlString = "Select p from Person p";
        query = dataServiceClient.createQuery(cqlString).setMaxResults(100).setFirstResult(i*100);
        personList = query.getResultList();
        // Get the same personId for every page. 
        Assert.assertEquals(100, personList.size());

        System.out.println("haofan for: " + personList.get(10).getPersonId());
    }

2 个答案:

答案 0 :(得分:0)

您正在寻找offset个查询,Cassandra本身不支持。

答案 1 :(得分:0)

我尝试了多种解决方案,最终对我来说如下所示。请参阅:https://docs.datastax.com/en/developer/java-driver/3.6/manual/paging/

public String paging(Session session, String pageState) {
    Statement statement = new SimpleStatement("SELECT * FROM testkeyspace.\"PERSON\"");
    statement.setFetchSize(3);
    if (pageState != null) {
        statement.setPagingState( PagingState.fromString(pageState));
    }
    ResultSet rs = session.execute(statement);
    int remaining = rs.getAvailableWithoutFetching();
    System.out.println("remaining " + remaining);
    for (Row row : rs) {
        System.out.println("first" + row);
        if (--remaining == 0) {
            break;
        }
    }
    return rs.getExecutionInfo().getPagingState().toString();
}

如何使用此功能:

@Test
@Category(DataServiceRequired.class)
public void pagingTest() throws Exception {
    Cluster cluster = Cluster.builder().addContactPoint("localhost").withPort(9042).build();
    Session session = cluster.connect();

    String pageState = paging(session, null);

    paging(session, pageState);
}