Emanuel George Hategan
Emanuel George Hategan

Reputation: 1263

What's the pythonic way of fetching a single value from a single row in cassandra

The query can either return 0 or 1 rows. I'm trying to fetch the id if there is one.

This works but I'm hoping I can end up with something simpler:

result = session.execute("SELECT * FROM table_name WHERE email = %s", (email,))
if len(result.current_rows) is not 1:
    raise SystemExit("Account not found for {}".format(email))

id = result[0].id

Upvotes: 1

Views: 714

Answers (2)

markc
markc

Reputation: 2158

You could do something like what's outlined in the api docs here

Probably also worth checking that

  1. No empty results are returned (as you do above)
  2. Not more than one result is returned

So in your code:

if (len(result.current_rows) > 1:
   raise SystemExit("More than one result found for {}".format(email))
elif (len(result.current_rows) < 1:
   raise SystemExit("No results found for {}".format(email))
for result in results:
    # code to do things here with the end result

Its probably not a good idea to assume that element [0] will always contain the right result. Maybe have a boolean field value to check which user id is the current one and then iterate through the results until you hit that flag. Thats if you want to check over more than one result, in which case the >1 check above is not applicable.

Upvotes: 1

metmirr
metmirr

Reputation: 4312

Specify column name and access by column name:

result = session.execute("SELECT id FROM table_name WHERE email = %s", (email,))

result.id

Upvotes: 0

Related Questions