Sunday 16 October 2016

Getting started with Cassandra Python API driver

Pre-Req

Please follow this to setup a multi-node cluster (You can try this post with single node cluster as well. For that just follow till step 4 of the link).

Instantiating a cluster: 

from cassandra.cluster import Cluster

cluster = Cluster(['10.10.0.4', '10.10.0.32'])
10.10.0.4 and 10.10.0.32 are ip addresses of 2 nodes of our cluster. These are initial contact points. 
You don't need to give exhaustive list here. Just few of them or even one of them is sufficient. Once the driver find one of them, he will automatically discover rest.

Connect to cluster:

Instantiating a cluster does not connect driver to the cluster. To connect you should give something like
session = cluster.connect()

Set Keyspace:

session.set_keyspace('mykeyspace')

Executing Queries:

Now we are all set to execute queries. Simplest way is to use execute method
rows = session.execute('SELECT name, age, email FROM users')

Complete example:

from cassandra.cluster import Cluster

cluster = Cluster(['10.10.0.4', '10.10.0.32'])
session = cluster.connect('mykeyspace')
session.execute("""
        CREATE TABLE users (
            email text, 
            name text,
            age int,
            city text,
            PRIMARY KEY ((email), age)
        )
        """)
session.execute("""
insert into users (email, name, age, city) values ('inaya@gmail.com', 'INAYA', 3, 'SantaClara')
""")
result = session.execute("select * from users")[0]
print result.name, result.age

No comments:

Post a Comment