首页 > 解决方案 > How to use bind variable inside collection literal in cassandra - InvalidQueryException

问题描述

I'm preparing a cassandra query in java using com.datastax.driver.core.PreparedStatement

My schema is very simple - a key which is of type text and value of type set<text>. I am preparing the statement like so:

mySession.prepare("UPDATE a.table USING TTL :ttl SET value = value + {:value} WHERE key = :key ");

[This is done in order to add a value to the set and have separate ttl for each value]

I got this error when evaluating the above statement:

com.datastax.driver.core.exceptions.InvalidQueryException: Invalid set literal for value: bind variables are not supported inside collection literals
at com.datastax.driver.core.exceptions.InvalidQueryException.copy(InvalidQueryException.java:49)
at com.datastax.driver.core.DriverThrowables.propagateCause(DriverThrowables.java:35)
at com.datastax.driver.core.AbstractSession.prepare(AbstractSession.java:86)

How can I overcome this exception and bind my variable to a collection of type set<text>. Alternatively, is there some better/prefered way of accomplishing my goal of dynamically (with different TTL) adding items to a set in cassandra from java?

标签: javacassandra

解决方案


You can do as follows:

PreparedStatement st = session.prepare("UPDATE test2 USING TTL :ttl SET value = value + :value WHERE name = :name ");
session.execute(st.bind()
                .setInt("ttl",1)
                .setSet("value", ImmutableSet.of("add this value"))
                .setString("name","key1"));

推荐阅读