【问题标题】:CosmosDB Cassandra API - select in query throws exceptionCosmosDB Cassandra API - 在查询中选择抛出异常
【发布时间】:2020-09-10 20:19:02
【问题描述】:
SELECT partition_int, clustering_int, value_string 
FROM test_ks1.test WHERE partition_int = ? AND clustering_int IN ?

使用 in 子句准备的选择查询会引发以下异常:

java.lang.ClassCastException: class com.datastax.oss.driver.internal.core.type.PrimitiveType cannot be cast to class com.datastax.oss.driver.api.core.type.ListType 
(com.datastax.oss.driver.internal.core.type.PrimitiveType and com.datastax.oss.driver.api.core.type.ListType are in unnamed module of loader 'app')
   at com.datastax.oss.driver.internal.core.type.codec.registry.CachingCodecRegistry.inspectType(CachingCodecRegistry.java:343)
   at com.datastax.oss.driver.internal.core.type.codec.registry.CachingCodecRegistry.codecFor(CachingCodecRegistry.java:256)
   at com.datastax.oss.driver.internal.core.data.ValuesHelper.encodePreparedValues(ValuesHelper.java:112)
   at com.datastax.oss.driver.internal.core.cql.DefaultPreparedStatement.bind(DefaultPreparedStatement.java:159)

使用 datastax oss 驱动程序 - 版本 4.5.1 和 cosmosDB。

查询使用 cassadra 作为 docker,并在 cqlsh 中使用 CosmosDB。

使用的查询:

  • CREATE TABLE IF NOT EXISTS test_ks1.test (partition_int int, value_string text, clustering_int int, PRIMARY KEY ((partition_int),clustering_int))
  • 准备声明:INSERT INTO test_ks1.test (partition_int,clustering_int,value_string) values (?,?,?)
  • 插入值:1,1,”a” | 1,2,”b”
  • 准备声明:SELECT partition_int, clustering_int, value_string FROM test_ks1.test WHERE partition_int = ? AND clustering_int IN ?
  • 使用参数1,List.of(1,2)执行
  • 预期的参数是一个整数,而不是整数列表

选择准备语句的示例代码:

final CqlSessionBuilder sessionBuilder = CqlSession.builder()
     .withConfigLoader(loadConfig(sessionConfig));
CqlSession session = sessionBuilder.build();

PreparedStatement statement = session.prepare(
   "SELECT partition_int, clustering_int,"
    + "value_string FROM test_ks1.test WHERE partition_int = ? "
    + "AND clustering_int IN ?");


com.datastax.oss.driver.api.core.cql.ResultSet rs = 
    session.execute(statement.bind(1,List.of(1, 2)));

是否有一种解决方法可以将准备好的选择查询与 in 子句一起使用?

谢谢。

【问题讨论】:

  • 你能展示你绑定变量的代码吗?
  • @AlexOtt 添加了带有绑定的示例代码。

标签: cassandra azure-cosmosdb


【解决方案1】:

我的建议是使用这样的解决方法:

//IDS you want to use;
List<Integer> list = Arrays.asList(1, 2);
// Multiply the number of question marks
String markers = StringUtils.repeat("?,", list.size()-1);
//Final query 
final String query = "SELECT * FROM test_ks1.test where clustering_int in ("+markers+" ?)";

PreparedStatement prepared = session.prepare(query);
BoundStatement bound = prepared.bind(list.toArray()).setIdempotent(true);
List<Row> rows  = session.execute(bound).all();

我已经尝试过了,它适用于我。

现在,在您的情况下,您在 IN 之前还有另一个参数需要包含在参数列表中,但仅在构建标记占位符之后。

【讨论】:

    猜你喜欢
    • 2016-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-02
    • 2020-03-12
    • 1970-01-01
    • 2016-05-18
    • 1970-01-01
    相关资源
    最近更新 更多