Doyle.Czh
Doyle.Czh

Reputation: 11

elasticsearch how to group by repetitive items in array without distinct

I'm trying to get the counts group by the repetitive items in array without distinct, use aggs terms but not work

GET /my_index/_search
{
  "size": 0,
  "aggs": {
    "keywords": {
       "terms": {
          "field": "keywords"
       }
    }
  }
}

documents like:

"keywords": [
            "value1",
            "value1",
            "value2"
          ],

but the result is:

"buckets": [
        {
          "key": "value1",
          "doc_count": 1
        },
        {
          "key": "value2",
          "doc_count": 1
        }
]

how can i get the result like:

"buckets": [
            {
              "key": "value1",
              "doc_count": 2
            },
            {
              "key": "value2",
              "doc_count": 1
            }
    ]

Upvotes: 0

Views: 36

Answers (1)

Doyle.Czh
Doyle.Czh

Reputation: 11

finally I modify the mapping use nested:

"keywords": {
    "type": "nested",
    "properties": {
        "count": {
            "type": "integer"
        },
        "keyword": {
            "type": "keyword"
        }
    }
},

and query:

GET /my_index/_search
{
    "size": 0,
    "aggs": {
        "keywords": {
            "nested": {
                "path": "keywords"
            },
            "aggs": {
                "keyword_name": {
                    "terms": {
                        "field": "keywords.keyword"
                    },
                    "aggs": {
                        "sums": {
                            "sum": {
                                "field": "keywords.count"
                            }
                        }
                    }
                }
            }
        }
    }
}

result:

"buckets": [{
    "key": "value1",
    "doc_count": 495,
    "sums": {
        "value": 609
    }
},
{
    "key": "value2",
    "doc_count": 440,
    "sums": {
        "value": 615
    }
},
{
    "key": "value3",
    "doc_count": 319,
    "sums": {
        "value": 421
    }
},
...]

Upvotes: 1

Related Questions