使用Python驱动程序检查Cassandra表中是否存在记录 [英] Check if a record exists in a Cassandra table using the Python driver
问题描述
如何确定表中是否存在记录?我尝试的方法是执行 SELECT
查询,然后使用以下方法计算 ResultSet
的行:
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"
但是, ResultSet
不支持 len
。在另一个答案中,他们建议使用 SELECT COUNT(*)
在另一个参考文献中强烈建议不要这样做。有更标准的方法可以做到这一点吗?
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?
推荐答案
您只需执行以下一项操作即可:
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"
或者,如果选择多行,则可以使用以下方法遍历ResultSet:
Or, if selecting multiple rows you could iterate over the ResultSet with:
for row in rows:
do_something(row)
ResultSet还具有current_rows属性,如果未返回任何属性,则该属性为空。
ResultSet also has a current_rows attribute which will be empty if none were returned.
请参见 http://datastax.github.io/python-driver/api/cassandra/ cluster.html#cassandra.cluster.ResultSet 有关如何使用ResultSet的更多详细信息。
See http://datastax.github.io/python-driver/api/cassandra/cluster.html#cassandra.cluster.ResultSet for more details on how to use the ResultSet.
这篇关于使用Python驱动程序检查Cassandra表中是否存在记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!