【问题标题】:Check if a record exists in a Cassandra table using the Python driver使用 Python 驱动程序检查 Cassandra 表中是否存在记录
【发布时间】:2020-03-24 21:59:23
【问题描述】:

如何判断表中是否存在记录?我尝试的方法是进行SELECT 查询,然后使用以下方法计算ResultSet 的行数:

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

但是,ResultSet 不支持len。在另一个答案中,他们建议使用SELECT COUNT(*),在另一个参考中强烈建议不要这样做。有没有更标准的方法来做到这一点?

【问题讨论】:

    标签: python cassandra


    【解决方案1】:

    您可以简单地执行以下操作之一:

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

    或者,如果选择多行,您可以使用以下方法遍历 ResultSet:

    for row in rows:
        do_something(row)
    

    ResultSet 还有一个 current_rows 属性,如果没有返回则为空。

    有关如何使用 ResultSet 的更多详细信息,请参阅http://datastax.github.io/python-driver/api/cassandra/cluster.html#cassandra.cluster.ResultSet

    【讨论】:

      【解决方案2】:

      Cassandra session.execute 返回包含 current_rows 属性的 ResultSet 对象。

      尝试以下操作:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-07-11
        • 1970-01-01
        • 2012-11-02
        • 2013-09-09
        • 1970-01-01
        • 1970-01-01
        • 2021-02-21
        相关资源
        最近更新 更多