在Elasticsearch中按日期获取上一个和下一个文档

时间:2015-05-27 15:49:32

标签: date elasticsearch

我的Elasticsearch索引包含每个都有日期字段的文档。文件可按日期排序。

假设我有一个特定的文档ID及其日期,按日期在索引中获取上一个和下一个文档的最佳方法是什么?

我查看了带日期的模糊查询,但它没有直接解决问题。它将返回最相似的文档,但不一定是前一个和下一个文档。

1 个答案:

答案 0 :(得分:1)

这是你可以做到的一种方式,但需要两个请求。为了测试我定义了一个简单的索引并添加了一些文档:

PUT /test_index
{
   "settings": {
      "number_of_shards": 1
   },
   "mappings": {
      "doc": {
         "properties": {
            "doc_date": {
               "type": "date",
               "format": "YYYY-MM-dd"
            }
         }
      }
   }
}

POST /test_index/doc/_bulk
{"index":{"_id":1}}
{"doc_date":"2015-5-21"}
{"index":{"_id":3}}
{"doc_date":"2015-5-22"}
{"index":{"_id":2}}
{"doc_date":"2015-5-23"}
{"index":{"_id":4}}
{"doc_date":"2015-5-24"}
{"index":{"_id":6}}
{"doc_date":"2015-5-25"}
{"index":{"_id":5}}
{"doc_date":"2015-5-26"}

现在我可以选择一个日期,比如"2015-5-23",然后获取下一个文档:

POST /test_index/_search
{
   "size": 1,
   "query": {
      "constant_score": {
         "filter": {
            "range": {
               "doc_date": {
                  "gt": "2015-5-23"
               }
            }
         }
      }
   },
   "sort": [
      {
         "doc_date": {
            "order": "asc"
         }
      }
   ]
}
...
{
   "took": 2,
   "timed_out": false,
   "_shards": {
      "total": 1,
      "successful": 1,
      "failed": 0
   },
   "hits": {
      "total": 3,
      "max_score": null,
      "hits": [
         {
            "_index": "test_index",
            "_type": "doc",
            "_id": "4",
            "_score": null,
            "_source": {
               "doc_date": "2015-5-24"
            },
            "sort": [
               1432425600000
            ]
         }
      ]
   }
}

和前一个像这样:

POST /test_index/_search
{
   "size": 1,
   "query": {
      "constant_score": {
         "filter": {
            "range": {
               "doc_date": {
                  "lt": "2015-5-23"
               }
            }
         }
      }
   },
   "sort": [
      {
         "doc_date": {
            "order": "desc"
         }
      }
   ]
}
...
{
   "took": 1,
   "timed_out": false,
   "_shards": {
      "total": 1,
      "successful": 1,
      "failed": 0
   },
   "hits": {
      "total": 2,
      "max_score": null,
      "hits": [
         {
            "_index": "test_index",
            "_type": "doc",
            "_id": "3",
            "_score": null,
            "_source": {
               "doc_date": "2015-5-22"
            },
            "sort": [
               1432252800000
            ]
         }
      ]
   }
}

不确定如何在单个请求中执行此操作。我会考虑一下。

以下是我用于测试的代码:

http://sense.qbox.io/gist/ffeda4baeafac27dcc11e2010594015c98e6d40f