Gilbert Williams
Gilbert Williams

Reputation: 1050

ElasticSearch NEST bulk upsert

I conducted the following piece of code which performs partial update to the Content field in existing documents:

var partials = new object[]
            {
                new{
                Id = 1337,
                Content = "test"
            }
            };

            var response = await _elastic.BulkAsync(b => b
                .Index(indexName)
                                         .Index(indexName)
                                         .UpdateMany(partials, (bu, d) => bu.Doc(d))
                                         );

However, I want to upsert this document if it does not exist and I'm not sure how. I tried to change bu.Doc to bu.Upsert however it expects a script.

Upvotes: 1

Views: 1163

Answers (1)

Simon Lang
Simon Lang

Reputation: 592

Doc() and Upsert() work the same as described in the elastic "Update API" documentation: https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update.html


With Doc() you specify a partial document to update an existing document. This is not an upsert, only an update


With Upsert() the documentation states:

If the document does not already exist, the contents of the upsert element are inserted as a new document. If the document exists, the script is executed

So the upsert part specifies what happens if the document does not exist. You need to add a script which is executed against the existing document.


There is also the doc_as_upsert field in conjunction with doc. If set to true, then the document in doc is inserted if it does not exist, else it is updated. You can set it with bu.DocAsUpsert()

Upvotes: 0

Related Questions