A C# client driver for Apache Cassandra. This driver works exclusively with the Cassandra Query Language version 3 (CQL3) and Cassandra's binary protocol.
PM> Install-Package CassandraCSharpDriver- Connection pooling
- Node discovery
- Automatic failover
- Several load balancing and retry policies
- Result paging
- Query batching
- Linq2Cql and Ado.Net support
You can use the project Mailing list or create a ticket on the Jira issue tracker.
If you are upgrading from the 1.x branch of the driver, be sure to have a look at the upgrade guide.
//Create a cluster instance using 3 cassandra nodes.varcluster=Cluster.Builder().AddContactPoints("host1","host2","host3").Build();//Create connections to the nodes using a keyspacevarsession=cluster.Connect("sample_keyspace");//Execute a query on a connection synchronouslyvarrs=session.Execute("SELECT * FROM sample_table");//Iterate through the RowSetforeach(varrowinrs){varvalue=row.GetValue<int>("sample_int_column");//do something with the value}Prepare your query once and bind different parameters to obtain best performance.
//Prepare a statement oncevarps=session.Prepare("UPDATE user_profiles SET birth=? WHERE key=?");//...bind different parameters every time you need to executevarstatement=ps.Bind(newDateTime(1942,11,27),"hendrix");//Execute the bound statement with the provided parameterssession.Execute(statement);You can execute multiple statements (prepared or unprepared) in a batch to update/insert several rows atomically even in different column families.
//Prepare the statements involved in a profile update oncevarprofileStmt=session.Prepare("UPDATE user_profiles SET email=? WHERE key=?");varuserTrackStmt=session.Prepare("INSERT INTO user_track (key, text, date) VALUES (?, ?, ?)");//...you should reuse the prepared statement//Bind the parameters and add the statement to the batch batchvarbatch=newBatchStatement().Add(profileStmt.Bind(emailAddress,"hendrix")).Add(userTrackStmt.Bind("hendrix","You changed your email",DateTime.Now));//Execute the batchsession.Execute(batch);Session allows asynchronous execution of statements (for any type of statement: simple, bound or batch) by exposing the ExecuteAsync method.
//Execute a statement asynchronously using awaitvarrs=awaitsession.ExecuteAsync(statement);Or if you want to continue or wait for the async task to complete.
//Execute a statement asynchronously using TPLvartask=session.ExecuteAsync(statement);//The task can waited, awaited, continued, ...task.ContinueWith((t)=>{varrs=t.Result;//Iterate through the rowsforeach(varrowinrs){//Get the values from each row}},TaskContinuationOptions.OnlyOnRanToCompletion);You can iterate indefinitely over the RowSet, having the rows fetched block by block until the rows available on the client side are exhausted.
varstatement=newSimpleStatement("SELECT * from large_table");//Set the page size, in this case the RowSet will not contain more than 1000 at any timestatement.SetPageSize(1000);varrs=session.Execute(statement);foreach(varrowinrs){//The enumerator will yield all the rows from Cassandra//Retrieving them in the back in blocks of 1000.}You can map your User Defined Types to your application entities.
For a given udt
CREATETYPE address (
street text,
city text,
zip_code int,
phones set<text>
);For a given class
publicclassAddress{publicstringStreet{get;set;}publicstringCity{get;set;}publicintZipCode{get;set;}publicIEnumerable<string>Phones{get;set;}}You can either map the properties by name
//Map the properties by name automaticallysession.UserDefinedTypes.Define(UdtMap.For<Address>());Or you can define the properties manually
session.UserDefinedTypes.Define(UdtMap.For<Address>().Map(a =>a.Street,"street").Map(a =>a.City,"city").Map(a =>a.ZipCode,"zip_code").Map(a =>a.Phones,"phones"));You should map your UDT to your entity once and you will be able to use that mapping during all your application lifetime.
varrs=session.Execute("SELECT id, name, address FROM users where id = x");varrow=rs.First();//You can retrieve the field as a value of type AddressvaruserAddress=row.GetValue<Address>("address");Console.WriteLine("user lives on {0} Street",userAddress.Street);You can set the options on how the driver connects to the nodes and the execution options.
//Example at cluster levelvarcluster=Cluster.Builder().AddContactPoints(hosts).WithCompression(CompressionType.LZ4).WithLoadBalancingPolicy(newDCAwareRoundRobinPolicy("west"));//Example at statement (simple, bound, batch) levelvarstatement=newSimpleStatement(query).SetConsistencyLevel(ConsistencyLevel.Quorum).SetRetryPolicy(DowngradingConsistencyRetryPolicy.Instance).SetPageSize(1000);You can use Visual Studio or msbuild to build the solution.
Check the documentation for building the driver from source and running the tests.
Copyright 2014, DataStax
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.