Search code examples
c#elasticsearchnest

ElasticSearch C# NEST - How to prevent overwriting a document


When I perform an Index call, is there a way to make the call fail if a document with the same ID already exists?

I see warnings being issued, but the original document is still overwritten.


Solution

  • You can achieve this by using the _create endpoint, or by specifying OpType.Create when indexing the document

    var client = new ElasticClient();
    
    // using OpType.Create
    client.Index(new Test { Id = 1, Message = "message 1" }, i => i
        .OpType(OpType.Create)
    );
    
    // using _create endpoint
    client.Create(new Test { Id = 1, Message = "message 1" });
    

    If the document already exists, a HTTP 409 Conflict response will be returned. In both cases, you need an ID for the document that you're indexing/creating.