【问题标题】:Elasticsearch 5.4: Use normal and nested fields in same Painless script query?Elasticsearch 5.4:在同一个无痛脚本查询中使用普通字段和嵌套字段?
【发布时间】:2017-10-10 23:29:24
【问题描述】:

我有这样的映射:

{
  printings: { 
    type: "nested",
    properties: {
      prop1: {type: "number"}
    }  
  },
  prop2: {type: "number"}
}

然后我想构建一个这样的无痛查询:

"script": {
          "lang": "painless",
          "inline": "doc['prop1'] > (3 * doc['printings.prop2'])"
        }

但是,在 Sense 中对此进行测试是行不通的。如果我用一个简单的数字替换嵌套的 prop2,那么它确实有效。有没有办法在单个脚本查询中同时访问根属性和嵌套属性?

【问题讨论】:

    标签: elasticsearch elasticsearch-5


    【解决方案1】:

    你可以试试下面的查询。

    {
    "query": {
      "script": {
         "script": {
            "lang": "painless",
            "inline": "params['_source']['prop1'] > (2 * params['_source']['printings']['prop2'])"
         }
       }
     }
    }
    

    但是请记住这件事_source 非常慢。阅读更多关于here

    【讨论】:

      【解决方案2】:

      不幸的是,您不能从根访问嵌套上下文,也不能从嵌套访问根上下文,因为嵌套文档是单独的文档,即使它们存储在父级附近。但是您可以使用 copy_to 字段功能通过不同的映射来解决它。这是一个映射:

      {
          "mappings": {
              "sample": {
                  "properties": {
                      "printings": {
                          "type": "nested",
                          "properties": {
                              "prop2": {
                                  "type": "integer",
                                  "copy_to": "child_prop2"
                              }
                          }
                      },
                      "prop1": {
                          "type": "integer"
                      },
                      "child_prop2": {
                          "type": "integer"
                      }
                  }
              }
          }
      }
      

      在这种情况下,嵌套文档中的值将被复制到父级。您不必显式填写这个新字段,这里是批量索引的 ax 示例:

      POST http://localhost:9200/_bulk HTTP/1.1
      
      {"index":{"_index":"my_index","_type":"sample","_id":null}}
      {"printings":[{"prop2":1},{"prop2":4}],"prop1":2}
      {"index":{"_index":"my_index","_type":"sample","_id":null}}
      {"printings":[{"prop2":0},{"prop2":1}],"prop1":2}
      {"index":{"_index":"my_index","_type":"sample","_id":null}}
      {"printings":[{"prop2":1},{"prop2":0}],"prop1":2}
      

      之后你就可以使用这个查询了

      {
          "query": {
              "script": {
                  "script": {
                      "inline": "doc['prop1'].value > (3 * doc['child_prop2'].value)",
                      "lang": "painless"
                  }
              }
          }
      }
      

      第一个文档不匹配。第二个将与第一个子文档匹配。第三个将与第二个子文档匹配。

      【讨论】:

      • 我的问题是我可以将 1 到 40 个 printings 嵌套在一个文档中,所以我不需要为每个 child_prop2 实例提供一个 child_prop2 吗?
      • 我猜它会被存储为一个多值字段。因此,如果至少一个嵌套文档与此条件匹配,则该文档将匹配。添加了更详细的示例
      猜你喜欢
      • 2020-10-10
      • 1970-01-01
      • 1970-01-01
      • 2021-05-16
      • 1970-01-01
      • 1970-01-01
      • 2014-12-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多