【发布时间】:2015-09-02 09:14:53
【问题描述】:
我需要编写一组 CQL 脚本,其中脚本的内容是否运行取决于某些数据的存在。有没有办法写这种东西:
if(insert into table ... values ... if not exists) {
// the real script
} else {
// print some error description
}
【问题讨论】:
我需要编写一组 CQL 脚本,其中脚本的内容是否运行取决于某些数据的存在。有没有办法写这种东西:
if(insert into table ... values ... if not exists) {
// the real script
} else {
// print some error description
}
【问题讨论】:
您无法直接在 CQL 脚本中执行此操作,因为 CQL 中没有 if 语句控制逻辑。
但您可以在调用 cqlsh 的 bash 脚本中执行此操作。
您可以像这样在 bash 中运行命令:
cqlsh -e "insert into test.t1 (p,c) values (1,8) IF NOT EXISTS;"
[applied]
-----------
True
这意味着该行不存在并且被插入。现在,如果您尝试再次插入它,它将像这样失败:
cqlsh -e "insert into test.t1 (p,c) values (1,8) IF NOT EXISTS;"
[applied] | p | c | v
-----------+---+---+------
False | 1 | 8 | null
因此,您可以做的是捕获该输出,然后检查它是否已应用,如下所示:
#!/bin/bash
result=`cqlsh -e "insert into test.t1 (p,c) values (1,8) IF NOT EXISTS;"`
if [[ $result == *"applied"*"True"* ]]
then
echo "the real script"
else
echo "some error"
fi
另一种方法是使用 java 驱动程序编写 Cassandra 客户端。它可以执行“INSERT...IF NOT EXISTS”或“UPDATE...IF”,然后测试是否应用了该语句并做出相应的响应。
【讨论】: