Demetris
Demetris

Reputation: 3241

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?

Upvotes: 5

Views: 10563

Answers (2)

Nick Suslov
Nick Suslov

Reputation: 124

Cassandra session.execute returns ResultSet object that contain current_rows attribute.

try folowing:

    r = session.execute(f"SELECT * FROM test_table WHERE id = {some_id} limit 1")
    if(len(r.current_rows) == 0):
        # your code here

Upvotes: 0

Kurt
Kurt

Reputation: 191

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.

Upvotes: 8

Related Questions