问题
I am trying to update an existing indexed document. I have indexed tags, title and owners field. Now when the user changes the title, I need to find and update the document inside the index.
Should I update and replace the entire document or just the title field?
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);
}
It just doesn't work. The code above generates a syntax error. Does anyone know the correct way to do this using the C# NEST client of ElasticSearch?
回答1:
I have successfully updated existing items in my Elasticsearch index with NEST using a method like the following. Note in this example, you only need to send a partial document with the fields that you wish to be updated.
// 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)
);
You can find more examples of ways to send updates in the NEST Update Unit Tests from the GitHub Source.
回答2:
Actually for Nest 2 it's:
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))
回答3:
For Nest 2 to update an POCO that already include an ID field:
var task = client.UpdateAsync<ElasticsearchDocument>(
new DocumentPath<ElasticsearchDocument>(doc), u =>
u.Index(indexName).Doc(doc));
回答4:
A better solution in Nest 7.x:
await _client.UpdateAsync<ElasticSearchDoc>(doc.Id, u => u.Index("movies").Doc(new ElasticSearchDoc { Title = "Updated title!" }));
来源:https://stackoverflow.com/questions/23796286/how-do-i-update-an-existing-document-inside-elasticsearch-index-using-nest