Search code examples
c#elasticsearchnest

How to Update nested objects in Elasticsearch documents?


I am trying to find the best practice to update a document with nested objects: I am using the ES as a view cache:

let say I have tow entities in my SQL DB: the First one is Address and the Homes and the relation between them is one too many

Address Table has columns=> Id , Street, ZipCode

Home Table has colmns=> Id, AddressId(FK), price

And I store them in ES aggregated:

Home : {
Id: 1,
price : 3000,
Address :{
   id: 1,
   street: "blabla",
   zibcode : 12345

  }
}

if I made any change on Address I want to update all Home Documents that contains the same Address in the Home index with the new value. What I need to know how can I update all Documents in the same index in one request to ES.


Solution

  • _update_by_query is probably what you're after.

    This ain't pretty but it should do the job:

    PUT test/_doc/1
    {
      "Id": 1,
      "price": 3000,
      "Address": {
        "id": 1,
        "street": "blabla",
        "zipcode": 12345
      }
    }
    
    POST test/_update_by_query
    {
      "query": { 
        "term": {
          "Address.id": 1
        }
      },
      "script": {
        "source": "ctx._source['Address']['id'] = 2;ctx._source['Address']['street'] = 'foo';ctx._source['Address']['zipcode'] = 5678"
      }
    }
    
    GET test/_doc/1
    

    And the output then is:

    {
      "_index" : "test",
      "_type" : "_doc",
      "_id" : "1",
      "_version" : 9,
      "_seq_no" : 8,
      "_primary_term" : 1,
      "found" : true,
      "_source" : {
        "Address" : {
          "zipcode" : 5678,
          "street" : "foo",
          "id" : 2
        },
        "price" : 3000,
        "Id" : 1
      }
    }