11

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?

Jim
  • 4,509
  • 16
  • 50
  • 80

2 Answers2

27

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()
});
Rob
  • 9,664
  • 3
  • 41
  • 43
4

I was working on a .NET client for ElasticSearch 5.x, and I was fortunate to have the following code running (as well as succeeding all unit tests) for bulk deletion using ID's:

  //IList<string> ids = ...

  var descriptor = new BulkDescriptor();

  foreach (var id in ids.Where(x => !string.IsNullOrWhiteSpace(x)))
    descriptor.Delete<T>(x => x
        .Id(id))
      .Refresh(Refresh.WaitFor);

  var response = await _client.BulkAsync(descriptor);
Burak Tasci
  • 887
  • 12
  • 18