javaelasticsearchelasticsearch-jest

how to use maxAggregation in jest elasticsearch


i want to get the maximun id form a subfield of an aptitude object,

{
"mappings": {
    "aptitude": {
        "dynamic": "strict",
        "properties": {
            "id": {
                "type": "long"
            },
            "es": {
                "type": "text"
            },
            "en": {
                "type": "text"
            },
            "behaviors": {
                "properties": {
                    "id": {
                        "type": "long"
                    },
                    "es": {
                        "type": "text"
                    },
                    "en": {
                        "type": "text"
                    }
                }
            }
        }
    }
}

as you can see the aptitude have an array of behaviors who in turn have an id, afaik i should use the maxAggregation from Jest, but cant find a decent example of how to do it in java, can someone help?


Solution

  • i found the way like this:

    String query = "{\n"
                +"    \"query\" : {\n"
                +"        \"match\" : {\"id\":" + aptitudeId + "}\n"
                +"    },\n"
                +"    \"aggs\" : {\n"
                +"        \"max1\" : {\n"
                +"            \"max\" : {\n"
                +"                \"field\" : \"behaviors.id\"\n"
                +"            }\n"
                +"        }\n"
                +"    }\n"
                +"}";
    

    i was looking into the aggregation builders from jest but doing it via query was much easier.

    the return looks like this:

    Search search = new Search.Builder(query)
                .addIndex(aptitudeIndexName)
                .addType(aptitudeTypeName)
                .build();
    
        try {
            SearchResult result = client.execute(search);
    
    
            MaxAggregation max1 = result.getAggregations().getMaxAggregation("max1");
            Double max = max1.getMax();
            return max.longValue() + 1;//so it would add 1 to the current maximum id