Search code examples
elasticsearchnest

Nest DeleteByQuery without the Object name


I want to send a Nest delete request to elasticsearch without specifying the object which I don't have. I've seen solutions like:

var response = elasticClient.DeleteByQuery<MyClass>(q => q                
            .Match(m => m.OnField(f => f.Guid).Equals(someObject.Guid))            
            );

From: DeleteByQuery using NEST and ElasticSearch

As I'm just reading plain text from a queue I don't have access to the MyClass object to use with the delete request. Basically I just want to delete all documents in an index (whose name I know) where a variable matches for example ordId = 1234. Something like:

    var response = client.DeleteByQuery<string>( q => q
        .Index(indexName)
        .AllTypes()
        .Routing(route)
        .Query(rq => rq
            .Term("orgId", "1234"))
    );

I see that the nest IElasticClient interface does have a DeleteByQuery method that doesn't require the mapping object but just not sure how to implement it.


Solution

  • You can just specify object as the document type T for DeleteByQuery<T> - just be sure to explicitly provide the index name and type name to target in this case. T is used to provide strongly type access within the body of the request only. For example,

    var client = new ElasticClient();
    
    var deleteByQueryResponse = client.DeleteByQuery<object>(d => d
        .Index("index-name")
        .Type("type-name")
        .Query(q => q
            .Term("orgId", "1234")
        )
    );
    

    Will generate the following query

    POST http://localhost:9200/index-name/type-name/_delete_by_query
    {
      "query": {
        "term": {
          "orgId": {
            "value": "1234"
          }
        }
      }
    }
    

    Replace _delete_by_query with _search in the URI first, to ensure you're targeting the expected documents :)