如何使用NEST更新ElasticSearch索引中的现有文档?

khe*_*eya 21 c# elasticsearch nest

我正在尝试更新现有的索引文档.我有索引标签,标题和所有者字段.现在,当用户更改标题时,我需要查找并更新索引中的文档.

我应该更新和替换整个文档还是只更改标题字段?

public void UpdateDoc(ElasticsearchDocument doc)
{
 Uri localhost = new Uri("http://localhost:9200");
 var setting = new ConnectionSettings(localhost);
 setting.SetDefaultIndex("movies");
 var client = new ElasticClient(setting);

 IUpdateResponse resp = client.Update<ElasticsearchDocument, IndexedDocument>(
                                  d => d.Index("movies")
                                        .Type(doc.Type)
                                        .Id(doc.Id), doc);
}
Run Code Online (Sandbox Code Playgroud)

它只是不起作用.上面的代码生成语法错误.有没有人知道使用ElasticSearch的C#NEST客户端执行此操作的正确方法?

Pai*_*ook 18

我已使用如下方法使用NEST成功更新了我的Elasticsearch索引中的现有项目.请注意,在此示例中,您只需发送包含要更新的字段的部分文档.

    // Create partial document with a dynamic
    dynamic updateDoc = new System.Dynamic.ExpandoObject();
    updateDoc.Title = "My new title";

    var response = client.Update<ElasticsearchDocument, object>(u => u
        .Index("movies")
        .Id(doc.Id)
        .Document(updateDoc)
     );
Run Code Online (Sandbox Code Playgroud)

您可以在GitHub源中找到更多在NEST更新单元测试中发送更新的方法示例.


Jon*_*wik 13

实际上对于Nest 2来说:

dynamic updateFields = new ExpandoObject();
updateFields.IsActive = false;
updateFields.DateUpdated = DateTime.UtcNow;

await _client.UpdateAsync<ElasticSearchDoc, dynamic>(new DocumentPath<ElasticSearchDoc>(id), u => u.Index(indexName).Doc(updateFields))
Run Code Online (Sandbox Code Playgroud)


Ali*_*yat 11

Nest 7.x 中更好的解决方案:

 await _client.UpdateAsync<ElasticSearchDoc>(doc.Id, u => u.Index("movies").Doc(new ElasticSearchDoc { Title = "Updated title!" }));
Run Code Online (Sandbox Code Playgroud)