Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I update an existing document inside ElasticSearch index using NEST?

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?

like image 636
kheya Avatar asked May 22 '14 01:05

kheya


People also ask

Can you update a document in Elasticsearch?

The script can update, delete, or skip modifying the document. The update API also supports passing a partial document, which is merged into the existing document. To fully replace an existing document, use the index API.

How do I replace a document in Elasticsearch?

In Elasticsearch, to replace a document you simply have to index a document with the same ID and it will be replaced automatically. If you would like to update a document you can either do a scripted update, a partial update or both.

What is Elasticsearch Upsert?

Upserts are "Update or Insert" operations. This means an upsert attempts to run your update script, but if the document does not exist (or the field you are trying to update doesn't exist), default values are inserted instead.


1 Answers

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.

like image 84
Paige Cook Avatar answered Sep 23 '22 03:09

Paige Cook