| 1 | ## Paging |
| 2 | |
| 3 | When a query returns many rows, it would be inefficient to return them |
| 4 | as a single response message. Instead, the driver breaks the results |
| 5 | into *pages* which get returned as they are needed. |
| 6 | |
| 7 | ### Setting the fetch size |
| 8 | |
| 9 | The *fetch size* specifies how many rows will be returned at once by |
| 10 | Cassandra (in other words, it's the size of each page). |
| 11 | |
| 12 | You can set a default fetch size globally for a `Cluster` instance: |
| 13 | |
| 14 | ```java |
| 15 | // At initialization: |
| 16 | Cluster cluster = Cluster.builder() |
| 17 | .addContactPoint("127.0.0.1") |
| 18 | .withQueryOptions(new QueryOptions().setFetchSize(2000)) |
| 19 | .build(); |
| 20 | |
| 21 | // Or at runtime: |
| 22 | cluster.getConfiguration().getQueryOptions().setFetchSize(2000); |
| 23 | ``` |
| 24 | |
| 25 | The fetch size can also be set on a statement: |
| 26 | |
| 27 | ```java |
| 28 | Statement statement = new SimpleStatement("your query"); |
| 29 | statement.setFetchSize(2000); |
| 30 | ``` |
| 31 | |
| 32 | If the fetch size is set on a statement, it will take precedence; |
| 33 | otherwise, the cluster-wide value (which defaults to 5000) will be used. |
| 34 | |
| 35 | Note that setting a fetch size doesn't mean that Cassandra will always |
| 36 | return the exact number of rows, it is possible that it returns slightly |
| 37 | more or less results. |
| 38 | |
| 39 | ### Result set iteration |
| 40 | |
| 41 | The fetch size limits the number of results that are returned in one |
| 42 | page; if you iterate past that, the driver will run background queries |
| 43 | to 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 | |
| 75 | By default, the background fetch happens at the last moment, when there |
| 76 | are 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 | |
| 83 | Here's how you could use these methods to pre-fetch the next page in |
| 84 | advance, in order to avoid the performance hit at the end of each page: |
| 85 | |
| 86 | ```java |
| 87 | ResultSet rs = session.execute("your query"); |
| 88 | for (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 | If you use paging with the async API, you'll also want to use those |
| 97 | methods to avoid triggering synchronous fetches unintentionally; see |
| 98 | [async paging](../async/#async-paging). |
| 99 | |
| 100 | |
| 101 | ### Saving and reusing the paging state |
| 102 | |
| 103 | Sometimes it is convenient to save the paging state in order to restore |
| 104 | it later. For example, consider a stateless web service that displays a |
| 105 | list of results with a link to the next page. When the user clicks that |
| 106 | link, we want to run the exact same query, except that the iteration |
| 107 | should start where we stopped on the previous page. |
| 108 | |
| 109 | To do so, the driver exposes a [PagingState][paging_state] object that represents |
| 110 | where we were in the result set when the last page was fetched: |
| 111 | |
| 112 | ```java |
| 113 | ResultSet resultSet = session.execute("your query"); |
| 114 | // iterate the result set... |
| 115 | PagingState pagingState = resultSet.getExecutionInfo().getPagingState(); |
| 116 | ``` |
| 117 | |
| 118 | This object can be serialized to a `String` or a byte array: |
| 119 | |
| 120 | ```java |
| 121 | String string = pagingState.toString(); |
| 122 | byte[] bytes = pagingState.toBytes(); |
| 123 | ``` |
| 124 | |
| 125 | This serialized form can be saved in some form of persistent storage to |
| 126 | be reused later. In our web service example, we would probably save the |
| 127 | string version as a query parameter in the URL to the next page |
| 128 | (`http://myservice.com/results?page=<...>`). When that value is |
| 129 | retrieved later, we can deserialize it and reinject it in a statement: |
| 130 | |
| 131 | ```java |
| 132 | PagingState pagingState = PagingState.fromString(string); |
| 133 | Statement st = new SimpleStatement("your query"); |
| 134 | st.setPagingState(pagingState); |
| 135 | ResultSet rs = session.execute(st); |
| 136 | ``` |
| 137 | |
| 138 | Note that the paging state can only be reused with the exact same |
| 139 | statement (same query string, same parameters). Also, it is an opaque |
| 140 | value that is only meant to be collected, stored an re-used. If you try |
| 141 | to modify its contents or reuse it with a different statement, the |
| 142 | driver will raise an error. |
| 143 | |
| 144 | Putting it all together, here's a more comprehensive example |
| 145 | implementation for our web service: |
| 146 | |
| 147 | ```java |
| 148 | final int RESULTS_PER_PAGE = 100; |
| 149 | |
| 150 | Statement st = new SimpleStatement("your query"); |
| 151 | st.setFetchSize(RESULTS_PER_PAGE); |
| 152 | |
| 153 | String requestedPage = extractPagingStateStringFromURL(); |
| 154 | // This will be absent for the first page |
| 155 | if (requestedPage != null) { |
| 156 | st.setPagingState( |
| 157 | PagingState.fromString(requestedPage)); |
| 158 | } |
| 159 | |
| 160 | ResultSet rs = session.execute(st); |
| 161 | PagingState 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 |
| 165 | int remaining = rs.getAvailableWithoutFetching(); |
| 166 | for (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 |
| 174 | if (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 | |
| 183 | Due to internal implementation details, `PagingState` instances are not |
| 184 | portable across [native protocol](../native_protocol/) versions. This |
| 185 | could 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 | |
| 196 | If this is not acceptable for you, you might want to consider the unsafe |
| 197 | API described in the next section. |
| 198 | |
| 199 | #### Unsafe API |
| 200 | |
| 201 | As an alternative to the standard API, there are two methods that |
| 202 | manipulate a raw `byte[]` instead of a `PagingState` object: |
| 203 | |
| 204 | * [ExecutionInfo#getPagingStateUnsafe()][gpsu] |
| 205 | * [Statement#setPagingStateUnsafe(byte[])][spsu] |
| 206 | |
| 207 | These low-level methods perform no validation on their arguments; |
| 208 | therefore nothing protects you from reusing a paging state that was |
| 209 | generated from a different statement, or altered in any way. This could |
| 210 | result in sending a corrupt paging state to Cassandra, with |
| 211 | unpredictable consequences (ranging from wrong results to a query |
| 212 | failure). |
| 213 | |
| 214 | There 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 | |
| 227 | Saving the paging state works well when you only let the user move from |
| 228 | one page to the next. But it doesn't allow random jumps (like "go |
| 229 | directly to page 10"), because you can't fetch a page unless you have |
| 230 | the 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)). |
| 233 | The rationale is that offset queries are inherently inefficient (the |
| 234 | performance will always be linear in the number of rows skipped), so the |
| 235 | Cassandra team doesn't want to encourage their use. |
| 236 | |
| 237 | If you really want offset queries, you can emulate them client-side. |
| 238 | You'll still get linear performance, but maybe that's acceptable for |
| 239 | your use case. For example, if each page holds 10 rows and you show at |
| 240 | most 20 pages, this means you'll fetch at most 190 extra rows, which |
| 241 | doesn't sound like a big deal. |
| 242 | |
| 243 | For example, if the page size is 10, the fetch size is 50, and the user |
| 244 | asks 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 | |
| 255 | You'll want to experiment with the fetch size to find the best balance: |
| 256 | too small means many background queries; too big means bigger messages |
| 257 | and too many unneeded rows returned (we picked 50 above for the sake of |
| 258 | example, but it's probably too small -- the default is 5000). |
| 259 | |
| 260 | Again, offset queries are inefficient by nature. Emulating them |
| 261 | client-side is a compromise when you think you can get away with the |
| 262 | performance 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. |