Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a record exists in a Cassandra table using the Python driver

How can be determined whether a record exists in a table? The way I tried was to do a SELECT query and then count the rows of the ResultSet using the following:

rows = session.execute("SELECT * FROM test_table WHERE id=%s", ([<id_here>]))
if len(rows) == 0:
    print "Does not exist"

However, ResultSet does not support len. In another answer, they suggest to use SELECT COUNT(*) which in another reference is strongly discouraged. Is there a more standard way to do this?

like image 825
Demetris Avatar asked Mar 11 '23 22:03

Demetris


1 Answers

You can simply do one of the following:

rows = session.execute("SELECT * FROM test_table WHERE id=%s", ([<id_here>]))
if not rows:
    print "Does not exist"

Or, if selecting multiple rows you could iterate over the ResultSet with:

for row in rows:
    do_something(row)

ResultSet also has a current_rows attribute which will be empty if none were returned.

See http://datastax.github.io/python-driver/api/cassandra/cluster.html#cassandra.cluster.ResultSet for more details on how to use the ResultSet.

like image 110
Kurt Avatar answered Apr 08 '23 01:04

Kurt