我有一个问题,我需要写一个Elasticsearch查询,让我找到想要的东西,首先,这是我在数据库中查询以下内容的JSON对象中的一项:
{
"data": {
"circuit": {
"version": "2.12.2",
"createdOn": "2020-02-04T10:38:11.282",
"expirationDate": "2020-02-06T05:50:00.000",
"expiredSoonNotification": false
}
},
"createdDate": "2020-02-04T10:38:11.282"
}
我需要获取所有接受此条件的物品:
now
含义:我需要从现在开始获取expirationDate小于10%的所有项目我希望我解释了我的问题,因为我不知道如何使用lt og gt
中的字段直到现在我还是那样做,但是没有用:
{
"query": {
"bool": {
"must_not": [
{
"bool": {
"must": [
{
"range": {
"data.circuit.expirationDate": {
"gt": "now",
"lt": ("data.circuit.expirationDate" - "createdDate")/10 + now
}
}
}
]
}
}
]
}
},
"sort": [
{
"createdDate": {
"order": "desc"
}
}
]
}
谢谢
您无法在range
查询中引用其他字段进行数学运算。您将需要使用Elasticsearch“无痛”脚本语言在script
查询中对逻辑进行编码。 Script
查询比其他查询要慢得多,因为需要为每个文档执行脚本。您可以通过将逻辑分为两部分来限制需要执行脚本的文档数量:
[第一部分:现在
您的查询结构将看起来像这样(伪代码):
"query": {
"bool": {
"must": { "script": ("data.circuit.expirationDate" - "createdDate")/10 + now }
"filter": { "range": ("data.circuit.expirationDate" > now) }
}
}
您还应该考虑是否真的需要精确到毫秒级的精度。在性能上,最好将now
舍入到更细的单位(例如,对于二级粒度,现在为/ s)。预先计算("data.circuit.expirationDate" - "createdDate")/10
并将计算结果直接存储在您的文档中将进一步显着提高查询性能。