什么是从cassandra中的单行中获取单个值的pythonic方法

时间:2017-02-17 12:39:13

标签: python cassandra

查询可以返回0或1行。我试图获取id,如果有的话。

这有效,但我希望我最终能得到更简单的东西:

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

2 个答案:

答案 0 :(得分:0)

按列名指定列名和访问权限:

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

result.id

答案 1 :(得分:0)

您可以执行api docs here

中列出的内容

可能也值得检查

  1. 不会返回空结果(如上所述)
  2. 返回的结果不超过一个
  3. 所以在你的代码中:

    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
    

    假设元素[0]将始终包含正确的结果可能不是一个好主意。也许有一个布尔字段值来检查哪个用户ID是当前用户ID,然后迭代结果直到你点击该标志。如果您想检查多个结果,那么上面的>1检查不适用。

相关问题