Python Data Persistence – Python Cassandra Driver

Python Data Persistence – Python Cassandra Driver

Cassandra’s Python module has been provided by apache itself. It works with the latest version CQL version 3 and uses Cassandra’s native protocol. This Python driver also has ORM API in addition to core API which is similar in many ways to DB-API.

To install this module, use the pip installer as always.

E:\python37>scripts\pip3 install Cassandra-driver

Verify successful installation by following commands:

Example

>>> import cassandra 
>>> print (cassandra.__version__)
3.17.0

To execute CQL queries, we have to set up a Cluster object, first.

Example

>>> from cassandra.cluster import Cluster 
>>> clstr=Cluster( )

Next up, we need to start a session by establishing a connection with our keyspace in the cluster.

Example

>>> session=clstr.connect('mykeyspace')

The ubiquitous execute( ) method of the session object is used to perform all CQL operations. For instance, the primary SELECT query over the ‘products’ table in ‘niykeypace’ returns a result set object. Using atypical for loop, all rows can be traversed.

Example

#cassandra-select.py from cassandra.cluster import 
Cluster clstr=Cluster() session=clstr.connect(1mykeyspace1) . 
rows=session.execute("select * from products;") for row in rows: 
print (’Manufacturer: {} ProductID:{} Name:{ }
 priceformat(row[1] ,row [0] , 
row [2], row [3]) )

Output

E:\python37>python cassandra-select.py Manufacturer: ’Epson’ ProductID:5 Name:1 Printer’
price:9000
Manufacturer: 1IBall’ ProductID:10 Name:’Keyboard1
price : 1000
Manufacturer: ’Acer’ ProductID:l Name:’Laptop’
price:25000
Manufacturer: ’Acer’ ProductID:8 Name:’Tab’
price:10000
Manufacturer: ’Samsung’ ProductID:2 Name:’TV’
price:40000
Manufacturer: ’Epson’ ProductID:4 Name:1 Scanner’
price:5000
Manufacturer: ’IBall’ ProductID:7 Name:’Mouse' price:500
Manufacturer: ’Samsung’ ProductID:6 Name:’Mobile’
price:15000
Manufacturer: ’Samsung’ ProductID:9 Name:’AC’
price:35000
Manufacturer: ’IBall’ ProductID:3 Name:’Router’
price:2000

Leave a Comment