Monday 17 October 2016

Cassandra Asynchronous Queries

Cassandra Python driver supports asynchronous queries via execute_async() method. This method immediately return ResponseFuture object. There are two ways to get final results from the object

  1. result(): The first is by calling the result() function. This would block untill query is completed or it would raise an exception in case of error.
    query = "SELECT * FROM users"
    try:
    
    future = session.execute_async(query) rows = future.result()
    except Exception:
    print "Exception hit."
  2. callbacks: Alternatively, you can attach callbacks and errback funtion through add_callback(), add_errback() and add_callbacks() function.

    def handle_success(rows):
        user = rows[0]
        print ("name:%s age:%s" % (user.name, user.age))
    
    def handle_error(exception):
        log.error("Failed to fetch user info: %s", exception)
    
    
    future = session.execute_async(query)
    future.add_callbacks(handle_success, handle_error)
Complete example:
from cassandra.cluster import Cluster

cluster = Cluster(['10.10.0.4', '10.10.0.32'])
session = cluster.connect('poc')
query = "insert into users (email, name, age, city) 
         values ('tahir@gmail.com', 'tahir', 34, 'SantaClara')"
future1 = session.execute_async(query)
query = "select * from users"
future2 = session.execute_async(query)

try:
    rows = future1.result()
except Exception:
    print ("Hit an exception")

try:
    rows = future2.result()
    for row in rows:
      print row.name, row.email
except ReadTimeout:
    log.exception("Query timed out:")

References: 
https://datastax.github.io/python-driver/getting_started.html

No comments:

Post a Comment