涉及根值和嵌套值的 Elasticsearch 脚本查询

标签 elasticsearch

假设我有一个简化的 Organization 文档,其中包含嵌套的发布值,如下所示 (ES 2.3):

{ 
  "organization" : { 
    "dateUpdated" : 1395211600000,

    "publications" : [ 
      { 
        "dateCreated" : 1393801200000
      },
      { 
        "dateCreated" : 1401055200000
      }
    ]
  }
}

我想找到所有发布日期为 < 组织更新日期:

的组织
{
  "query": {
    "nested": {
      "path": "publications",
      "query": {
        "bool": {
          "filter": [
            {
              "script": {
                "script": "doc['publications.dateCreated'].value < doc['dateUpdated'].value"
              }
            }
          ]
        }
      }
    }
  }
}

我的问题是,当我执行嵌套查询时,嵌套查询无法访问根文档值,因此 doc['dateUpdated'].value 无效,我得到 0 次匹配.

有没有办法将值传递到嵌套查询中?或者我的嵌套方法完全不在这里?如有必要,我想避免仅为出版物创建单独的文档。

谢谢。

最佳答案

您无法从嵌套查询上下文中访问根值。它们被索引为单独的文档。来自documentation

The nested clause “steps down” into the nested comments field. It no longer has access to fields in the root document, nor fields in any other nested document.

您可以借助 copy_to 获得想要的结果范围。另一种方法是使用 include_in_parentinclude_in_root 但它们可能是 deprecated将来它还会增加索引大小,因为嵌套类型的每个字段都将包含在根文档中,因此在这种情况下 copy_to 功能更好。

这是一个示例索引

PUT nested_index
{
  "mappings": {
    "blogpost": {
      "properties": {
        "rootdate": {
          "type": "date"
        },
        "copy_of_nested_date": {
          "type": "date"
        },
        "comments": {
          "type": "nested",
          "properties": {
            "nested_date": {
              "type": "date",
              "copy_to": "copy_of_nested_date"
            }
          }
        }
      }
    }
  }
}

这里 nested_date 的每个值都将被复制到 copy_of_nested_date 所以 copy_of_nested_date 看起来像 [1401055200000,1393801200000,1221542100000] 然后你可以使用这样的简单查询来得到结果。

{
  "query": {
    "bool": {
      "filter": [
        {
          "script": {
            "script": "doc['rootdate'].value < doc['copy_of_nested_date'].value"
          }
        }
      ]
    }
  }
}

您不必更改嵌套结构,但您必须在将 copy_to 添加到 publication dateCreated 之后重新索引文档。 p>

关于涉及根值和嵌套值的 Elasticsearch 脚本查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40095499/

相关文章:

elasticsearch - Elasticsearch:禁用索引编制,但将copy_to应用于字段

elasticsearch - RestHighLevelClient 不能与 elasticsearch 7 BulkProcessor 一起使用。应该使用哪个客户端?

python - Elasticsearch 查询过滤

amazon-web-services - 不允许重新索引 Elasticsearch?

java - ElasticSearch JAVA API 查找给定索引的别名

elasticsearch - 如何在 Elasticsearch 中添加文档?

node.js - Elasticsearch 返回类型

elasticsearch - 我们可以在不为 Elasticsearch 指定文档 ID 的情况下进行批量索引吗?

elasticsearch - Elasticsearch: bool 'should'下的嵌套查询不返回结果

bash - 如何创建多行 curl 字符串,变量包含在单引号和双引号中?