在 CQL 脚本中使用时,有没有办法在 CQL 命令中传递变量,例如:
select * from "Column Family Name" where "ColumnName"='A variable which takes different values';
欢迎任何建议。
最佳答案
不,CQL 确实没有办法定义变量、运行循环以及基于这些变量进行更新/查询。
作为替代方案,我通常使用 DataStax Python driver对于像这样的简单任务/脚本。以下是我不久前用来从 CSV 文件填充产品颜色的 Python 脚本的摘录。
# connect to Cassandra
auth_provider = PlainTextAuthProvider(username='username', password='currentHorseBatteryStaple')
cluster = Cluster(['127.0.0.1'], auth_provider=auth_provider)
session = cluster.connect('products')
# prepare statements
preparedUpdate = session.prepare(
"""
UPDATE products.productsByItemID SET color=? WHERE itemid=? AND productid=?;
"""
)
# end prepare statements
counter = 0
# read csv file
dataFile = csv.DictReader(csvfilename, delimiter=',')
for csvRow in dataFile:
itemid = csvRow['itemid']
color = csvRow['customcolor']
productid = csvRow['productid']
#update product color
session.execute(preparedUpdate,[color,itemid,productid])
counter = counter + 1
# close Cassandra connection
session.cluster.shutdown()
session.shutdown()
print "updated %d colors" % (counter)
有关详细信息,请查看 DataStax 教程 Getting Started with Apache Cassandra and Python .
关于cassandra - 是否可以在 cql 脚本中的 cql 命令中使用变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30373893/