Elasticsearch script query involving root and nested values

后端 未结 1 1939
被撕碎了的回忆
被撕碎了的回忆 2020-12-21 02:12

Suppose I have a simplified Organization document with nested publication values like so (ES 2.3):

{ 
  \"organization\" : { 
    \"dateUpdated\" : 139521160         


        
相关标签:
1条回答
  • 2020-12-21 03:03

    You can not access the root values from nested query context. They are indexed as separate documents. From the 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.

    You can get the desired results with the help of copy_to parameter. Another way to do this would be to use include_in_parent or include_in_root but they might be deprecated in future and it will also increase the index size as every field of nested type will be included in root document so in this case copy_to functionality is better.

    This is a sample index

    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"
                }
              }
            }
          }
        }
      }
    }
    

    Here every value of nested_date will be copied to copy_of_nested_date so copy_of_nested_date will look something like [1401055200000,1393801200000,1221542100000] and then you could use simple query like this to get the results.

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

    You don't have to change your nested structure but you would have to reindex the documents after adding copy_to to publication dateCreated

    0 讨论(0)
提交回复
热议问题