How to search for a cassandra collection map using QueryBuilder

In my cassandra table, I have a Map collection. I also indexed the map keys.

CREATE TABLE IF NOT EXISTS test.collection_test( name text, year text, attributeMap map<text,text>, PRIMARY KEY ((name, year)) ); CREATE INDEX ON collection_test (attributeMap); 

The syntax of a QueryBuilder is as follows:

 select().all().from("test", "collection_test") .where(eq("name", name)).and(eq("year", year)); 

How do I condition an attributeMap ?

+5
source share
1 answer

First of all, you will need to create an index for the keys on the map. By default, an index created on a map indexes map values, not keys. To index keys, a special syntax is used:

 CREATE INDEX attributeKeyIndex ON collection_test (KEYS(attributeMap)); 

Next, to SELECT from a card with indexed keys, you will need the keyword CONTAINS KEY . But there is currently no definition for this function in the request API. However, there is an open ticket to support it: JAVA-677

Currently, to accomplish this using the Java driver, you need to create your own query or use a prepared statement:

  PreparedStatement statement = _session.prepare("SELECT * " + "FROM test.collection_test " + "WHERE attributeMap CONTAINS KEY ?"); BoundStatement boundStatement = statement.bind(yourKeyValue); ResultSet results = _session.execute(boundStatement); 

Finally, you should read the DataStax document when to use the index . Secondary indexes are known to work poorly. I can’t imagine that the secondary index in the collection will be different.

+2
source

All Articles