elasticsearchelasticsearch-aggregationmatch-phrase

How to aggregate on a matched prefix/phrase from ElasticSearch records?


I have a field "Departments" which is a list: { "Departments": ["Food Service","Software Development","Manufacturing","Deployment"] }'

I want to aggregate on the elements of "Department" that start with "d". i.e., Deployment from all records.

I am able to find the records that have one element with prefix "d" but not able to aggregate over them. Rather I am aggregating over all the elements of "Departments" in the records returned after querying for the prefix "d".

{
 "query": {
        "bool": {
            "filter": {
                "match_phrase_prefix": {
                    "Departments": {"query": "a"}
                }
            }
        }
    },
    "aggs" : {
        "all_locations" : {
            "terms" : { "field" : "Departments" }
        }
    }
}

For example, if I have 4 records in total, out of which "Deployment" is present in 1, then I want:

Deployment:1

But what I am actually getting is the frequency of all the elements in that record where "Deployment" is present.

Deployment:1, Food:1, Services:1, Software:1, Development:1, Manufacturing:1


Solution

  • That's easy. Just make use of include keyword and add the required regex value to it, in the Terms Query and you'd get what you want.

    I've mentioned the solution below:


    POST <your_index_name>/_search
    {  
       "query":{  
          "bool":{  
             "filter":{  
                "match_phrase_prefix":{  
                   "Departments":{  
                      "query":"a"
                   }
                }
             }
          }
       },
       "aggs":{  
          "all_locations":{  
             "terms":{  
                "field":"Departments",
                "include":"D.*"
             }
          }
       }
    }
    

    The above query would only return aggregation buckets starting with D. You can change it to Dep.* to test for Deployment

    Feel free to accept/upvote the answer if you think it resolved your requirement. Queries are most welcome.