简体   繁体   中英

Elasticsearch php : aggregations of documents with date interval

I'm trying to build a faceted search using Elasticsearch-php 6.0, but I'm having a hard time to figure out how to use a date range aggregation. Here's what I'm trying to do :

Mapping sample :

"mappings": {
  "_doc": {
    "properties": {
      ...
      "timeframe": {
        "properties": {
          "gte": {
            "type": "date",
            "format": "yyyy"
          },
          "lte": {
            "type": "date",
            "format": "yyyy"
          }
        }
      }
      ...

In my document, I have this property:

"timeframe":[{"gte":"1701","lte":"1800"}]

I want to be able display a facet with a date range slider, where the user can input a range (min value - max value). Ideally, those min-max values should be returned by the Elasticsearch aggregation automatically given the current query.

Here's the aggregation I'm trying to write in "pseudo code", to give you an idea:

"aggs": {
  "date_range": {
      "field": "timeframe",
      "format": "yyyy",
      "ranges": [{
          "from": min(timeframe.gte),
          "to": max(timeframe.lte)
      }]
  }
}

I think I need to use Date Range aggregation, min/max aggregation, and pipeline aggregations, but the more I read about them, the more I'm confused. I can't find how to glue this whole world together.

Keep in mind I can change the mapping and / or the document structure if this is not the correct way to achieve this.

Thanks !

As for me with the official "elasticsearch/elasticsearch" package of ES itself, I was able to find a range of my required documents with this document. You need to read the documentation as you'll be needing the format.

$from_date = '2018-03-08T17:58:03Z';
$to_date = '2018-04-08T17:58:03Z';
$params = [
        'index' => 'your_index',
        'type'  => 'your_type',
        'body'  => [
            'query' => [
                'range' => [
                    'my_date_field' => [
                        //gte = great than or equal, lte = less than or equal
                        'gte'    => $from_date,
                        // 'lte'     => $to_date,
                        'format' => "yyyy-MM-dd||yyyy-MM-dd'T'HH:mm:ss'Z'",
                        'boost'  => 2.0
                    ]
                ]
            ],
        ]
    ];
    $search = $client->search($params);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM