Search code examples
elasticsearchaggregateaggregationelasticsearch-aggregation

ElasticSearch how display all documents matching date range aggregation


Following elastic docs: https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-datehistogram-aggregation.html

Question:

How to make date range aggregation and display all documents that match to relevant date bucket just not the doc_count.

The Aggregation :

{
    "aggs" : {
        "articles_over_time" : {
            "date_histogram" : {
                "field" : "date",
                "interval" : "1M",
                "format" : "yyyy-MM-dd" 
            }
        }
    }
}

Response:

        {
            "aggregations": {
                "articles_over_time": {
                    "buckets": [
                        {
                            "key_as_string": "2013-02-02",
                            "key": 1328140800000,
                            "doc_count": 1
                        },
                        {
                            "key_as_string": "2013-03-02",
                            "key": 1330646400000,
                            "doc_count": 2  //how display whole json ??
                 
                    [ .. Here i want to display 
                           all document with array based 
                           NOT only doc_count:2.......... ]

                        },
                        ...
                    ]
                }
            }
        }

Maybe I need to do some sub-aggregation or something else?

Any ideas?


Solution

  • You have to perform top_hits sub-aggregation on date-histogram aggregation. All the options can be read from here.

    Your final aggregation would look like this

    {
      "aggs": {
        "articles_over_time": {
          "date_histogram": {
            "field": "date",
            "interval": "1M",
            "format": "yyyy-MM-dd"
          },
          "aggs": {
            "documents": {
              "top_hits": {
                "size": 10
              }
            }
          }
        }
      }
    }