Elffuss BraidHub

kikocis/java-driver public

3.1.x · 10.5 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
96If you use paging with the async API, you'll also want to use those
97methods to avoid triggering synchronous fetches unintentionally; see
98[async paging](../async/#async-paging).
99
100
101### Saving and reusing the paging state
102
103Sometimes it is convenient to save the paging state in order to restore
104it later. For example, consider a stateless web service that displays a
105list of results with a link to the next page. When the user clicks that
106link, we want to run the exact same query, except that the iteration
107should start where we stopped on the previous page.
108
109To do so, the driver exposes a [PagingState][paging_state] object that represents
110where we were in the result set when the last page was fetched:
111
112```java
113ResultSet resultSet = session.execute("your query");
114// iterate the result set...
115PagingState pagingState = resultSet.getExecutionInfo().getPagingState();
116```
117
118This object can be serialized to a `String` or a byte array:
119
120```java
121String string = pagingState.toString();
122byte[] bytes = pagingState.toBytes();
123```
124
125This serialized form can be saved in some form of persistent storage to
126be reused later. In our web service example, we would probably save the
127string version as a query parameter in the URL to the next page
128(`http://myservice.com/results?page=<...>`). When that value is
129retrieved later, we can deserialize it and reinject it in a statement:
130
131```java
132PagingState pagingState = PagingState.fromString(string);
133Statement st = new SimpleStatement("your query");
134st.setPagingState(pagingState);
135ResultSet rs = session.execute(st);
136```
137
138Note that the paging state can only be reused with the exact same
139statement (same query string, same parameters). Also, it is an opaque
140value that is only meant to be collected, stored an re-used. If you try
141to modify its contents or reuse it with a different statement, the
142driver will raise an error.
143
144Putting it all together, here's a more comprehensive example
145implementation for our web service:
146
147```java
148final int RESULTS_PER_PAGE = 100;
149
150Statement st = new SimpleStatement("your query");
151st.setFetchSize(RESULTS_PER_PAGE);
152
153String requestedPage = extractPagingStateStringFromURL();
154// This will be absent for the first page
155if (requestedPage != null) {
156 st.setPagingState(
157 PagingState.fromString(requestedPage));
158}
159
160ResultSet rs = session.execute(st);
161PagingState nextPage = rs.getExecutionInfo().getPagingState();
162
163// Note that we don't rely on RESULTS_PER_PAGE, since Cassandra might
164// have not respected it, or we might be at the end of the result set
165int remaining = rs.getAvailableWithoutFetching();
166for (Row row : rs) {
167 renderInResponse(row);
168 if (--remaining == 0) {
169 break;
170 }
171}
172
173// This will be null if there are no more pages
174if (nextPage != null) {
175 renderNextPageLink(nextPage.toString());
176}
177```
178
179[result_set]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/ResultSet.html
180[paging_state]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PagingState.html
181
182
183Due to internal implementation details, `PagingState` instances are not
184portable across [native protocol](../native_protocol/) versions. This
185could become a problem in the following scenario:
186
187* you're using the driver 2.0.x and Cassandra 2.0.x, and therefore
188 native protocol v2;
189* a user bookmarks a link to your web service that contains a serialized
190 paging state;
191* you upgrade your server stack to use the driver 2.1.x and Cassandra
192 2.1.x, so you're now using protocol v3;
193* the user tries to reload their bookmark, but the paging state was
194 serialized with protocol v2, so trying to reuse it will fail.
195
196If this is not acceptable for you, you might want to consider the unsafe
197API described in the next section.
198
199#### Unsafe API
200
201As an alternative to the standard API, there are two methods that
202manipulate a raw `byte[]` instead of a `PagingState` object:
203
204* [ExecutionInfo#getPagingStateUnsafe()][gpsu]
205* [Statement#setPagingStateUnsafe(byte[])][spsu]
206
207These low-level methods perform no validation on their arguments;
208therefore nothing protects you from reusing a paging state that was
209generated from a different statement, or altered in any way. This could
210result in sending a corrupt paging state to Cassandra, with
211unpredictable consequences (ranging from wrong results to a query
212failure).
213
214There are two situations where you might want to use the unsafe API:
215
216* you never expose the paging state to end users and you are confident
217 that it won't get altered;
218* you want portability across protocol versions and/or you prefer
219 implementing your own validation logic (for example, signing the raw
220 state with a private key).
221
222[gpsu]: http://www.datastax.com/drivers/java/3.0/com/datastax/driver/core/ExecutionInfo.html#getPagingStateUnsafe--
223[spsu]: http://www.datastax.com/drivers/java/3.0/com/datastax/driver/core/Statement.html#setPagingStateUnsafe-byte:A-
224
225### Offset queries
226
227Saving the paging state works well when you only let the user move from
228one page to the next. But it doesn't allow random jumps (like "go
229directly to page 10"), because you can't fetch a page unless you have
230the paging state of the previous one. Such a feature would require
231*offset queries*, but they are not natively supported by Cassandra (see
232[CASSANDRA-6511](https://issues.apache.org/jira/browse/CASSANDRA-6511)).
233The rationale is that offset queries are inherently inefficient (the
234performance will always be linear in the number of rows skipped), so the
235Cassandra team doesn't want to encourage their use.
236
237If you really want offset queries, you can emulate them client-side.
238You'll still get linear performance, but maybe that's acceptable for
239your use case. For example, if each page holds 10 rows and you show at
240most 20 pages, this means you'll fetch at most 190 extra rows, which
241doesn't sound like a big deal.
242
243For example, if the page size is 10, the fetch size is 50, and the user
244asks for page 12 (rows 110 to 119):
245
246* execute the statement a first time (the result set contains rows 0 to
247 49, but you're not going to use them, only the paging state);
248* execute the statement a second time with the paging state from the
249 first query;
250* execute the statement a third time with the paging state from the
251 second query. The result set now contains rows 100 to 149;
252* skip the first 10 rows of the iterator. Read the next 10 rows and
253 discard the remaining ones.
254
255You'll want to experiment with the fetch size to find the best balance:
256too small means many background queries; too big means bigger messages
257and too many unneeded rows returned (we picked 50 above for the sake of
258example, but it's probably too small -- the default is 5000).
259
260Again, offset queries are inefficient by nature. Emulating them
261client-side is a compromise when you think you can get away with the
262performance hit. We recommend that you:
263
264* test your code at scale with the expected query patterns, to make sure
265 that your assumptions are correct;
266* set a hard limit on the highest possible page number, to prevent
267 malicious users from triggering queries that would skip a huge amount
268 of rows.