gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 02:57:02 25 4
gpt4 key购买 nike

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

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

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

最佳答案

这是您可以执行此操作的一种方法,但它需要两个请求。为了测试,我定义了一个简单的索引并添加了一些文档:

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

关于date - 在 Elasticsearch 中按日期获取上一个和下一个文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30487320/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com