user1849773 user1849773 - 6 months ago 11
Java Question

Lucen/Elasticsearch: a query for a filed with multiple values

Here is what I would like to do. I have an index with several documents in Elasticsearch. In every document I have two field: deviceField (name of the device) and pressionField (the value of the pression periodically). I want to query in my index the average pression per device. Do you know a way to do it in a single query? Indeed, I do not want to do a kind of loop 'for' in order to the query per deviceName. It will take too much time due to the fact that I have millions of devices.

Thank you for your attention and your help.

S

Answer

You have to use metric aggregations. If you want to list all at same query you use subaggregation

{
    "aggs" : {
        "devices" : {
            "terms" : { "field" : "deviceField" },
             "aggs" : {
                "avg_pression" : { "avg" : { "field" : "pressionField" } }
           }
        }
    }
}

Here is the link of documentation:

https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-avg-aggregation.html