Elasticsearch NEST向现有索引添加属性

时间:2018-12-20 19:28:05

标签: c# elasticsearch nest

我想向已经包含文档的现有索引添加新属性。

原始文件

[ElasticsearchType(Name = "mydocument", IdProperty = nameof(Id))]
public class MyDocument
{
    public Guid Id { get; set; } = Guid.NewGuid();

    [Date(Name = "occurredon")]
    public DateTime OccurredOn { get; set; }

    [Text(Name = "details")]
    public string Details { get; set; }
}

如何初始化和填充索引...

var client = new ElasticClient(settings);
var createResponse = client.CreateIndex("myindex", d => d.Mappings(ms => ms.Map<MyDocument>(m => m.AutoMap())));

// index many documents...
var docs= new List<MyDocument>();
docs.Add(new MyDocument { OccurredOn = DateTime.UtcNow, Details = "foo1" });
docs.Add(new MyDocument { OccurredOn = DateTime.UtcNow, Details = "foo2" });
var indexResponse = await client.IndexManyAsync(docs, "myindex");

现在,我想通过添加'collector'属性来更新文档。新文档将如下所示……

[ElasticsearchType(Name = "mydocument", IdProperty = nameof(Id))]
public class MyDocument
{
    public Guid Id { get; set; } = Guid.NewGuid();

    [Date(Name = "occurredon")]
    public DateTime OccurredOn { get; set; }

    [Text(Name = "details")]
    public string Details { get; set; }

    // new property
    [Text(Name = "collector")]
    public string CollectionHost { get; set; }
}

添加新的“收藏家”属性时,我必须发出什么一次性命令?我试过了,但是失败了。

var z = await client.MapAsync(new PutMappingRequest("myindex", typeof(MyDocument)));

我确定可以做到这一点,但也许不能使用NEST,我需要使用较低级别的API吗?

2 个答案:

答案 0 :(得分:1)

我想我想念ES和Kibana在做什么。我以为如果将具有其他属性的文档索引到现有索引中,它们将会丢失。可能不会。我只需要刷新Kibana使其快乐即可。

简而言之,我刚刚添加了一个文档,该文档利用了更新的POCO(带有“ collector”字段的POCO),然后刷新了Kibana的索引字段列表,一切都按预期运行。

猜猜我使这一过程变得比原本困难得多。不会是我最后一次想什么。

答案 1 :(得分:0)

尝试

client.Update<MyDocument, object>(documentId, d => d
    .Doc(new 
    {
        Collector = "value"
    }));

此外,请查看此答案以获取更多详细信息

https://stackoverflow.com/a/39029907/7327715