使用Python驱动程序检查Cassandra表中是否存在记录

Dem*_*ris 3 python cassandra

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

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

但是,ResultSet不支持len.在另一个答案中,他们建议使用SELECT COUNT(*)在另一个参考文献中强烈劝阻.有更标准的方法吗?

小智 5

您只需执行以下操作之一:

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

或者,如果选择多行,您可以使用以下内容迭代ResultSet:

for row in rows:
    do_something(row)
Run Code Online (Sandbox Code Playgroud)

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

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