0

I've got data indexed using ElasticSearch, and I'm having trouble updating a particular field. A snippet of the JSON is as follows:

 {
 "_index": "indexName",
 "_type": "type",
 "_id": "00001",
 "colors": [
     "red",
     "green"
 ]
 "place": "london",
 "person": [
      {
           "name": "john",
           "age": "27",
           "eyes": "blue"
      }
      {
           "name": "mary",
           "age": "19",
           "eyes": "green"
      }

 ]
 }

I need to add in a new person object, something like:

{
    "name": "jane",
    "age": "30",
    "eyes": "grey"
}

I've got People defined as follows:

public class People
{
    public List<string> colors {get; set; }
    public string place {get; set; }
    public List<Person> person {get; set; }
}
public class Person
{
    public string name {get; set; }
    public string age {get; set; }
    public string eyes {get; set; }
}

I updated color with no problems by doing:

client.Update<People>(u => u
    .Id(u.Id)
    .Index(u.Index)
    .Type(u.Type)
    .Script("if ctx._source.containsKey(\"color\")) { ctx._source.color += color; } else { ctx._source.color = [color] }")
    .Params(p => p
        .Add("color", "pink"))
);

I can't figure out how to update the person field though, as it's a list of Person objects rather than a list of strings.

Any help is greatly appreciated!

helencrump
  • 1,351
  • 1
  • 18
  • 27

1 Answers1

2

I have done this previously by using an anonymous object and sending a partial document update to Elasticsearch to only update the needed section.

Here is a code snippet that should work...

var peopleId = //Get Id of document to be updated.
var persons = new List<Person>(3);
persons.Add(new Person { name = "john", eyes = "blue", age = "27" });
persons.Add(new Person { name = "mary", eyes = "green", age = "19" });
persons.Add(new Person { name = "jane", eyes = "grey", age = "30" });

var response = Client.Update<People, object>(u => u
            .Id(peopleId)
            .Doc(new { person = persons})
            .Refresh()
        );
Paige Cook
  • 22,415
  • 3
  • 57
  • 68
  • No good - nothing gets updated. I've tried different variations of passing in a Person object to the update statement, none of which have worked. – helencrump Sep 09 '15 at 14:22
  • Looks like the .Doc property should be set with the update. I have updated my example above accordingly.You might want to try using an anonymous object as shown in the NEST documentation - http://nest.azurewebsites.net/nest/core/update.html under the Anonymous objects as partial documents section. – Paige Cook Sep 09 '15 at 14:48
  • I've tried this too with no success, but thanks for the suggestion. :) – helencrump Sep 09 '15 at 14:49
  • 1
    I was able to get this working using the anonymous object. I have updated my answer and included a full working example at https://dotnetfiddle.net/2v08C6 – Paige Cook Sep 09 '15 at 16:43