【问题标题】:ElasticSearch: range date with fields inside fieldsElasticSearch:范围日期与字段内的字段
【发布时间】:2020-05-23 10:38:34
【问题描述】:

我有一个问题,我需要编写一个弹性搜索查询来提供我所寻找的内容, 首先,这是我在 db 中查询的 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"
}

我需要的是获取所有接受此条件的项目:

现在

含义:我需要从现在开始获取所有 expireDate 小于 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"
      }
    }
  ]
}

谢谢

【问题讨论】:

  • 您的映射是什么,到目前为止您尝试过什么?请看stackoverflow.com/help/on-topic
  • @ibexit 我添加了我到目前为止尝试过的内容
  • 只是为了确定,这是搜索文档的公式:expirationDate > now && expirationDate < (expirationDate - createdDate)/10 + now
  • @ibexit 没错

标签: json elasticsearch elasticsearch-5


【解决方案1】:

您不能在 range-查询中引用其他字段进行数学运算。您需要使用 Elasticsearch“无痛”脚本语言在 script-query 中编码您的逻辑。 Script-queries 比其他查询慢得多,因为脚本需要为每个文档执行。您可以通过将逻辑分成两部分来限制执行脚本的文档数量:

  1. "data.circuit.expirationDate" > now
  2. "data.circuit.expirationDate" < (("data.circuit.expirationDate" - "createdDate")/10 + now)

您的查询结构需要如下所示(伪代码):

"query": {
  "bool": {
    "must": { "script": "data.circuit.expirationDate" < ("data.circuit.expirationDate" - "createdDate")/10 + now) }
    "filter": { "range": "data.circuit.expirationDate" > now }
  }
}

您还应该考虑是否真的需要精确到毫秒级。在性能方面,将now 舍入到更细粒度的单位会更好(例如,now/s 用于二级粒度)。

预先计算 ("data.circuit.expirationDate" - "createdDate")/10 并将计算结果直接存储在您的文档中将进一步显着提高查询性能。

【讨论】:

    猜你喜欢
    • 2015-10-24
    • 2014-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多