Search code examples
elasticsearchkibanaquerydsl

Elasticsearch query to get the value of attribute from JSON


I have pushed some data in elasticsearch. I am using Kibana to check all the data linked to logs index name. Below is how the json data looks like:

{
  "_index": "logs",
  "_type": "_doc",
  "_id": "122",
  "_version": 7,
  "_score": null,
  "_source": {
    "Data": {
      "DiskTotal": 62701268992,
      "DiskFree": 56609468416,
      "DiskStatus": "Normal",
      "Version": "2.0",
      "Ip": "192.168.0.106"
    },
    "Created": "2021-01-04T14:13:48.245760",
    "Customer": "demo1"
    
  },
  "fields": {
    "Data.UpTime": [
      "2021-01-04T14:10:05.000Z"
    ],
    "Created": [
      "2021-01-04T14:13:48.245Z"
    ]
  },
  "sort": [
    1609769628245
  ]
}

I want to write a query which can get me all the customer value in logs index name. Can anyone please help me in this. Thanks

Response:

{
  "took" : 242,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 325,
      "relation" : "eq"
    },
    "max_score" : null,
    "hits" : [ ]
  },
  "aggregations" : {
    "customers" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
        {
          "key" : "HF",
          "doc_count" : 155
        },
        {
          "key" : "HF3",
          "doc_count" : 144
        },
        {
          "key" : "HF2",
          "doc_count" : 24
        },
        {
          "key" : "HF1",
          "doc_count" : 2
        }
      ]
    }
  }
}

Solution

  • You can achieve that with a simple terms aggregation on the Customer field (ideally Customer.keyword if it exists)

    {
      "size": 0,
      "aggs": {
        "customers": {
          "terms": {
            "field": "Customer.keyword",
            "size": 100
          }
        }
      }
    }