2

Given I have the following records.

[
    {
        "profile": "123",
        "inner": [
            {
                "name": "John"
            }
        ]
    },
    {
        "profile": "456",
        "inner": [
            {
                "name": "John"
            },
            {
                "name": "John"
            },
            {
                "name": "James"
            }
        ]
    }
]

I want to get something like:

"aggregations": {
    "name": {
        "buckets": [
            {
                "key": "John",
                "doc_count": 3
            },
            {
                "key": "James",
                "doc_count": 1
            }
        ]
    }
}

I'm a beginner using Elasticsearch, and this seems to be a pretty simple operation to do, but I can't find how to achieve this.
If I try a simple aggs using term, it returns 2 for John, instead of 3. Example request I'm trying:

{
  "size": 0,
  "aggs": {
    "name": {
      "terms": {
        "field": "inner.name"
      }
    }
  }
}

How can I possibly achieve this?
Additional Info: It will be used on Kibana later. I can change mapping to whatever I want, but AFAIK Kibana doesn't like the "Nested" type. :(

1 Answer 1

5

You need to do a value_count aggregation, by default terms only does a doc_count, but the value_count aggregation will count the number of times a given field exists.

So, for your purposes:

{
  "size": 0,
  "aggs": {
    "name": {
      "terms": {
        "field": "inner.name"
      },
      "aggs": {
        "total": {
          "value_count": {
            "field": "inner.name"
          }
        }
      }
    }
  }
}

Which returns:

"aggregations" : {
    "name" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
        {
          "key" : "John",
          "doc_count" : 2,
          "total" : {
            "value" : 3
          }
        },
        {
          "key" : "James",
          "doc_count" : 1,
          "total" : {
            "value" : 2
          }
        }
      ]
    }
  }
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, that works perfectly. Do you by any chance know how can I achieve this in a Kibana chart as well?
This seems like a different question. It depends on the visualization and I am not 100% how you want it visualized.
It would actually be a data table, just to have the count by name in the same dashboard of everything else. And yes, I understand it should be another question. sorry for the confusion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.