Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to update nested field by query?

I am using update by query plugin (https://github.com/yakaz/elasticsearch-action-updatebyquery/) to update documents by query. In my case, there is nested field in document, the mapping is something like this:

"mappings": {
  "mytype": {
    "properties": {
      "Myfield1": {
        "type": "nested",
        "properties": {
          "field1": {
            "type": "string"
          },
          "field2": {
            "type": "long"
          }
        }
      },
      "Title": {
        "type": "string"
      }
    }
  }
}

Then I want to update the nested field Myfield1 by query with following request:

But unfortunately, it does not work.

{
  "query": {
    "match": {
      "Title": "elasticsearch"
    }
  },
  "script": "ctx._source.Myfield1 = [{'nestfield1':'foo blabla...','nestfield2':100},{'nestfield1':'abc...','nestfield2':200}]"
}

Does update by query support nested object?

BTW: any other ways to update document by query?

Is the update by query plugin the only choice?

like image 368
Youxu Avatar asked Dec 08 '22 03:12

Youxu


2 Answers

This example uses _update_by_query

POST indexname/type/_update_by_query
{
  "query": {
    "match": {
      "Title": "elasticsearch"
    }
  },
  "script": {
    "source": "ctx._source.Myfield1= params.mifieldAsParam",
    "params": {
      "mifieldAsParam": [
        {
          "nestfield1": "foo blabla...",
          "nestfield2": 100
        },
        {
          "nestfield1": "abc...",
          "nestfield2": 200
        }
      ]
    },
    "lang": "painless"
  }
}
like image 151
AFO Avatar answered Dec 24 '22 02:12

AFO


Nested elements need to be iterated in painless script to update values

POST /index/_update_by_query
{
  "script": {
    "source": "for(int i=0;i<=ctx._source['Myfield1'].size()-1;i++){ctx._source.Myfield1[i].field1='foo blabla...';ctx._source.Myfield1[i].field2=100}",
    "lang": "painless"
  },
  "query": {
     "match": {
        "Title": "elasticsearch"
     }
  }
}

Nested elements value update if index is known

POST /index/_update_by_query
{
  "script": {
    "source": "ctx._source.Myfield1[0].field1='foo blabla...';ctx._source.Myfield1[0].field2=100;ctx._source.Myfield1[1].field1='abc...';ctx._source.Myfield1[1].field2=200;",
    "lang": "painless"
  },
  "query": {
    "match": {
         "Title": "elasticsearch"
    }
  }
}
like image 21
karthi.613 Avatar answered Dec 24 '22 04:12

karthi.613