Search code examples
elasticsearchaggregateelasticsearch-aggregationelasticsearch-querynosql

Elastic search(2.4) - search and aggregate over arrays


I have a index with mapping as -

GET /sampledesc/desc/_mapping
{
  "sampledesc": {
  "mappings": {
     "desc": {
        "properties": {
           "labels": {
              "type": "string",
              "index": "not_analyzed"
           },
           "tags": {
              "type": "string",
              "index": "not_analyzed"
           },
           "user_id": {
              "type": "long"
           }
        }
     }
  }
 }
}

I added some data in it -

PUT /sampledesc/desc/1
{
"user_id": 1,
"tags": ["tag1", "tag2", "tag3"],
"labels": ["label1","label2"]
}

PUT /sampledesc/desc/2
{
"user_id": 2,
"tags": ["tag2","tag3",],
"labels": ["label2","label4"]
}

PUT /sampledesc/desc/3
{
"user_id": 3,
"tags": ["tag7"],
"labels": ["label1","label4"]
}

I want to query this data with these rules:

  1. Find all users who have given list of tags.
  2. For those users, group the labels by count.

For eg., I want to query users who have both tag2 AND tag3 and group the labels with their count in sorted order. In the given sample data for three users, my result would be label2 = 2; label1 = 1, label4 = 1.


Solution

  • Hi You can use the following query

    {
        "aggs": {
            "label_group": {
                "terms": {
                    "field": "labels",
                    "size": 10
                }
            }
        },
        "query": {
            "bool": {
                "must": [{
                    "terms": {
                        "tags": [
                            "tag2"
                        ]
                    }
                }, {
                    "terms": {
                        "tags": [
                            "tag3"
                        ]
                    }
                }]
            }
        }
    }
    

    Hope this helps Thanks