Skip to content

Instantly share code, notes, and snippets.

@jeromatron
Created May 30, 2013 17:26
Show Gist options
  • Save jeromatron/5679624 to your computer and use it in GitHub Desktop.
Save jeromatron/5679624 to your computer and use it in GitHub Desktop.
Basic encode/decode of composite values with DataStax Java driver
package org.mostlyharmless;
import com.datastax.driver.core.*;
import org.apache.cassandra.db.marshal.*;
import java.util.ArrayList;
import java.util.List;
public class SimpleClient {
private Cluster cluster;
private Session session;
private static final CompositeType composite;
static {
List<AbstractType<?>> subComparators = new ArrayList<AbstractType<?>>();
subComparators.add(BooleanType.instance);
subComparators.add(LongType.instance);
subComparators.add(LongType.instance);
subComparators.add(BytesType.instance);
subComparators.add(UTF8Type.instance);
subComparators.add(AsciiType.instance);
composite = CompositeType.getInstance(subComparators);
}
public static void main(String[] args) {
SimpleClient client = new SimpleClient();
client.connect("localhost");
client.insert();
client.query();
client.close();
}
public void connect(String node) {
cluster = Cluster.builder()
.addContactPoint(node).build();
Metadata metadata = cluster.getMetadata();
System.out.printf("Connected to cluster: %s\n",
metadata.getClusterName());
for ( Host host : metadata.getAllHosts() ) {
System.out.printf("Datacenter: %s; Host: %s; Rack: %s\n",
host.getDatacenter(), host.getAddress(), host.getRack());
}
session = cluster.connect("test");
}
public void insert() {
PreparedStatement statement =
session.prepare("INSERT INTO cskids (key, column1, value) VALUES (?, ?, ?);");
BoundStatement boundStatement = new BoundStatement(statement);
session.execute(boundStatement.bind(
"cskid4",
"",
composite.fromString("true:101:303:232345:Hi:There")
));
}
public void query() {
ResultSet results = session.execute("SELECT * FROM cskids");
for (Row row : results) {
System.out.println("For row: " + row);
System.out.println("-- Key: " + row.getString("key"));
System.out.println("-- Value: " + composite.getString(row.getBytesUnsafe("value")));
}
System.out.println();
}
public void close() {
cluster.shutdown();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment