Elffuss BraidHub

kikocis/java-driver public

37a0d01b83e2 · 8.4 KiBRenderedRawPermalink
1## Frequently Asked Questions
2
3### How do I implement paging?
4
5When using [native protocol](../manual/native_protocol/) version 2 or
6higher, the driver automatically pages large result sets under the hood.
7You can also save the paging state to resume iteration later. See [this
8page](../manual/paging/) for more information.
9
10Native protocol v1 does not support paging, but you can emulate it in
11CQL with `LIMIT` and the `token()` function. See
12[this conversation](https://groups.google.com/a/lists.datastax.com/d/msg/java-driver-user/U2KzAHruWO4/6vDmUVDDkOwJ) on the mailing list.
13
14
15### Can I check if a conditional statement (lightweight transaction) was successful?
16
17When executing a conditional statement, the `ResultSet` will contain a single `Row` with a
18column named "applied" of type boolean. This tells whether the conditional statement was
19successful or not.
20
21The driver provides a convenience method [wasApplied] to check this on the result set directly:
22
23```java
24ResultSet rset = session.execute(conditionalStatement);
25rset.wasApplied();
26```
27
28You may also inspect the value yourself:
29
30```java
31ResultSet rset = session.execute(conditionalStatement);
32Row row = rset.one();
33row.getBool(0); // this is equivalent row.getBool("applied")
34```
35
36Note that, unlike manual inspection, `wasApplied` does not consume the first row.
37
38[wasApplied]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/ResultSet.html#wasApplied--
39
40
41### What is a parameterized statement and how can I use it?
42
43Starting with Cassandra 2.0, normal statements (that is non-prepared statements) do
44not need to concatenate parameter values inside a query string. Instead you can use
45`?` markers and provide the values separately:
46
47```java
48session.execute( "INSERT INTO contacts (email, firstname, lastname)
49 VALUES (?, ?, ?)", "clint.barton@hawkeye.com", "Barney", "Barton");
50```
51
52See [Simple statements](../manual/statements/simple/) for more information.
53
54
55### Does a parameterized statement escape parameters?
56
57A parameterized statement sends the values of parameters separate from the query
58(similar to the way a prepared statement does) as bytes so there is no need to escape
59parameters.
60
61
62### What's the difference between a parameterized statement and a Prepared statement?
63
64The only similarity between a parameterized statement and a prepared statement is in
65the way that the parameters are sent. The difference is that a prepared statement:
66
67* is already known on the cluster side (it has been compiled and there is an execution
68 plan available for it) which leads to better performance
69* sends only the statement id and its parameters (thus reducing the amount of data sent
70 to the cluster)
71
72See [Prepared statements](../manual/statements/prepared/) for more information.
73
74
75### Can I combine `PreparedStatements` and normal statements in a batch?
76
77Yes. A batch can include both bound statements and simple statements:
78
79```java
80PreparedStatement ps = session.prepare( "INSERT INTO contacts (email, firstname, lastname)
81 VALUES (?, ?, ?)");
82BatchStatement batch = new BatchStatement();
83batch.add(ps.bind(...));
84batch.add(ps.bind(...));
85// here's a simple statement
86batch.add(new SimpleStatement( "INSERT INTO contacts (email, firstname, lastname) VALUES (?, ?, ?)", ...));
87session.execute(batch);
88```
89
90
91### Why do my 'SELECT *' `PreparedStatement`-based queries stop working after a schema change?
92
93Both the driver and Cassandra maintain a mapping of `PreparedStatement` queries to their
94metadata. When a change is made to a table, such as a column being added or dropped, there
95is currently no mechanism for Cassandra to invalidate the existing metadata. Because of this,
96the driver is not able to properly react to these changes and will improperly read rows after
97a schema change is made.
98
99See [Prepared statements](../manual/statements/prepared) for more information.
100
101
102### Can I get the raw bytes of a text column?
103
104If you need to access the raw bytes of a text column, call the
105`Row.getBytesUnsafe("columnName")` method.
106
107Trying to use `Row.getBytes("columnName")` for the same purpose results in an
108exception, as the `getBytes` method can only be used if the column has the CQL type `BLOB`.
109
110
111### How do I increment counters with `QueryBuilder`?
112
113Considering the following query:
114
115```java
116UPDATE clickstream SET clicks = clicks + 1 WHERE userid = id;
117```
118
119To do this using `QueryBuilder`:
120
121```java
122Statement query = QueryBuilder.update("clickstream")
123 .with(incr("clicks", 1)) // Use incr for counters
124 .where(eq("userid", id));
125```
126
127
128### Is there a way to control the batch size of the results returned from a query?
129
130Use the `setFetchSize()` method on your `Statement` object. The fetch size controls
131how many resulting rows are retrieved simultaneously (the goal being to avoid
132loading too many results in memory for queries yielding large result sets).
133
134Keep in mind that if your code iterates the `ResultSet` entirely, the driver may
135run additional background queries to fetch the rest of the data. The fetch size
136only affects what is retrieved at a time, not the overall number of rows.
137
138See [Paging](../manual/paging/) for more information.
139
140
141### What's the difference between using `setFetchSize()` and `LIMIT`?
142
143Basically, `LIMIT` controls the maximum number of results returned by the query,
144while the `setFetchSize()` method controls the amount of data transferred at a time.
145
146For example, if you limit is 30 and your fetch size is 10, the `ResultSet` will contain
14730 rows, but under the hood the driver will perform 3 requests that will transfer 10
148rows each.
149
150See [Paging](../manual/paging/) for more information.
151
152
153### I'm reading a BLOB column and the driver returns incorrect data.
154
155Check your code to ensure that you read the returned `ByteBuffer` correctly. `ByteBuffer` is a very error-prone API,
156and we've had many reports where the problem turned out to be in user code.
157
158See [Blobs.java] in the `driver-examples` module for some examples and explanations.
159
160
161### Why am I seeing messages about `tombstone_warn_threshold` or `tombstone_fail_threshold` being exceeded in my Cassandra logs?
162
163Applications which use the object mapper or set `null` values in their
164statements may observe that many tombstones are being stored in their tables
165which subsequently may lead to poor query performance, failed queries, or
166columns being mysteriously deleted.
167
168This is caused by INSERT/UPDATE statements containing `null` values for columns
169that a user does not intend to change. Common circumstances around this come
170from using the object mapper or writing your own persistence layer and
171attempting to reuse the same `PreparedStatement` for inserting data, even with
172partial updates.
173
174Prior to cassandra 2.2, there was no means of reusing the same
175`PreparedStatement` for making partial updates to different columns.
176
177For example, given the following code:
178
179```java
180PreparedStatement prepared = session.prepare("INSERT INTO contacts (email, firstname, lastname) VALUES (?, ?, ?)");
181BoundStatement bound = prepared.bind();
182bound.set("email", "clint.barton@hawkeye.com");
183bound.set("firstname", "Barney");
184// creates a tombstone!!
185bound.set("lastname", null);
186```
187
188If one wanted to use this query to update only `firstname` this would not
189be achievable without binding the `lastname` parameter to `null`. This would
190have an undesired side effect of creating a tombstone for `lastname` and thus
191to the user giving the impression that `lastname` was deleted.
192
193In cassandra 2.2 and later with protocol v4, bind parameters (`?`) can
194optionally be left unset
195([CASSANDRA-7304]):
196
197 ```java
198 PreparedStatement prepared = session.prepare("INSERT INTO contacts (email, firstname, lastname) VALUES (?, ?, ?)");
199 BoundStatement bound = prepared.bind();
200 bound.set("email", "clint.barton@hawkeye.com");
201 bound.set("firstname", "Barney");
202 // lastname is left unset.
203 ```
204
205See [Parameters and Binding] for more details about unset parameters.
206
207Another possible root cause for this is using the object mapper and leaving
208fields set to `null`. This also causes tombstones to be inserted unless
209setting `saveNullFields` option to false. See [Mapper options] for more
210details.
211
212[Blobs.java]: https://github.com/datastax/java-driver/tree/3.0.x/driver-examples/src/main/java/com/datastax/driver/examples/datatypes/Blobs.java
213[CASSANDRA-7304]: https://issues.apache.org/jira/browse/CASSANDRA-7304
214[Parameters and Binding]: ../manual/statements/prepared/#parameters-and-binding
215[Mapper options]: ../manual/object_mapper/using/#mapper-options