Elffuss BraidHub

kikocis/java-driver public

b364a0e42c7c · 10.4 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### Saving and reusing the paging state
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
176
177Due to internal implementation details, `PagingState` instances are not
178portable across [native protocol](../native_protocol/) versions. This
179could become a problem in the following scenario:
180
181* you're using the driver 2.0.x and Cassandra 2.0.x, and therefore
182 native protocol v2;
183* a user bookmarks a link to your web service that contains a serialized
184 paging state;
185* you upgrade your server stack to use the driver 2.1.x and Cassandra
186 2.1.x, so you're now using protocol v3;
187* the user tries to reload their bookmark, but the paging state was
188 serialized with protocol v2, so trying to reuse it will fail.
189
190If this is not acceptable for you, you might want to consider the unsafe
191API described in the next section.
192
193#### Unsafe API
194
195As an alternative to the standard API, there are two methods that
196manipulate a raw `byte[]` instead of a `PagingState` object:
197
198* [ExecutionInfo#getPagingStateUnsafe()][gpsu]
199* [Statement#setPagingStateUnsafe(byte[])][spsu]
200
201These low-level methods perform no validation on their arguments;
202therefore nothing protects you from reusing a paging state that was
203generated from a different statement, or altered in any way. This could
204result in sending a corrupt paging state to Cassandra, with
205unpredictable consequences (ranging from wrong results to a query
206failure).
207
208There are two situations where you might want to use the unsafe API:
209
210* you never expose the paging state to end users and you are confident
211 that it won't get altered;
212* you want portability across protocol versions and/or you prefer
213 implementing your own validation logic (for example, signing the raw
214 state with a private key).
215
216[gpsu]: http://www.datastax.com/drivers/java/2.0/com/datastax/driver/core/ExecutionInfo.html#getPagingStateUnsafe()
217[spsu]: http://www.datastax.com/drivers/java/2.0/com/datastax/driver/core/Statement.html#setPagingStateUnsafe(byte[])
218
219### Offset queries
220
221Saving the paging state works well when you only let the user move from
222one page to the next. But it doesn't allow random jumps (like "go
223directly to page 10"), because you can't fetch a page unless you have
224the paging state of the previous one. Such a feature would require
225*offset queries*, but they are not natively supported by Cassandra (see
226[CASSANDRA-6511](https://issues.apache.org/jira/browse/CASSANDRA-6511)).
227The rationale is that offset queries are inherently inefficient (the
228performance will always be linear in the number of rows skipped), so the
229Cassandra team doesn't want to encourage their use.
230
231If you really want offset queries, you can emulate them client-side.
232You'll still get linear performance, but maybe that's acceptable for
233your use case. For example, if each page holds 10 rows and you show at
234most 20 pages, this means you'll fetch at most 190 extra rows, which
235doesn't sound like a big deal.
236
237For example, if the page size is 10, the fetch size is 50, and the user
238asks for page 12 (rows 110 to 119):
239
240* execute the statement a first time (the result set contains rows 0 to
241 49, but you're not going to use them, only the paging state);
242* execute the statement a second time with the paging state from the
243 first query;
244* execute the statement a third time with the paging state from the
245 second query. The result set now contains rows 100 to 149;
246* skip the first 10 rows of the iterator. Read the next 10 rows and
247 discard the remaining ones.
248
249You'll want to experiment with the fetch size to find the best balance:
250too small means many background queries; too big means bigger messages
251and too many unneeded rows returned (we picked 50 above for the sake of
252example, but it's probably too small -- the default is 5000).
253
254Again, offset queries are inefficient by nature. Emulating them
255client-side is a compromise when you think you can get away with the
256performance hit. We recommend that you:
257
258* test your code at scale with the expected query patterns, to make sure
259 that your assumptions are correct;
260* set a hard limit on the highest possible page number, to prevent
261 malicious users from triggering queries that would skip a huge amount
262 of rows.