SlideShare ist ein Scribd-Unternehmen logo
1 von 37
Getting Started with DataStax C#
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.AddQuery(bound);
batchStatement.AddQuery(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 Paging in a Web Application
• Show page of records in UI and allow user to
navigate
• 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.
Follow me on Twitter for updates: @LukeTillman

Weitere ähnliche Inhalte

Was ist angesagt?

What We Learned About Cassandra While Building go90 (Christopher Webster & Th...
What We Learned About Cassandra While Building go90 (Christopher Webster & Th...What We Learned About Cassandra While Building go90 (Christopher Webster & Th...
What We Learned About Cassandra While Building go90 (Christopher Webster & Th...
DataStax
 
From Postgres to Cassandra (Rimas Silkaitis, Heroku) | C* Summit 2016
From Postgres to Cassandra (Rimas Silkaitis, Heroku) | C* Summit 2016From Postgres to Cassandra (Rimas Silkaitis, Heroku) | C* Summit 2016
From Postgres to Cassandra (Rimas Silkaitis, Heroku) | C* Summit 2016
DataStax
 
Cassandra on Mesos Across Multiple Datacenters at Uber (Abhishek Verma) | C* ...
Cassandra on Mesos Across Multiple Datacenters at Uber (Abhishek Verma) | C* ...Cassandra on Mesos Across Multiple Datacenters at Uber (Abhishek Verma) | C* ...
Cassandra on Mesos Across Multiple Datacenters at Uber (Abhishek Verma) | C* ...
DataStax
 

Was ist angesagt? (20)

Caching In The Cloud
Caching In The CloudCaching In The Cloud
Caching In The Cloud
 
Cassandra 2.0 better, faster, stronger
Cassandra 2.0   better, faster, strongerCassandra 2.0   better, faster, stronger
Cassandra 2.0 better, faster, stronger
 
Pycon 2012 Apache Cassandra
Pycon 2012 Apache CassandraPycon 2012 Apache Cassandra
Pycon 2012 Apache Cassandra
 
Cassandra Community Webinar | Become a Super Modeler
Cassandra Community Webinar | Become a Super ModelerCassandra Community Webinar | Become a Super Modeler
Cassandra Community Webinar | Become a Super Modeler
 
Cassandra 3.0 Awesomeness
Cassandra 3.0 AwesomenessCassandra 3.0 Awesomeness
Cassandra 3.0 Awesomeness
 
Bulk Loading into Cassandra
Bulk Loading into CassandraBulk Loading into Cassandra
Bulk Loading into Cassandra
 
Cassandra 3.0 advanced preview
Cassandra 3.0 advanced previewCassandra 3.0 advanced preview
Cassandra 3.0 advanced preview
 
Monitoring Cassandra at Scale (Jason Cacciatore, Netflix) | C* Summit 2016
Monitoring Cassandra at Scale (Jason Cacciatore, Netflix) | C* Summit 2016Monitoring Cassandra at Scale (Jason Cacciatore, Netflix) | C* Summit 2016
Monitoring Cassandra at Scale (Jason Cacciatore, Netflix) | C* Summit 2016
 
Instaclustr Webinar 50,000 Transactions Per Second with Apache Spark on Apach...
Instaclustr Webinar 50,000 Transactions Per Second with Apache Spark on Apach...Instaclustr Webinar 50,000 Transactions Per Second with Apache Spark on Apach...
Instaclustr Webinar 50,000 Transactions Per Second with Apache Spark on Apach...
 
Cassandra Day SV 2014: Netflix’s Astyanax Java Client Driver for Apache Cassa...
Cassandra Day SV 2014: Netflix’s Astyanax Java Client Driver for Apache Cassa...Cassandra Day SV 2014: Netflix’s Astyanax Java Client Driver for Apache Cassa...
Cassandra Day SV 2014: Netflix’s Astyanax Java Client Driver for Apache Cassa...
 
Optimizing Your Cluster with Coordinator Nodes (Eric Lubow, SimpleReach) | Ca...
Optimizing Your Cluster with Coordinator Nodes (Eric Lubow, SimpleReach) | Ca...Optimizing Your Cluster with Coordinator Nodes (Eric Lubow, SimpleReach) | Ca...
Optimizing Your Cluster with Coordinator Nodes (Eric Lubow, SimpleReach) | Ca...
 
Hazelcast
HazelcastHazelcast
Hazelcast
 
Manchester Hadoop Meetup: Cassandra Spark internals
Manchester Hadoop Meetup: Cassandra Spark internalsManchester Hadoop Meetup: Cassandra Spark internals
Manchester Hadoop Meetup: Cassandra Spark internals
 
Monitoring with Prometheus
Monitoring with PrometheusMonitoring with Prometheus
Monitoring with Prometheus
 
What We Learned About Cassandra While Building go90 (Christopher Webster & Th...
What We Learned About Cassandra While Building go90 (Christopher Webster & Th...What We Learned About Cassandra While Building go90 (Christopher Webster & Th...
What We Learned About Cassandra While Building go90 (Christopher Webster & Th...
 
DataStax: An Introduction to DataStax Enterprise Search
DataStax: An Introduction to DataStax Enterprise SearchDataStax: An Introduction to DataStax Enterprise Search
DataStax: An Introduction to DataStax Enterprise Search
 
From Postgres to Cassandra (Rimas Silkaitis, Heroku) | C* Summit 2016
From Postgres to Cassandra (Rimas Silkaitis, Heroku) | C* Summit 2016From Postgres to Cassandra (Rimas Silkaitis, Heroku) | C* Summit 2016
From Postgres to Cassandra (Rimas Silkaitis, Heroku) | C* Summit 2016
 
Cassandra on Mesos Across Multiple Datacenters at Uber (Abhishek Verma) | C* ...
Cassandra on Mesos Across Multiple Datacenters at Uber (Abhishek Verma) | C* ...Cassandra on Mesos Across Multiple Datacenters at Uber (Abhishek Verma) | C* ...
Cassandra on Mesos Across Multiple Datacenters at Uber (Abhishek Verma) | C* ...
 
Introduction to data modeling with apache cassandra
Introduction to data modeling with apache cassandraIntroduction to data modeling with apache cassandra
Introduction to data modeling with apache cassandra
 
Enter the Snake Pit for Fast and Easy Spark
Enter the Snake Pit for Fast and Easy SparkEnter the Snake Pit for Fast and Easy Spark
Enter the Snake Pit for Fast and Easy Spark
 

Andere mochten auch

Olap with Spark and Cassandra
Olap with Spark and CassandraOlap with Spark and Cassandra
Olap with Spark and Cassandra
DataStax Academy
 
SCALE11x: 10 Years of FOSS Hosting at the OSUOSL
SCALE11x: 10 Years of FOSS Hosting at the OSUOSLSCALE11x: 10 Years of FOSS Hosting at the OSUOSL
SCALE11x: 10 Years of FOSS Hosting at the OSUOSL
Lance Albertson
 
DDD Sydney 2011 - Getting out of Sync with IIS and Riding a Comet
DDD Sydney 2011 - Getting out of Sync with IIS and Riding a CometDDD Sydney 2011 - Getting out of Sync with IIS and Riding a Comet
DDD Sydney 2011 - Getting out of Sync with IIS and Riding a Comet
Richard Banks
 

Andere mochten auch (20)

A Deep Dive into Apache Cassandra for .NET Developers
A Deep Dive into Apache Cassandra for .NET DevelopersA Deep Dive into Apache Cassandra for .NET Developers
A Deep Dive into Apache Cassandra for .NET Developers
 
Olap with Spark and Cassandra
Olap with Spark and CassandraOlap with Spark and Cassandra
Olap with Spark and Cassandra
 
Client Drivers and Cassandra, the Right Way
Client Drivers and Cassandra, the Right WayClient Drivers and Cassandra, the Right Way
Client Drivers and Cassandra, the Right Way
 
Cassandra Day London 2015: Getting Started with Apache Cassandra and Java
Cassandra Day London 2015: Getting Started with Apache Cassandra and JavaCassandra Day London 2015: Getting Started with Apache Cassandra and Java
Cassandra Day London 2015: Getting Started with Apache Cassandra and Java
 
Cassandra Summit EU 2014 Lightning talk - Paging (no animation)
Cassandra Summit EU 2014 Lightning talk - Paging (no animation)Cassandra Summit EU 2014 Lightning talk - Paging (no animation)
Cassandra Summit EU 2014 Lightning talk - Paging (no animation)
 
Getting started with DataStax .NET Driver for Cassandra
Getting started with DataStax .NET Driver for CassandraGetting started with DataStax .NET Driver for Cassandra
Getting started with DataStax .NET Driver for Cassandra
 
Cassandra Drivers and Tools
Cassandra Drivers and ToolsCassandra Drivers and Tools
Cassandra Drivers and Tools
 
Real data models of silicon valley
Real data models of silicon valleyReal data models of silicon valley
Real data models of silicon valley
 
Real-time Cassandra
Real-time CassandraReal-time Cassandra
Real-time Cassandra
 
Apache Cassandra in the Real World
Apache Cassandra in the Real WorldApache Cassandra in the Real World
Apache Cassandra in the Real World
 
Introduction to .Net Driver
Introduction to .Net DriverIntroduction to .Net Driver
Introduction to .Net Driver
 
Apache Spark and DataStax Enablement
Apache Spark and DataStax EnablementApache Spark and DataStax Enablement
Apache Spark and DataStax Enablement
 
On needle settings of tuck stitch fully fashioned,22rib diamond design fully-...
On needle settings of tuck stitch fully fashioned,22rib diamond design fully-...On needle settings of tuck stitch fully fashioned,22rib diamond design fully-...
On needle settings of tuck stitch fully fashioned,22rib diamond design fully-...
 
SCALE11x: 10 Years of FOSS Hosting at the OSUOSL
SCALE11x: 10 Years of FOSS Hosting at the OSUOSLSCALE11x: 10 Years of FOSS Hosting at the OSUOSL
SCALE11x: 10 Years of FOSS Hosting at the OSUOSL
 
Rescue.asd
Rescue.asdRescue.asd
Rescue.asd
 
Lesson plan nº 1, 2 and 3
Lesson plan nº 1, 2 and 3Lesson plan nº 1, 2 and 3
Lesson plan nº 1, 2 and 3
 
Sovereignty, Free Will, and Salvation - Limited Atonement
Sovereignty, Free Will, and Salvation - Limited AtonementSovereignty, Free Will, and Salvation - Limited Atonement
Sovereignty, Free Will, and Salvation - Limited Atonement
 
B.j. mate i
B.j. mate iB.j. mate i
B.j. mate i
 
DDD Sydney 2011 - Getting out of Sync with IIS and Riding a Comet
DDD Sydney 2011 - Getting out of Sync with IIS and Riding a CometDDD Sydney 2011 - Getting out of Sync with IIS and Riding a Comet
DDD Sydney 2011 - Getting out of Sync with IIS and Riding a Comet
 
article198
article198article198
article198
 

Ähnlich wie Cassandra Day NY 2014: Getting Started with the DataStax C# Driver

Getting Started with Datatsax .Net Driver
Getting Started with Datatsax .Net DriverGetting Started with Datatsax .Net Driver
Getting Started with Datatsax .Net Driver
DataStax Academy
 
OSCON 2014 - API Ecosystem with Scala, Scalatra, and Swagger at Netflix
OSCON 2014 - API Ecosystem with Scala, Scalatra, and Swagger at NetflixOSCON 2014 - API Ecosystem with Scala, Scalatra, and Swagger at Netflix
OSCON 2014 - API Ecosystem with Scala, Scalatra, and Swagger at Netflix
Manish Pandit
 

Ähnlich wie Cassandra Day NY 2014: Getting Started with the DataStax C# Driver (20)

Getting Started with Datatsax .Net Driver
Getting Started with Datatsax .Net DriverGetting Started with Datatsax .Net Driver
Getting Started with Datatsax .Net Driver
 
Cassandra Summit 2014: Highly Scalable Web Application in the Cloud with Cass...
Cassandra Summit 2014: Highly Scalable Web Application in the Cloud with Cass...Cassandra Summit 2014: Highly Scalable Web Application in the Cloud with Cass...
Cassandra Summit 2014: Highly Scalable Web Application in the Cloud with Cass...
 
Web UI test automation instruments
Web UI test automation instrumentsWeb UI test automation instruments
Web UI test automation instruments
 
DjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling DisqusDjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling Disqus
 
Testing basics for developers
Testing basics for developersTesting basics for developers
Testing basics for developers
 
Ice mini guide
Ice mini guideIce mini guide
Ice mini guide
 
The Ring programming language version 1.3 book - Part 53 of 88
The Ring programming language version 1.3 book - Part 53 of 88The Ring programming language version 1.3 book - Part 53 of 88
The Ring programming language version 1.3 book - Part 53 of 88
 
ASP.Net 5 and C# 6
ASP.Net 5 and C# 6ASP.Net 5 and C# 6
ASP.Net 5 and C# 6
 
Auto-GWT : Better GWT Programming with Xtend
Auto-GWT : Better GWT Programming with XtendAuto-GWT : Better GWT Programming with Xtend
Auto-GWT : Better GWT Programming with Xtend
 
JS Fest 2019/Autumn. Maciej Treder. Angular Schematics - Develop for developers
JS Fest 2019/Autumn. Maciej Treder. Angular Schematics - Develop for developersJS Fest 2019/Autumn. Maciej Treder. Angular Schematics - Develop for developers
JS Fest 2019/Autumn. Maciej Treder. Angular Schematics - Develop for developers
 
Guice gin
Guice ginGuice gin
Guice gin
 
The Ring programming language version 1.4 book - Part 19 of 30
The Ring programming language version 1.4 book - Part 19 of 30The Ring programming language version 1.4 book - Part 19 of 30
The Ring programming language version 1.4 book - Part 19 of 30
 
Sapphire Gimlets
Sapphire GimletsSapphire Gimlets
Sapphire Gimlets
 
JUnit5 and TestContainers
JUnit5 and TestContainersJUnit5 and TestContainers
JUnit5 and TestContainers
 
Linq
LinqLinq
Linq
 
OSCON 2014 - API Ecosystem with Scala, Scalatra, and Swagger at Netflix
OSCON 2014 - API Ecosystem with Scala, Scalatra, and Swagger at NetflixOSCON 2014 - API Ecosystem with Scala, Scalatra, and Swagger at Netflix
OSCON 2014 - API Ecosystem with Scala, Scalatra, and Swagger at Netflix
 
[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless
 
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
 
SCWCD : Thread safe servlets : CHAP : 8
SCWCD : Thread safe servlets : CHAP : 8SCWCD : Thread safe servlets : CHAP : 8
SCWCD : Thread safe servlets : CHAP : 8
 
Hey Relational Developer, Let's Go Crazy (Patrick McFadin, DataStax) | Cassan...
Hey Relational Developer, Let's Go Crazy (Patrick McFadin, DataStax) | Cassan...Hey Relational Developer, Let's Go Crazy (Patrick McFadin, DataStax) | Cassan...
Hey Relational Developer, Let's Go Crazy (Patrick McFadin, DataStax) | Cassan...
 

Mehr von DataStax Academy

Cassandra on Docker @ Walmart Labs
Cassandra on Docker @ Walmart LabsCassandra on Docker @ Walmart Labs
Cassandra on Docker @ Walmart Labs
DataStax Academy
 
Cassandra Adoption on Cisco UCS & Open stack
Cassandra Adoption on Cisco UCS & Open stackCassandra Adoption on Cisco UCS & Open stack
Cassandra Adoption on Cisco UCS & Open stack
DataStax Academy
 
Cassandra @ Netflix: Monitoring C* at Scale, Gossip and Tickler & Python
Cassandra @ Netflix: Monitoring C* at Scale, Gossip and Tickler & PythonCassandra @ Netflix: Monitoring C* at Scale, Gossip and Tickler & Python
Cassandra @ Netflix: Monitoring C* at Scale, Gossip and Tickler & Python
DataStax Academy
 
Standing Up Your First Cluster
Standing Up Your First ClusterStanding Up Your First Cluster
Standing Up Your First Cluster
DataStax Academy
 
Real Time Analytics with Dse
Real Time Analytics with DseReal Time Analytics with Dse
Real Time Analytics with Dse
DataStax Academy
 
Introduction to Data Modeling with Apache Cassandra
Introduction to Data Modeling with Apache CassandraIntroduction to Data Modeling with Apache Cassandra
Introduction to Data Modeling with Apache Cassandra
DataStax Academy
 
Enabling Search in your Cassandra Application with DataStax Enterprise
Enabling Search in your Cassandra Application with DataStax EnterpriseEnabling Search in your Cassandra Application with DataStax Enterprise
Enabling Search in your Cassandra Application with DataStax Enterprise
DataStax Academy
 
Advanced Data Modeling with Apache Cassandra
Advanced Data Modeling with Apache CassandraAdvanced Data Modeling with Apache Cassandra
Advanced Data Modeling with Apache Cassandra
DataStax Academy
 

Mehr von DataStax Academy (20)

Forrester CXNYC 2017 - Delivering great real-time cx is a true craft
Forrester CXNYC 2017 - Delivering great real-time cx is a true craftForrester CXNYC 2017 - Delivering great real-time cx is a true craft
Forrester CXNYC 2017 - Delivering great real-time cx is a true craft
 
Introduction to DataStax Enterprise Graph Database
Introduction to DataStax Enterprise Graph DatabaseIntroduction to DataStax Enterprise Graph Database
Introduction to DataStax Enterprise Graph Database
 
Introduction to DataStax Enterprise Advanced Replication with Apache Cassandra
Introduction to DataStax Enterprise Advanced Replication with Apache CassandraIntroduction to DataStax Enterprise Advanced Replication with Apache Cassandra
Introduction to DataStax Enterprise Advanced Replication with Apache Cassandra
 
Cassandra on Docker @ Walmart Labs
Cassandra on Docker @ Walmart LabsCassandra on Docker @ Walmart Labs
Cassandra on Docker @ Walmart Labs
 
Cassandra 3.0 Data Modeling
Cassandra 3.0 Data ModelingCassandra 3.0 Data Modeling
Cassandra 3.0 Data Modeling
 
Cassandra Adoption on Cisco UCS & Open stack
Cassandra Adoption on Cisco UCS & Open stackCassandra Adoption on Cisco UCS & Open stack
Cassandra Adoption on Cisco UCS & Open stack
 
Data Modeling for Apache Cassandra
Data Modeling for Apache CassandraData Modeling for Apache Cassandra
Data Modeling for Apache Cassandra
 
Coursera Cassandra Driver
Coursera Cassandra DriverCoursera Cassandra Driver
Coursera Cassandra Driver
 
Production Ready Cassandra
Production Ready CassandraProduction Ready Cassandra
Production Ready Cassandra
 
Cassandra @ Netflix: Monitoring C* at Scale, Gossip and Tickler & Python
Cassandra @ Netflix: Monitoring C* at Scale, Gossip and Tickler & PythonCassandra @ Netflix: Monitoring C* at Scale, Gossip and Tickler & Python
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 1Cassandra @ Sony: The good, the bad, and the ugly part 1
Cassandra @ Sony: The good, the bad, and the ugly part 1
 
Cassandra @ Sony: The good, the bad, and the ugly part 2
Cassandra @ Sony: The good, the bad, and the ugly part 2Cassandra @ Sony: The good, the bad, and the ugly part 2
Cassandra @ Sony: The good, the bad, and the ugly part 2
 
Standing Up Your First Cluster
Standing Up Your First ClusterStanding Up Your First Cluster
Standing Up Your First Cluster
 
Real Time Analytics with Dse
Real Time Analytics with DseReal Time Analytics with Dse
Real Time Analytics with Dse
 
Introduction to Data Modeling with Apache Cassandra
Introduction to Data Modeling with Apache CassandraIntroduction to Data Modeling with Apache Cassandra
Introduction to Data Modeling with Apache Cassandra
 
Cassandra Core Concepts
Cassandra Core ConceptsCassandra Core Concepts
Cassandra Core Concepts
 
Enabling Search in your Cassandra Application with DataStax Enterprise
Enabling Search in your Cassandra Application with DataStax EnterpriseEnabling Search in your Cassandra Application with DataStax Enterprise
Enabling Search in your Cassandra Application with DataStax Enterprise
 
Bad Habits Die Hard
Bad Habits Die Hard Bad Habits Die Hard
Bad Habits Die Hard
 
Advanced Data Modeling with Apache Cassandra
Advanced Data Modeling with Apache CassandraAdvanced Data Modeling with Apache Cassandra
Advanced Data Modeling with Apache Cassandra
 
Advanced Cassandra
Advanced CassandraAdvanced Cassandra
Advanced Cassandra
 

Kürzlich hochgeladen

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Kürzlich hochgeladen (20)

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

Cassandra Day NY 2014: Getting Started with the DataStax C# Driver

  • 1. Getting Started with DataStax C# 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.AddQuery(bound); batchStatement.AddQuery(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 Paging in a Web Application • Show page of records in UI and allow user to navigate • Automatic Paging – this is not the feature you are looking for
  • 31. Where To Go From Here
  • 32. 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
  • 33. 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; } }
  • 34. 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(); }
  • 35. 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
  • 36. The KillrVideo Sample Application • Many of this presentation’s samples are taken from here • https://github.com/luketillman/killrvideo-csharp
  • 37. What Next? • Data Modeling, Data Modeling, Data Modeling • Planet Cassandra (http://www.planetcassandra.org) • Links to videos, drivers, documentation, tutorials, etc. Follow me on Twitter for updates: @LukeTillman