Elffuss BraidHub

kikocis/java-driver public

3.1.x · 8.7 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[Blobs.java]: https://github.com/datastax/java-driver/tree/3.x/driver-examples/src/main/java/com/datastax/driver/examples/datatypes/Blobs.java
161
162
163### How do I use the driver in an OSGi application?
164
165Read our [OSGi-specific FAQ section](osgi/) to find out.
166
167
168### Why am I seeing messages about `tombstone_warn_threshold` or `tombstone_fail_threshold` being exceeded in my Cassandra logs?
169
170Applications which use the object mapper or set `null` values in their
171statements may observe that many tombstones are being stored in their tables
172which subsequently may lead to poor query performance, failed queries, or
173columns being mysteriously deleted.
174
175This is caused by INSERT/UPDATE statements containing `null` values for columns
176that a user does not intend to change. Common circumstances around this come
177from using the object mapper or writing your own persistence layer and
178attempting to reuse the same `PreparedStatement` for inserting data, even with
179partial updates.
180
181Prior to cassandra 2.2, there was no means of reusing the same
182`PreparedStatement` for making partial updates to different columns.
183
184For example, given the following code:
185
186```java
187PreparedStatement prepared = session.prepare("INSERT INTO contacts (email, firstname, lastname) VALUES (?, ?, ?)");
188BoundStatement bound = prepared.bind();
189bound.set("email", "clint.barton@hawkeye.com");
190bound.set("firstname", "Barney");
191// creates a tombstone!!
192bound.set("lastname", null);
193```
194
195If one wanted to use this query to update only `firstname` this would not
196be achievable without binding the `lastname` parameter to `null`. This would
197have an undesired side effect of creating a tombstone for `lastname` and thus
198to the user giving the impression that `lastname` was deleted.
199
200In cassandra 2.2 and later with protocol v4, bind parameters (`?`) can
201optionally be left unset
202([CASSANDRA-7304]):
203
204 ```java
205 PreparedStatement prepared = session.prepare("INSERT INTO contacts (email, firstname, lastname) VALUES (?, ?, ?)");
206 BoundStatement bound = prepared.bind();
207 bound.set("email", "clint.barton@hawkeye.com");
208 bound.set("firstname", "Barney");
209 // lastname is left unset.
210 ```
211
212See [Parameters and Binding] for more details about unset parameters.
213
214Another possible root cause for this is using the object mapper and leaving
215fields set to `null`. This also causes tombstones to be inserted unless
216setting `saveNullFields` option to false. See [Mapper options] for more
217details.
218
219[Blobs.java]: https://github.com/datastax/java-driver/tree/3.0.x/driver-examples/src/main/java/com/datastax/driver/examples/datatypes/Blobs.java
220[CASSANDRA-7304]: https://issues.apache.org/jira/browse/CASSANDRA-7304
221[Parameters and Binding]: ../manual/statements/prepared/#parameters-and-binding
222[Mapper options]: ../manual/object_mapper/using/#mapper-options