我正在使用数据存储Cassandra 2.0驱动程序,我正在使用准备和绑定语句。假设我想查询这样的内容:
SELECT * FROM foo WHERE mykey IN (UUID1, UUID2, UUID3);
其中UUID1,UUID2,UUID3是UUID值。使用绑定语句执行此操作的编程方式是什么?目前我正在尝试以下方面:
preparedStatement = session.prepare("SELECT * FROM foo WHERE vref IN ?")
boundStatement = new BoundStatement(preparedStatement)
val uuids: java.util.ArrayList[java.util.UUID] = //assume we're getting the values from somewhere
session.execute(boundStatement.bind(uuids))
目前这是错误的结果。有关如何正确格式化查询的任何建议吗?
答案 0 :(得分:1)
这是一个使用简单表和文本值的示例。使用Centos 6.5和DSE4.5.1
我的表:
DESCRIBE TABLE deleteme1 ;
CREATE TABLE deleteme1 (
col1 text,
col2 text,
PRIMARY KEY ((col1))
) WITH
bloom_filter_fp_chance=0.010000 AND
caching='KEYS_ONLY' AND
comment='' AND
dclocal_read_repair_chance=0.100000 AND
gc_grace_seconds=10000 AND
index_interval=128 AND
read_repair_chance=0.000000 AND
replicate_on_write='true' AND
populate_io_cache_on_flush='false' AND
default_time_to_live=0 AND
speculative_retry='99.0PERCENTILE' AND
memtable_flush_period_in_ms=0 AND
compaction={'class': 'SizeTieredCompactionStrategy'} AND
compression={'sstable_compression': 'LZ4Compressor'};
我的数据:
cqlsh:results> select * from deleteme1 ;
col1 | col2
-------+-------
three | three
one | one
two | two
four | four
(4 rows)
我的样本测试类
import java.util.ArrayList;
import com.datastax.driver.core.BoundStatement;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.PreparedStatement;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Session;
public class PrepStatement {
Cluster cluster;
Session session;
public static void main(String args []){
PrepStatement myTest = new PrepStatement();
String node = "192.168.56.22";
myTest.runTest(node);
myTest.close();
}
private void runTest(String node){
ArrayList<String> vals = new ArrayList<String>(2);
vals.add("one");
vals.add("three");
try {
cluster = Cluster.builder()
.addContactPoint(node)
//.withCredentials("cassandra", "cassandra") // only if you need a login
.build();
session = cluster.connect();
PreparedStatement preparedStatement = session.prepare("SELECT * FROM results.deleteme1 WHERE col1 IN ?");
BoundStatement boundStatement = new BoundStatement(preparedStatement);
ResultSet results = session.execute(boundStatement.bind(vals));
for (Object result : results){
System.out.println(result.toString());
}
}
catch (Exception e){
e.printStackTrace();
}
}
/**
* cleans up the session
*/
private void close() {
session.close();
cluster.close();
}
}
最后..这里是输出:
Row[one, one]
Row[three, three]
请注意,您只能在主键列的列上使用IN查询,如CQL3.0文档中所述:http://www.datastax.com/documentation/cql/3.0/cql/cql_reference/select_r.html