Possible to query by key instead of value in Hazelcast (using Predicates)?
Asked Answered
A

1

6

In Hazelcast, is it possible to query an IMap based on attributes of a key instead of the values? All the Hazelcast examples show querying by value. E.g., for a map of employees with keys that are strings:

IMap<String, Employee> employees;

The typical search predicates then search based on employee attributes (name, salary, etc). But my case uses more complex keys, such as:

IMap<DataAttributes, DataValue> myData;

So if DataAttributes has fields such as:

 class DataAttributes {
     String theDescription;
     Date   theStartTime;
     public String getDescription() { return theDescription; }
     // etc....
 }

I want to write a predicate that can query by the keys, to return an appropriate DataValue object. This does not work:

Predicate pred = Predicates.equal("description", "myDescription");
myData.keySet(pred);  // Throws IllegalArgumentException: "There is no suitable accessor for..."

I could roll-my-own as suggested in this answer, but I'd rather use an out-of-the-box solution if I can.

It doesn't matter if I wind up using the Criteria API, or the Distributed SQL Query API. Any working query would be great. Bonus points for a solution that works on nested attributes (i.e.: DataAttributes theStartTime.getYear()).

Afterclap answered 27/5, 2015 at 15:28 Comment(0)
A
8

It is possible using PredicateBuilder (com.hazelcast.query.PredicateBuilder). The PredicateBuilder paradigm allows you to query based on keys, like so:

EntryObject eo = new PredicateBuilder().getEntryObject();
Predicate fredWithStartTimeThisYear = eo.key().get("Description").equal("Fred")
  .and(eo.key().get("theStartTime.Year").equal(2015));

Note that you can refer to class members by accessor method ("getter") or field name, as you can see in the above example code. I found this information in the "Mastering Hazelcast" online book, available at hazelcast.org (but you have to fill out a registration form to gain access to it).

Afterclap answered 28/5, 2015 at 15:56 Comment(2)
note that using predicate (on key or values) is VERY expensive when a lot of data is loaded in the map... be careful with this usage !Commutation
@Commutation Right. I usually use indexes to mitigate this. And using an appropriate serializer is also helpful.Afterclap

© 2022 - 2024 — McMap. All rights reserved.