Elasticsearch 按日期范围分组

Elasticsearch count in groups by date range

我有这样的文件:

{
body: 'some text',
read_date: '2017-12-22T10:19:40.223000'
}

有没有办法按日期分组查询最近10天发表的文献数?例如:

2017-12-22, 150  
2017-12-21, 79  
2017-12-20, 111  
2017-12-19, 27  
2017-12-18, 100  

是的,您可以使用 date_histogram 聚合轻松实现,如下所示:

{
  "query": {
    "range": {
      "read_date": {
        "gte": "now-10d"
      }
    }
  },
  "aggs": {
    "byday": {
      "date_histogram": {
        "field": "read_date",
        "interval": "day"
      }
    }
  }
}

要接收过去 10 天的天数,每天您可以POST以下查询:

{
  "query": {
    "range": {
      "read_date": {
        "gte": "now-11d/d",
        "lte": "now-1d/d"
      }
    }
  },

    "aggs" : {
        "byDay" : {
            "date_histogram" : {
                "field" : "read_date",
                "calendar_interval" : "1d",
                "format" : "yyyy-MM-dd" 
            }
        }
    }
}

到以下Url:http://localhost:9200/Index_Name/Index_Type/_search?size=0

将大小设置为 0 可避免执行搜索的提取阶段,从而提高请求效率。有关详细信息,请参阅 this elastic documentation