Elffuss BraidHub

kikocis/java-driver public

f8d7c8f27f45 · 2.5 KiBRenderedRawPermalink
1## Query timestamps
2
3In Cassandra, each mutation has a microsecond-precision timestamp, which
4is used to order operations relative to each other.
5
6There are various ways to assign it:
7
8### Server-side generation
9
10If the client does not specify any timestamp, the server will assign one
11based on the time it receives the query.
12
13This can be a problem when the order of the writes matter: with unlucky
14timing (different coordinators, network latency, etc.), two successive
15requests from the same client might be processed in a different order
16server-side, and end up with out-of-order timestamps.
17
18### CQL `USING TIMESTAMP`
19
20You can explicitly provide the timestamp in your CQL query:
21
22```java
23session.execute("INSERT INTO my_table(c1, c2) values (1, 1) " +
24 "USING TIMESTAMP 1432815430948040");
25```
26
27This solves the problems of server-side generation: the client has
28control over the ordering of the statements it generates. On the other
29hand, it puts the burden of generating timestamps on client code.
30
31### Client-side generation
32
33Starting with version 2.1.2 of the driver, and if [native
34protocol](../native_protocol/) v3 or above is in use, a *default
35timestamp* can be sent with each query.
36
37To enable this feature, provide an instance of [TimestampGenerator][tsg]
38at initialization:
39
40```java
41Cluster.builder().addContactPoint("127.0.0.1")
42 .withTimestampGenerator(new AtomicMonotonicTimestampGenerator())
43 .build();
44```
45
46The default is still server-side generation. So unless you explicitly
47provide a generator, you get the same behavior as previous driver
48versions.
49
50In addition, you can also override the default timestamp on a
51per-statement basis:
52
53```java
54Statement statement = new SimpleStatement(
55 "UPDATE users SET email = 'x@y.com' where id = 1");
56statement.setDefaultTimestamp(1234567890);
57session.execute(statement);
58```
59
60[tsg]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/TimestampGenerator.html
61
62### Summary
63
64As shown in the previous sections, there are multiple ways to provide a
65timestamp, some of which overlap. The order of precedence is the
66following:
67
681. if there is a `USING TIMESTAMP` clause in the CQL string, use that
69 over anything else;
702. otherwise, if a default timestamp was set on the statement and is
71 different from `Long.MIN_VALUE`, use it;
723. otherwise, if a generator is specified, invoke it and use its result
73 if it is different from `Long.MIN_VALUE`;
744. otherwise, let the server assign the timestamp.
75
76Steps 2 and 3 only apply if native protocol v3 or above is in use.