Elffuss BraidHub

kikocis/java-driver public

d5dbc139ebbe · 6.3 KiBRenderedRawPermalink
1## Paging
2
3When a query returns many rows, it would be inefficient to return them
4as a single response message. Instead, the driver breaks the results
5into *pages* which get returned as they are needed.
6
7### Setting the fetch size
8
9The *fetch size* specifies how many rows will be returned at once by
10Cassandra (in other words, it's the size of each page).
11
12You can set a default fetch size globally for a `Cluster` instance:
13
14```java
15// At initialization:
16Cluster cluster = Cluster.builder()
17 .addContactPoint("127.0.0.1")
18 .withQueryOptions(new QueryOptions().setFetchSize(2000))
19 .build();
20
21// Or at runtime:
22cluster.getConfiguration().getQueryOptions().setFetchSize(2000);
23```
24
25The fetch size can also be set on a statement:
26
27```java
28Statement statement = new SimpleStatement("your query");
29statement.setFetchSize(2000);
30```
31
32If the fetch size is set on a statement, it will take precedence;
33otherwise, the cluster-wide value (which defaults to 5000) will be used.
34
35Note that setting a fetch size doesn't mean that Cassandra will always
36return the exact number of rows, it is possible that it returns slightly
37more or less results.
38
39### Result set iteration
40
41The fetch size limits the number of results that are returned in one
42page; if you iterate past that, the driver will run background queries
43to fetch subsequent pages. Here's an example with a fetch size of 20:
44
45```ditaa
46 client Session Cassandra
47 --+--------------+---------------------------------+-----
48 |execute(query)| |
49 |------------->| |
50 | | query rows 1 to 20 |
51 | |-------------------------------->|
52 | | |
53 | |create |
54 | |------>ResultSet |
55 | | |
56+-----+--------+-----------------+-+ |
57|For i in 1..20| | | |
58+--------------+ | | |
59| | get next row | | |
60| |------------------------->| | |
61| | row i | | |
62| |<-------------------------| | |
63| | | | |
64+-----+--------------------------+-+ |
65 | | |
66 | | |
67 | get next row | |
68 |------------------------->| |
69 | | query rows 21 to 40 |
70 | |-------------------->|
71 | row 21 | |
72 |<------------------------ | |
73```
74
75By default, the background fetch happens at the last moment, when there
76are no more "local" rows available. If you need finer control, the
77[ResultSet][result_set] interface provides the following methods:
78
79* `getAvailableWithoutFetching()` and `isFullyFetched()` to check the
80 current state;
81* `fetchMoreResults()` to force a page fetch.
82
83Here's how you could use these methods to pre-fetch the next page in
84advance, in order to avoid the performance hit at the end of each page:
85
86```java
87ResultSet rs = session.execute("your query");
88for (Row row : rs) {
89 if (rs.getAvailableWithoutFetching() == 100 && !rs.isFullyFetched())
90 rs.fetchMoreResults(); // this is asynchronous
91 // Process the row ...
92 System.out.println(row);
93}
94```
95
96### Manual paging
97
98Sometimes it is convenient to save the paging state in order to restore
99it later. For example, consider a stateless web service that displays a
100list of results with a link to the next page. When the user clicks that
101link, we want to run the exact same query, except that the iteration
102should start where we stopped on the previous page.
103
104To do so, the driver exposes a [PagingState][paging_state] object that represents
105where we were in the result set when the last page was fetched:
106
107```java
108ResultSet resultSet = session.execute("your query");
109// iterate the result set...
110PagingState pagingState = resultSet.getExecutionInfo().getPagingState();
111```
112
113This object can be serialized to a `String` or a byte array:
114
115```java
116String string = pagingState.toString();
117byte[] bytes = pagingState.toBytes();
118```
119
120This serialized form can be saved in some form of persistent storage to
121be reused later. In our web service example, we would probably save the
122string version as a query parameter in the URL to the next page
123(`http://myservice.com/results?page=<...>`). When that value is
124retrieved later, we can deserialize it and reinject it in a statement:
125
126```java
127PagingState pagingState = PagingState.fromString(string);
128Statement st = new SimpleStatement("your query");
129st.setPagingState(pagingState);
130ResultSet rs = session.execute(st);
131```
132
133Note that the paging state can only be reused with the exact same
134statement (same query string, same parameters). Also, it is an opaque
135value that is only meant to be collected, stored an re-used. If you try
136to modify its contents or reuse it with a different statement, the
137driver will raise an error.
138
139Putting it all together, here's a more comprehensive example
140implementation for our web service:
141
142```java
143final int RESULTS_PER_PAGE = 100;
144
145Statement st = new SimpleStatement("your query");
146st.setFetchSize(RESULTS_PER_PAGE);
147
148String requestedPage = extractPagingStateStringFromURL();
149// This will be absent for the first page
150if (requestedPage != null) {
151 st.setPagingState(
152 PagingState.fromString(requestedPage));
153}
154
155ResultSet rs = session.execute(st);
156PagingState nextPage = rs.getExecutionInfo().getPagingState();
157
158// Note that we don't rely on RESULTS_PER_PAGE, since Cassandra might
159// have not respected it, or we might be at the end of the result set
160int remaining = rs.getAvailableWithoutFetching();
161for (Row row : rs) {
162 renderInResponse(row);
163 if (--remaining == 0) {
164 break;
165 }
166}
167
168// This will be null if there are no more pages
169if (nextPage != null) {
170 renderNextPageLink(nextPage.toString());
171}
172```
173
174[result_set]:http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/ResultSet.html
175[paging_state]:http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/PagingState.html