SlideShare a Scribd company logo
Getting Started with DataStax .NET
Driver
Luke Tillman
Language Evangelist
@LukeTillman
Life as the .NET Language Evangelist
Where do I get the driver?
• NuGet
• GitHub
• https://github.com/datastax/csharp-driver
Bootstrapping the Driver
Cluster
• Singleton - one per application
• Use the Builder
Cluster cluster = Cluster.Builder()
.AddContactPoint("127.0.0.1")
.Build();
Cluster
• Fluent Interface with Lots of Options
var authProvider = new PlainTextAuthProvider("username", "password");
var queryOptions = new QueryOptions()
.SetConsistencyLevel(ConsistencyLevel.LocalQuorum)
.SetPageSize(1000);
Cluster cluster = Cluster.Builder().AddContactPoint("127.0.0.1")
.WithSSL()
.WithQueryOptions(queryOptions)
.WithAuthProvider(authProvider)
.Build();
Session
• Singleton per keyspace
• Inspired by the (N)Hibernate session object
• Get it from your Cluster object
ISession session = cluster.Connect("killrvideo");
Sample IoC Container Registration
// Use the Cluster builder to create a cluster
Cluster cluster = Cluster.Builder().AddContactPoint("127.0.0.1").Build();
// Use the cluster to connect a session to the appropriate keyspace
ISession session = cluster.Connect("killrvideo");
// Register both Cluster and ISession instances with Windsor (as
// Singletons since it will reuse the instance)
container.Register(
Component.For<Cluster>().Instance(cluster),
Component.For<ISession>().Instance(session)
);
Creating Statements
Types of Statements
• SimpleStatement
• PreparedStatement / BoundStatement
• BatchStatement
SimpleStatement
• It’s… simple?
• Can use bind parameters
• Useful for one-off statements or dynamic CQL where
you can’t prepare it
var statement =
new SimpleStatement("SELECT * FROM users WHERE userid = ?");
statement = statement.Bind(145);
PreparedStatement / BoundStatement
• Pay the cost of Prepare once (server roundtrip)
• Save the PreparedStatement instance and reuse
PreparedStatement prepared = session.Prepare(
"SELECT * FROM user_credentials WHERE email = ?");
PreparedStatement / BoundStatement
• Bind variable values to get BoundStatement for
execution
• Execution only has to send variable values
• You will use these all the time
BoundStatement bound =
prepared.Bind("luke.tillman@datastax.com");
BatchStatement
• Add Simple/Bound statements to a batch
BoundStatement bound = prepared.Bind(video.VideoId, video.Name);
var simple = new SimpleStatement(
"UPDATE videos SET name = ? WHERE videoid = ?"
).Bind(video.Name, video.VideoId);
// Use an atomic batch to send over all the mutations
var batchStatement = new BatchStatement();
batchStatement.Add(bound);
batchStatement.Add(simple);
BatchStatement
• Batches are Logged, atomic (by default) and this is
the most common use case
• Set the batch type to use a different type of batch
• Counters have their own batch type (can’t mix)
var batch =
new BatchStatement().SetBatchType(BatchType.Unlogged);
Statements – You’ve Got Options
• Simple and Bound statements have options that can
be set at the Statement level
• Consistency Level
• Retry Policy
• Paging Size (for automatic paging, we’ll come back to this)
• Tracing
• If not set at the statement level, defaults set when
configuring/building the Cluster are used
Statements – You’ve Got Options
• Example of binding a PreparedStatement and setting
available options:
IStatement bound =
prepared.Bind("luke.tillman@datastax.com")
.SetPageSize(100)
.SetConsistencyLevel(ConsistencyLevel.LocalOne)
.SetRetryPolicy(new DefaultRetryPolicy())
.EnableTracing();
Executing Statements and Getting the
Results
Executing Statements
• Use your Session object to execute statements
• You can execute statements synchronously or
asynchronously
• Synchronous
• Asynchronous
• Execute methods return a RowSet
RowSet rows = await _session.ExecuteAsync(boundStatement);
RowSet rows = _session.Execute(boundStatement);
RowSet
• RowSet implements IEnumerable<Row>
• Use GetValue<T> method on a Row to get a
column’s value
• By column name
• By ordinal (position)
RowSet
• Because RowSet implements IEnumerable<Row>:
• Iterate with foreach
RowSet rows = await _session.ExecuteAsync(boundStatement);
foreach (Row row in rows)
{
returnList.Add(new VideoPreview
{
VideoId = row.GetValue<Guid>("videoid"),
AddedDate = row.GetValue<DateTimeOffset>("added_date"),
Name = row.GetValue<string>("name")
});
}
RowSet
• Because RowSet implements IEnumerable<Row>:
• Project Rows with LINQ to Objects Select()
RowSet rows = await _session.ExecuteAsync(boundStatement);
var returnList = rows.Select(row => new VideoPreview
{
VideoId = row.GetValue<Guid>(0),
AddedDate = row.GetValue<DateTimeOffset>(1),
Name = row.GetValue<string>(2)
}).ToList();
RowSet
• Because RowSet implements IEnumerable<Row>:
• Get a single row with LINQ to Objects Single() or
SingleOrDefault()
RowSet rows = await _session.ExecuteAsync(boundStatement);
Row row = rows.SingleOrDefault();
CQL 3 Data Types to .NET Types
Full listing available in driver docs
CQL 3 Data Type .NET Type
bigint, counter long
boolean bool
decimal, float float
double double
int int
uuid, timeuuid System.Guid
text, varchar string (Encoding.UTF8)
timestamp System.DateTimeOffset
varint System.Numerics.BigIntege
r
Driver 2.0 Features
Lightweight Transactions (LWT)
• Use when you don’t want writes to step on each
other
• AKA Linearizable Consistency
• Serial Isolation Level
• Be sure to read the fine print: has a latency cost
associated with using it, so use only where needed
• The canonical example: unique user accounts
Lightweight Transactions (LWT)
• Returns a column called [applied] indicating
success/failure
• Different from the relational world where you might
expect an Exception (i.e.
var statement = new SimpleStatement("INSERT INTO user_credentials (email,
password) VALUES (?, ?) IF NOT EXISTS");
statement = statement.Bind("user1@killrvideo.com", "Password1!");
RowSet rows = await _session.ExecuteAsync(statement);
var userInserted = rows.Single().GetValue<bool>("[applied]");
Automatic Paging
• The Problem: Loading big result sets into memory is
a recipe for disaster (OutOfMemoryExceptions, etc.)
• Better to load and process a large result set in pages
(chunks)
• Doing this manually with Cassandra prior to 2.0 was
a pain
Automatic Paging
• Set a page size on a statement (or will use default from
Cluster)
• Iterate over the resulting RowSet
• As you iterate, new pages are fetched transparently when
the Rows in the current page are exhausted
• Will allow you to iterate until all pages are exhausted
boundStatement = boundStatement.SetPageSize(100);
RowSet rows = await _session.ExecuteAsync(boundStatement);
foreach (Row row in rows)
{
}
Typical Pager UI in a Web Application
• Show page of records in UI and allow user to
navigate
Typical Pager UI in a Web Application
• Automatic Paging – this is not the feature you are
looking for
Where To Go From Here
LINQ to CQL
• Comes in the NuGet package as
Cassandra.Data.Linq
• Has support for all CRUD operations
• Start by decorating the objects you’ll be querying
with Table, Column, and PartitionKey attributes
LINQ to CQL
[Table("user_credentials")]
public class UserCredentials
{
[Column("email")]
[PartitionKey]
public string EmailAddress { get; set; }
[Column("password")]
public string Password { get; set; }
[Column("userid")]
public Guid UserId { get; set; }
}
LINQ to CQL
• Then query with LINQ using the Session’s
GetTable<T> method as your starting point
public UserCredentials GetCredentials(string emailAddress)
{
IEnumerable<UserCredentials> results =
_session.GetTable<UserCredentials>()
.Where(uc => uc.EmailAddress == emailAddress)
.Execute();
return results.SingleOrDefault();
}
ADO.NET Support
• Available in the NuGet package as Cassandra.Data
• Allows you to use your “favorite” ADO.NET objects
like DbConnection, DbCommand, etc. to query
Cassandra
• My recommendation? Avoid it.
• Cassandra concepts don’t always map well to
The KillrVideo Sample Application
• Many of this presentation’s samples are taken from
here
• https://github.com/luketillman/killrvideo-csharp
What Next?
• Data Modeling, Data Modeling, Data Modeling
• Planet Cassandra (http://www.planetcassandra.org)
• Links to videos, drivers, documentation, tutorials, etc.
• 2.1 Beta Available (support for User Defined Types)
Follow me on Twitter for updates: @LukeTillman

More Related Content

PDF
【Unity】Scriptable object 入門と活用例
PDF
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
PDF
High Performance Core Data
PDF
Core Data with multiple managed object contexts
PDF
Multithreading on iOS
PDF
Multithreading and Parallelism on iOS [MobOS 2013]
PDF
So you want to liberate your data?
PDF
Bonjour, iCloud
【Unity】Scriptable object 入門と活用例
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
High Performance Core Data
Core Data with multiple managed object contexts
Multithreading on iOS
Multithreading and Parallelism on iOS [MobOS 2013]
So you want to liberate your data?
Bonjour, iCloud

What's hot (20)

PDF
Apache Zookeeper
PPTX
Grand Central Dispatch
PPTX
Python database interfaces
PPT
iOS Multithreading
PDF
Adventures in Multithreaded Core Data
PPTX
JS Fest 2019/Autumn. Maciej Treder. Angular Schematics - Develop for developers
PPTX
MongoDB: tips, trick and hacks
KEY
Data perisistence in iOS
PDF
Python in the database
PPTX
Kotlin coroutines and spring framework
PPTX
Hazelcast
PDF
NoSQL and JavaScript: a Love Story
PDF
Cassandra summit 2013 - DataStax Java Driver Unleashed!
KEY
Grand Central Dispatch Design Patterns
PDF
Building data flows with Celery and SQLAlchemy
PDF
Pycon 2012 Apache Cassandra
PPTX
Cassandra 2.2 & 3.0
PPTX
Hadoop Puzzlers
PDF
Beginning icloud development - Cesare Rocchi - WhyMCA
KEY
Threading in iOS / Cocoa Touch
Apache Zookeeper
Grand Central Dispatch
Python database interfaces
iOS Multithreading
Adventures in Multithreaded Core Data
JS Fest 2019/Autumn. Maciej Treder. Angular Schematics - Develop for developers
MongoDB: tips, trick and hacks
Data perisistence in iOS
Python in the database
Kotlin coroutines and spring framework
Hazelcast
NoSQL and JavaScript: a Love Story
Cassandra summit 2013 - DataStax Java Driver Unleashed!
Grand Central Dispatch Design Patterns
Building data flows with Celery and SQLAlchemy
Pycon 2012 Apache Cassandra
Cassandra 2.2 & 3.0
Hadoop Puzzlers
Beginning icloud development - Cesare Rocchi - WhyMCA
Threading in iOS / Cocoa Touch
Ad

Similar to Getting Started with Datatsax .Net Driver (20)

PPTX
Cassandra Day NY 2014: Getting Started with the DataStax C# Driver
PDF
Introduction to .Net Driver
PDF
Cassandra Summit 2014: Highly Scalable Web Application in the Cloud with Cass...
PPTX
ORM - Ivan Marković
PPT
MySQL, LINQ and the ADO_NET Entity Framework Presentation.ppt
PDF
Getting started with DataStax .NET Driver for Cassandra
PDF
Going native with Apache Cassandra
KEY
Introducing LINQ
PDF
Top 10 Best Practices for Apache Cassandra and DataStax Enterprise
PPT
Introduction to NHibernate
PDF
FOSSASIA 2015 - 10 Features your developers are missing when stuck with Propr...
PDF
Hibernate performance tuning
PPT
B_110500002
PDF
Paris Cassandra Meetup - Cassandra for Developers
PPTX
In memory databases presentation
PPT
W-JAX Performance Workshop - Database Performance
PDF
YaJug - Cassandra for Java Developers
PDF
Cassandra drivers and libraries
PDF
70487.pdf
Cassandra Day NY 2014: Getting Started with the DataStax C# Driver
Introduction to .Net Driver
Cassandra Summit 2014: Highly Scalable Web Application in the Cloud with Cass...
ORM - Ivan Marković
MySQL, LINQ and the ADO_NET Entity Framework Presentation.ppt
Getting started with DataStax .NET Driver for Cassandra
Going native with Apache Cassandra
Introducing LINQ
Top 10 Best Practices for Apache Cassandra and DataStax Enterprise
Introduction to NHibernate
FOSSASIA 2015 - 10 Features your developers are missing when stuck with Propr...
Hibernate performance tuning
B_110500002
Paris Cassandra Meetup - Cassandra for Developers
In memory databases presentation
W-JAX Performance Workshop - Database Performance
YaJug - Cassandra for Java Developers
Cassandra drivers and libraries
70487.pdf
Ad

More from DataStax Academy (20)

PDF
Forrester CXNYC 2017 - Delivering great real-time cx is a true craft
PPTX
Introduction to DataStax Enterprise Graph Database
PPTX
Introduction to DataStax Enterprise Advanced Replication with Apache Cassandra
PPTX
Cassandra on Docker @ Walmart Labs
PDF
Cassandra 3.0 Data Modeling
PPTX
Cassandra Adoption on Cisco UCS & Open stack
PDF
Data Modeling for Apache Cassandra
PDF
Coursera Cassandra Driver
PDF
Production Ready Cassandra
PDF
Cassandra @ Netflix: Monitoring C* at Scale, Gossip and Tickler & Python
PPTX
Cassandra @ Sony: The good, the bad, and the ugly part 1
PPTX
Cassandra @ Sony: The good, the bad, and the ugly part 2
PDF
Standing Up Your First Cluster
PDF
Real Time Analytics with Dse
PDF
Introduction to Data Modeling with Apache Cassandra
PDF
Cassandra Core Concepts
PPTX
Enabling Search in your Cassandra Application with DataStax Enterprise
PPTX
Bad Habits Die Hard
PDF
Advanced Data Modeling with Apache Cassandra
PDF
Advanced Cassandra
Forrester CXNYC 2017 - Delivering great real-time cx is a true craft
Introduction to DataStax Enterprise Graph Database
Introduction to DataStax Enterprise Advanced Replication with Apache Cassandra
Cassandra on Docker @ Walmart Labs
Cassandra 3.0 Data Modeling
Cassandra Adoption on Cisco UCS & Open stack
Data Modeling for Apache Cassandra
Coursera Cassandra Driver
Production Ready Cassandra
Cassandra @ Netflix: Monitoring C* at Scale, Gossip and Tickler & Python
Cassandra @ Sony: The good, the bad, and the ugly part 1
Cassandra @ Sony: The good, the bad, and the ugly part 2
Standing Up Your First Cluster
Real Time Analytics with Dse
Introduction to Data Modeling with Apache Cassandra
Cassandra Core Concepts
Enabling Search in your Cassandra Application with DataStax Enterprise
Bad Habits Die Hard
Advanced Data Modeling with Apache Cassandra
Advanced Cassandra

Getting Started with Datatsax .Net Driver

  • 1. Getting Started with DataStax .NET Driver Luke Tillman Language Evangelist @LukeTillman
  • 2. Life as the .NET Language Evangelist
  • 3. Where do I get the driver? • NuGet • GitHub • https://github.com/datastax/csharp-driver
  • 5. Cluster • Singleton - one per application • Use the Builder Cluster cluster = Cluster.Builder() .AddContactPoint("127.0.0.1") .Build();
  • 6. Cluster • Fluent Interface with Lots of Options var authProvider = new PlainTextAuthProvider("username", "password"); var queryOptions = new QueryOptions() .SetConsistencyLevel(ConsistencyLevel.LocalQuorum) .SetPageSize(1000); Cluster cluster = Cluster.Builder().AddContactPoint("127.0.0.1") .WithSSL() .WithQueryOptions(queryOptions) .WithAuthProvider(authProvider) .Build();
  • 7. Session • Singleton per keyspace • Inspired by the (N)Hibernate session object • Get it from your Cluster object ISession session = cluster.Connect("killrvideo");
  • 8. Sample IoC Container Registration // Use the Cluster builder to create a cluster Cluster cluster = Cluster.Builder().AddContactPoint("127.0.0.1").Build(); // Use the cluster to connect a session to the appropriate keyspace ISession session = cluster.Connect("killrvideo"); // Register both Cluster and ISession instances with Windsor (as // Singletons since it will reuse the instance) container.Register( Component.For<Cluster>().Instance(cluster), Component.For<ISession>().Instance(session) );
  • 10. Types of Statements • SimpleStatement • PreparedStatement / BoundStatement • BatchStatement
  • 11. SimpleStatement • It’s… simple? • Can use bind parameters • Useful for one-off statements or dynamic CQL where you can’t prepare it var statement = new SimpleStatement("SELECT * FROM users WHERE userid = ?"); statement = statement.Bind(145);
  • 12. PreparedStatement / BoundStatement • Pay the cost of Prepare once (server roundtrip) • Save the PreparedStatement instance and reuse PreparedStatement prepared = session.Prepare( "SELECT * FROM user_credentials WHERE email = ?");
  • 13. PreparedStatement / BoundStatement • Bind variable values to get BoundStatement for execution • Execution only has to send variable values • You will use these all the time BoundStatement bound = prepared.Bind("luke.tillman@datastax.com");
  • 14. BatchStatement • Add Simple/Bound statements to a batch BoundStatement bound = prepared.Bind(video.VideoId, video.Name); var simple = new SimpleStatement( "UPDATE videos SET name = ? WHERE videoid = ?" ).Bind(video.Name, video.VideoId); // Use an atomic batch to send over all the mutations var batchStatement = new BatchStatement(); batchStatement.Add(bound); batchStatement.Add(simple);
  • 15. BatchStatement • Batches are Logged, atomic (by default) and this is the most common use case • Set the batch type to use a different type of batch • Counters have their own batch type (can’t mix) var batch = new BatchStatement().SetBatchType(BatchType.Unlogged);
  • 16. Statements – You’ve Got Options • Simple and Bound statements have options that can be set at the Statement level • Consistency Level • Retry Policy • Paging Size (for automatic paging, we’ll come back to this) • Tracing • If not set at the statement level, defaults set when configuring/building the Cluster are used
  • 17. Statements – You’ve Got Options • Example of binding a PreparedStatement and setting available options: IStatement bound = prepared.Bind("luke.tillman@datastax.com") .SetPageSize(100) .SetConsistencyLevel(ConsistencyLevel.LocalOne) .SetRetryPolicy(new DefaultRetryPolicy()) .EnableTracing();
  • 18. Executing Statements and Getting the Results
  • 19. Executing Statements • Use your Session object to execute statements • You can execute statements synchronously or asynchronously • Synchronous • Asynchronous • Execute methods return a RowSet RowSet rows = await _session.ExecuteAsync(boundStatement); RowSet rows = _session.Execute(boundStatement);
  • 20. RowSet • RowSet implements IEnumerable<Row> • Use GetValue<T> method on a Row to get a column’s value • By column name • By ordinal (position)
  • 21. RowSet • Because RowSet implements IEnumerable<Row>: • Iterate with foreach RowSet rows = await _session.ExecuteAsync(boundStatement); foreach (Row row in rows) { returnList.Add(new VideoPreview { VideoId = row.GetValue<Guid>("videoid"), AddedDate = row.GetValue<DateTimeOffset>("added_date"), Name = row.GetValue<string>("name") }); }
  • 22. RowSet • Because RowSet implements IEnumerable<Row>: • Project Rows with LINQ to Objects Select() RowSet rows = await _session.ExecuteAsync(boundStatement); var returnList = rows.Select(row => new VideoPreview { VideoId = row.GetValue<Guid>(0), AddedDate = row.GetValue<DateTimeOffset>(1), Name = row.GetValue<string>(2) }).ToList();
  • 23. RowSet • Because RowSet implements IEnumerable<Row>: • Get a single row with LINQ to Objects Single() or SingleOrDefault() RowSet rows = await _session.ExecuteAsync(boundStatement); Row row = rows.SingleOrDefault();
  • 24. CQL 3 Data Types to .NET Types Full listing available in driver docs CQL 3 Data Type .NET Type bigint, counter long boolean bool decimal, float float double double int int uuid, timeuuid System.Guid text, varchar string (Encoding.UTF8) timestamp System.DateTimeOffset varint System.Numerics.BigIntege r
  • 26. Lightweight Transactions (LWT) • Use when you don’t want writes to step on each other • AKA Linearizable Consistency • Serial Isolation Level • Be sure to read the fine print: has a latency cost associated with using it, so use only where needed • The canonical example: unique user accounts
  • 27. Lightweight Transactions (LWT) • Returns a column called [applied] indicating success/failure • Different from the relational world where you might expect an Exception (i.e. var statement = new SimpleStatement("INSERT INTO user_credentials (email, password) VALUES (?, ?) IF NOT EXISTS"); statement = statement.Bind("user1@killrvideo.com", "Password1!"); RowSet rows = await _session.ExecuteAsync(statement); var userInserted = rows.Single().GetValue<bool>("[applied]");
  • 28. Automatic Paging • The Problem: Loading big result sets into memory is a recipe for disaster (OutOfMemoryExceptions, etc.) • Better to load and process a large result set in pages (chunks) • Doing this manually with Cassandra prior to 2.0 was a pain
  • 29. Automatic Paging • Set a page size on a statement (or will use default from Cluster) • Iterate over the resulting RowSet • As you iterate, new pages are fetched transparently when the Rows in the current page are exhausted • Will allow you to iterate until all pages are exhausted boundStatement = boundStatement.SetPageSize(100); RowSet rows = await _session.ExecuteAsync(boundStatement); foreach (Row row in rows) { }
  • 30. Typical Pager UI in a Web Application • Show page of records in UI and allow user to navigate
  • 31. Typical Pager UI in a Web Application • Automatic Paging – this is not the feature you are looking for
  • 32. Where To Go From Here
  • 33. LINQ to CQL • Comes in the NuGet package as Cassandra.Data.Linq • Has support for all CRUD operations • Start by decorating the objects you’ll be querying with Table, Column, and PartitionKey attributes
  • 34. LINQ to CQL [Table("user_credentials")] public class UserCredentials { [Column("email")] [PartitionKey] public string EmailAddress { get; set; } [Column("password")] public string Password { get; set; } [Column("userid")] public Guid UserId { get; set; } }
  • 35. LINQ to CQL • Then query with LINQ using the Session’s GetTable<T> method as your starting point public UserCredentials GetCredentials(string emailAddress) { IEnumerable<UserCredentials> results = _session.GetTable<UserCredentials>() .Where(uc => uc.EmailAddress == emailAddress) .Execute(); return results.SingleOrDefault(); }
  • 36. ADO.NET Support • Available in the NuGet package as Cassandra.Data • Allows you to use your “favorite” ADO.NET objects like DbConnection, DbCommand, etc. to query Cassandra • My recommendation? Avoid it. • Cassandra concepts don’t always map well to
  • 37. The KillrVideo Sample Application • Many of this presentation’s samples are taken from here • https://github.com/luketillman/killrvideo-csharp
  • 38. What Next? • Data Modeling, Data Modeling, Data Modeling • Planet Cassandra (http://www.planetcassandra.org) • Links to videos, drivers, documentation, tutorials, etc. • 2.1 Beta Available (support for User Defined Types) Follow me on Twitter for updates: @LukeTillman