ElasticSearch.Net - 使用多个组件更新数组

时间:2015-09-09 12:04:16

标签: c# elasticsearch elasticsearch-net

我使用ElasticSearch索引数据,但我在更新特定字段时遇到问题。 JSON的片段如下:

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

 ]
 }

我需要添加一个新的person对象,例如:

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

我的People定义如下:

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

通过执行以下操作更新color没有任何问题:

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"))
);

我无法弄清楚如何更新person字段,因为它是Person个对象的列表而不是字符串列表。

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:2)

我以前通过使用匿名对象并向Elasticsearch发送部分文档更新来更新所需的部分来完成此操作。

这是一个应该有用的代码片段......

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()
        );