Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Cassandra summit 2013 - DataStax Java Driver Unleashed!

3,313 views

Published on

Published in: Technology
  • Be the first to comment

Cassandra summit 2013 - DataStax Java Driver Unleashed!

  1. 1. DataStax Java Driver Unleashed!
  2. 2. CQL The new face of Cassandra* CQL3* Simpler Data Model using Denormalized Tables* SQL-like Query Language* Schema Definition* CQL Native Protocol* Introduced in Cassandra 1.2* Designed for CQL3* Thrift will keep being supported by Cassandra
  3. 3. * Cassandra lives closer to users and application* Data model expresses your application intent* Not made for generalizable queries* Key to a successful projectCQL Data Model Overview
  4. 4. CQL3 Data ModelData duplicated over several tablesCQL3 Query Languagecomes with a new DataModel abstractionmade of denormalized,statically defined tables
  5. 5. CQL3 Data Modelgmasonuser_id1735tweet_idphenryauthorGive me liberty or give me deathbodyPartitionKeygmason 1742 gwashington I chopped down the cherry treeahamilton 1767 jadams A government of laws, not menahamilton 1794 gwashington I chopped down the cherry treeClusteringKeyTimeline Table
  6. 6. CQL3 Data Modelgmasonuser_id1735tweet_idphenryauthorGive me liberty or give me deathbodyPartitionKeygmason 1742 gwashington I chopped down the cherry treeahamilton 1767 jadams A government of laws, not menahamilton 1794 gwashington I chopped down the cherry treeClusteringKeyTimeline TableCREATE TABLE timeline (user_id varchar,tweet_id timeuuid,author varchar,body varchar,PRIMARY KEY (user_id, tweet_id));CQL
  7. 7. DB APICQL Native ProtocolCQL API OO APINext Generation DriverNew Driver Architecture
  8. 8. * Reference Implementation* Asynchronous architecture based on Netty* Prepared Statements Support* Automatic Fail-over* Node Discovery* Cassandra Tracing Support* Tunable PoliciesJava Driver Overview
  9. 9. ClientWithoutRequest PipeliningCassandraClient CassandraWithRequest PipeliningRequest Pipelining
  10. 10. ClientWithoutNotificationsWithNotificationsNodeNodeNodeClientNodeNodeNodeNotifications
  11. 11. ClientThreadNodeNodeNodeClientThreadClientThreadNodeDriverAsynchronous Architecture
  12. 12. 123456ClientThreadNodeNodeNodeClientThreadClientThreadNodeDriverAsynchronous Architecture
  13. 13. contactPoints = {“10.0.0.1”,”10.0.0.2”}keyspace = “videodb”public VideoDbBasicImpl(List<String> contactPoints, String keyspace) {cluster = Cluster.builder().addContactPoints(! contactPoints.toArray(new String[contactPoints.size()])).build();session = cluster.connect(keyspace);}Creating a Basic Connection
  14. 14. public void setUserByUsingString(User user) {StringBuffer userInsert = new StringBuffer("INSERT INTO users (username, firstname, lastname, email, password, created_date) VALUES (");userInsert.append("" + user.getUsername() + "");userInsert.append("" + user.getFirstname() + "");userInsert.append("" + user.getLastname() + "");userInsert.append("" + user.getEmail() + "");userInsert.append("" + user.getPassword() + "");userInsert.append("" + user.getCreated_date().toString() + "");userInsert.append(")");session.execute(userInsert.toString());}Basic write using insert
  15. 15. ! public User getUserByUsernameUsingString(String username) {! ! User user = new User();! ! ResultSet rs = session.execute("SELECT * FROM users WHERE username = "! ! ! ! + username + "");! ! // A result set has Rows which can be iterated over! ! for (Row row : rs) {! ! ! user.setUsername(username);! ! ! user.setFirstname(row.getString("firstname"));! ! ! user.setLastname(row.getString("lastname"));! ! ! user.setEmail(row.getString("email"));! ! ! user.setPassword(row.getString("Password"));! ! ! user.setCreated_date(row.getDate("created_date"));! ! }! ! return user;! }Basic Read using Select
  16. 16. public void setUserByPreparedStatement(User user) {BoundStatement bs = setUser.bind();bs.setString("username", user.getUsername());bs.setString("firstname", user.getFirstname());bs.setString("lastname", user.getLastname());bs.setString("email", user.getEmail());bs.setString("password", user.getPassword());bs.setDate("created_date", user.getCreated_date());! !session.execute(bs);}Writing with Prepared Statements
  17. 17. public List<Video> getVideosByUsernameUsingAsyncRead(String username) {BoundStatement bs = getVideosByUsernamePreparedStatement.bind();List<ResultSetFuture> futures = new ArrayList<ResultSetFuture>();List<Video> videos = new ArrayList<Video>();bs.setString("username", username);for (Row row : session.execute(bs)) {futures.add(session.executeAsync(getVideoByIDPreparedStatement.bind(row.getUUID("videoid"))));}for (ResultSetFuture future : futures) {for (Row row : future.getUninterruptibly()) {Video video = new Video();video.setVideoid(row.getUUID("videoid"));videos.add(video);}}return videos;}Asynchronous Read
  18. 18. for (String tag : tags) {BoundStatement bs = getVideosByTagPreparedStatement.bind(tag);final ResultSetFuture future = session.executeAsync(bs);future.addListener(new Runnable() {public void run() {for (Row row : future.getUninterruptibly()) {UUID videoId = row.getUUID("videoid");if (videoIds.putIfAbsent(videoId, PRESENT) == null) {videoFutures.add(session.executeAsync(getVideoByIDPreparedStatement.bind(videoId)));}}}}, executor);}Performing a Read with a Listener
  19. 19. public Video getVideoByIdUsingQueryBuilder(String videoId) {Video video = new Video();Query query = select().all().from("videodb", "videos").where(eq("videoId", videoId)).limit(10);query.setConsistencyLevel(ConsistencyLevel.ONE);ResultSet rs = session.execute(query);for (Row row : rs) {video.setVideoid(row.getUUID("videoid"));video.setVideoname(row.getString("videoName"));video.setUsername(row.getString("username"));video.setDescription(row.getString("description"));}return video;}Using the Query Builder
  20. 20. LoadBalancingPolicyNodeNodeNodeHealthMonitorLoad Balancing and FailoverReconnectionNotificationsClientRetryPolicyResponseDispatcher1 32456
  21. 21. NodeNodeNodeClientDatacenter BNodeNodeNodeClientClientClientClientClientDatacenter ALocal nodes are queriedfirst, if non are available,the request will be sentto a remote node.Multi Datacenter Load Balancing
  22. 22. Multi Datacenter Load BalancingNodeNodeReplicaNodeClient NodeNodeReplicaReplicaNodes that own aReplica of the databeing read or writtenby the query will becontacted first.
  23. 23. contactPoints = {“10.0.0.1”,”10.0.0.2”}keyspace = “videodb”public VideoDbBasicImpl(List<String> contactPoints, String keyspace) {cluster = Cluster.builder().addContactPoints(! contactPoints.toArray(new String[contactPoints.size()])).withLoadBalancingPolicy(Policies.defaultLoadBalancingPolicy()).build();session = cluster.connect(keyspace);}Create your own policy!Add a Load Balancing Policy
  24. 24. ClientIf the requestedConsistency Levelcannot be reached(QUORUM here), asecond request with alower CL is sentautomatically.NodeNode ReplicaReplicaNodeReplicaDowngrading Retry Policy
  25. 25. contactPoints = {“10.0.0.1”,”10.0.0.2”}keyspace = “videodb”public VideoDbBasicImpl(List<String> contactPoints, String keyspace) {cluster = Cluster.builder().addContactPoints(! contactPoints.toArray(new String[contactPoints.size()])).withLoadBalancingPolicy(Policies.defaultLoadBalancingPolicy()).withRetryPolicy(Policies.defaultRetryPolicy()).build();session = cluster.connect(keyspace);}Create your own policy!Specify a Retry Policy
  26. 26. public enum Gender { @EnumValue("m") MALE, @EnumValue("f") FEMALE;}@Table(name = "user")public class User { @PartitionKey @Column(name = "user_id") private String userId; private String name; private String email; private Gender gender;}Object Mapping
  27. 27. DevCenter an IDE for Developers
  28. 28. Questions ?

×