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

Hello everyone,

Lucen/Elasticsearch: a query for a filed with multiple valuesHere 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

Look at aggregations. They are built to do that sort of thing. They aren't
a query but instead something to do with the hits.

Hi Nik,

I used your advice and I wrote this code but I found an error:

  "type" : "search_parse_exception",
  "reason" : "Could not find aggregator type [avg_pression] in [aggs]",

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

Do you know how to fix it ?

Regards,

S

Hi S,

If you want your avg_pression aggregation to be a sub aggregation to your devices aggregation, change your code to the following:

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

If you want your avg_pression to also be a top level aggregation change it to the following:

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

Happy coding! :slight_smile:

1 Like

Thank you so much, it works very well :smiley: