Cassandra 2.0 database for
Java local client access to Cassandra, first building Java engineering, using MAVEN for management.
Introduce dependencies:
<dependency> <groupId>com.datastax.cassandra</groupId> <artifactId> Cassandra-driver-core</artifactid> <version>2.1.0</version></dependency>
1. Like Elasticsearch, the client now constructs a cluster object:
Cluster Cluster = Cluster.builder () . Addcontactpoint ("Your IP") . Build (); Metadata Metadata = Cluster.getmetadata (); System.out.printf ("Connected to cluster:%s\n", metadata.getclustername ()); For (Host host:metadata.getAllHosts ()) { System.out.printf ("Datatacenter:%s; Host:%s; Rack:%s\n ", host.getdatacenter (), host.getaddress (), Host.getrack ()); }
2. Through a Session object, to achieve the Cassandra of all additions and deletions to change.
Session session = Cluster.connect ();
3. Implement all DML operations through the session object. (PS: Before you operate on Cassandra, it is recommended to understand the architecture of Cassandra and the organization of data)
A. We first create a schema:
<pre name= "code" class= "java" >resultset results = Session.execute ("SELECT * from simplex.playlists"); System.out.println (String.Format ("%-30s\t%-20s\t%-20s\n%s", "title", "album", "Artist", "-------------------- -----------+-----------------------+--------------------")); for (Row row:results) { System.out.println (String.Format ("%-30s\t%-20s\t%-20s", Row.getstring ("title"), Row.getstring ("album"), Row.getstring ("artist")); } System.out.println ();
Session.execute ("CREATE keyspace simplex with replication" + "= {' class ': ' Simplestrategy ', ' Replication_factor ': 3};");
B. Create a table:
Session.execute (" CREATE TABLE simplex.songs (" + " ID uuid PRIMARY KEY," + " title text," + "album text," + "artist text," + "tags set<text>," + "data blob" + ");
c. Inserting data:
Session.execute ( "INSERT into Simplex.songs (ID, title, album, Artist, Tags)" + " VALUES (" + "756716f7-2e54- 4715-9F00-91DCBEA6CF50, "+ " ' La Petite tonkinoise ', "+ " ' Bye Bye Blackbird ', "+ " ' Joséphine Baker ', "+ "{' Jazz ', '} ')" + ";");
D. Querying data:
ResultSet results = Session.execute ("SELECT * from simplex.playlists"); System.out.println (String.Format ("%-30s\t%-20s\t%-20s\n%s", "title", "album", "Artist", "-------------------- -----------+-----------------------+--------------------")); for (Row row:results) { System.out.println (String.Format ("%-30s\t%-20s\t%-20s", Row.getstring ("title"), Row.getstring ("album"), Row.getstring ("artist")); } System.out.println ();
Cassandra Database Java Access