How to delete several documents by ID in one operation using Elasticsearch Nest

Jim picture Jim · Jun 24, 2015 · Viewed 7.8k times · Source

I am building some abstraction functions for my application to call, which will hit elasticsearch through Nest. One of such functions is a Delete(string id) call, which is easy to accomplish. I have done this as follows:

public void Delete(string id)
{
    esClient.Delete(id);
}

Now let's say I want to do the same thing, but operate on several documents simultaneously. My original hunch was to do something like this:

public void Delete(IEnumerable<string> ids)
{
    esClient.DeleteMany(ids); // won't compile
}

As my comment states, doing this won't compile. What is the proper way of batch deleting documents by ID in Nest?

Answer

Rob picture Rob · Jun 24, 2015

To use esClient.DeleteMany(..) you have to pass collection of objects to delete.

var objectsToDelete = new List<YourType> {.. };
var bulkResponse = client.DeleteMany<YourType>(objectsToDelete);

You can get around this by using following code:

var ids = new List<string> {"1", "2", "3"};
var bulkResponse = client.DeleteMany<YourType>(ids.Select(x => new YourType { Id = x }));

Third option, use bulk delete:

var bulkResponse = client.Bulk(new BulkRequest
{
    Operations = ids.Select(x => new BulkDeleteOperation<YourType>(x)).Cast<IBulkOperation>().ToList()
});