我的elasticsearch索引包含每个文档都有一个日期字段。文件可以按日期排序。假设我有一个特定的文档id和它的日期,那么按日期获取索引中的上一个和下一个文档的最佳方法是什么?我看过带日期的模糊查询,但它不能直接解决问题。它将返回最相似的文档,但不一定返回上一个和下一个文档。
jhdbpxl91#
这里有一种方法,但需要两个请求。为了进行测试,我定义了一个简单的索引并添加了一些文档:
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"}
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" ,然后像这样得到下一个医生:
"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": {
"gt": "2015-5-23"
"sort": [
"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"
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 ] } ] }}
"lt": "2015-5-23"
"order": "desc"
"took": 1,
"total": 2,
"_id": "3",
"doc_date": "2015-5-22"
1432252800000
不知道如何在一次请求中立即完成。我会考虑一下的。以下是我用于测试的代码:http://sense.qbox.io/gist/ffeda4baeafac27dcc11e2010594015c98e6d40f
1条答案
按热度按时间jhdbpxl91#
这里有一种方法,但需要两个请求。为了进行测试,我定义了一个简单的索引并添加了一些文档:
现在我可以选择一个日期了
"2015-5-23"
,然后像这样得到下一个医生:前一个是这样的:
不知道如何在一次请求中立即完成。我会考虑一下的。
以下是我用于测试的代码:
http://sense.qbox.io/gist/ffeda4baeafac27dcc11e2010594015c98e6d40f