plamb
plamb

Reputation: 5636

How do you add elements to a set with DataStax QueryBuilder?

I have a table whose column types are

text, bigint, set<text> 

I'm trying to update a single row and add an element to the set using QueryBuilder.

The code that overwrites the existing set looks like this (note this is scala):

val query = QueryBuilder.update("twitter", "tweets")
  .`with`(QueryBuilder.set("sinceid", update.sinceID))
  .and(QueryBuilder.set("tweets", setAsJavaSet(update.tweets)))
  .where(QueryBuilder.eq("handle", update.handle))

I was able to find the actual CQL for adding an element to a set which is:

UPDATE users
SET emails = emails + {'[email protected]'} WHERE user_id = 'frodo';

But could not find an example using QueryBuilder.

Based off of the CQL I also tried:

  .and(QueryBuilder.set("tweets", "tweets"+{setAsJavaSet(update.tweets)}))

But it did not work. Thanks in advance

Upvotes: 5

Views: 1784

Answers (3)

R&#233;mi.B
R&#233;mi.B

Reputation: 321

Using @Ananth and @sazzad answers, the code below works:

Session cassandraSession;
UUID uuid;
Long value;

Statement queryAddToSet = QueryBuilder
        .update("tableName")
        .with(QueryBuilder.addAll("setFieldName", QueryBuilder.bindMarker()))
        .where(QueryBuilder.eq("whereFieldName", QueryBuilder.bindMarker()));

PreparedStatement preparedQuery = cassandraSession.prepare(queryAddToSet);
BoundStatement boundQuery = preparedQuery.bind();

boundQuery
        .setUUID("whereFieldName", uuid)
        .setSet("setFieldName", Collections.singleton(value));

session.execute(boundQuery);

Upvotes: 0

sazzad
sazzad

Reputation: 6267

To extend Ananth's answer:

QueryBuilder.add does not support BindMarker. To use BindMarker while adding in set, it is required to use QueryBuilder.addAll only.*

*Just a note, Collections.singleton may come in handy in this regard.

Upvotes: 1

Ananth
Ananth

Reputation: 991

Use add (add one element at a time) or addAll (more than one any number of element at a time) method to add to a set.

Upvotes: 8

Related Questions