javahazelcasthazelcast-aggregate

How to use aggregations with HazelcastJsonValue?


How to use aggregations with HazelcastJsonValue?

I'm trying to use:

Long count = map1.aggregate(Aggregators.count(), e -> "name='John'".equals(e.getValue()));        
Long count = map1.aggregate(Aggregators.count("name='John'"));

But I'm getting 0 in both cases while the actual result should be 4.

Here's a sample code:

    HazelcastInstance hazelCast = Hazelcast.newHazelcastInstance();
    IMap<String, HazelcastJsonValue> map1 = hazelCast.getMap("map1");

    map1.put("1", new HazelcastJsonValue("{"name":"John", "age":31, "city":"New York"}"));
    map1.put("2",  new HazelcastJsonValue("{"name":"John", "age":31, "city":"New York"}"));
    map1.put("3", new HazelcastJsonValue("{"name":"John", "age":31, "city":"New York"}"));
    map1.put("4",  new HazelcastJsonValue("{"name":"John", "age":31, "city":"New York"}"));
    
    Long count = map1.aggregate(Aggregators.count(), e -> "name='John'".equals(e.getValue()));
    Long count = map1.aggregate(Aggregators.count("name='John'"));

    System.out.println(count);

Solution

  • The predicate doesn't look well-formed to me -- in the first one, you're comparing the entire JSON document (multiple fields) using 'equals' against a portion of the doc, so it will never match.

    What worked for me is this:

    Config c = new Config();
    HazelcastInstance hazelCast = Hazelcast.newHazelcastInstance(c);
    IMap<String, HazelcastJsonValue> map1 = hazelCast.getMap("map1");
    
    HazelcastJsonValue jsv = new HazelcastJsonValue("{\"name\":\"John\", \"age\":31, \"city\":\"New York\"}");
    map1.put("A", jsv);
    map1.put("B", jsv);
    
    Predicate p = Predicates.equal("name", "John");
    long count = map1.aggregate(Aggregators.count(), p);
    System.out.println("Count: " + count);
    hazelCast.shutdown();