Operations: How to Delete Documents by Query

DeleteByQueryOperation gives you the ability to delete a large number of documents with a single query. This operation is performed in the background on the server.

Syntax

public DeleteByQueryOperation(IndexQuery queryToDelete)

public DeleteByQueryOperation(IndexQuery queryToDelete, QueryOperationOptions options)
Parameters Type Description
indexName String Name of an index to perform a query on
queryToDelete IndexQuery Holds all the information required to query an index
options QueryOperationOptions Holds different setting options for base operations

Example I

// remove all documents from the server where Name == Bob using Person/ByName index
store
    .operations()
    .send(new DeleteByQueryOperation(new IndexQuery("from Persons where name = 'Bob'")));
from index 'Person/ByName' where Name = 'Bob'

Example II

// remove all documents from the server where Age > 35 using Person/ByAge index
store
    .operations()
    .send(new DeleteByQueryOperation(new IndexQuery("from 'Person/ByAge' where age < 35")));
from index 'Person/ByName' where Age < 35

Example III

// delete multiple docs with specific ids in a single run without loading them into the session
Operation operation = store
    .operations()
    .sendAsync(new DeleteByQueryOperation(new IndexQuery(
        "from People u where id(u) in ('people/1-A', 'people/3-A')"
    )));
from People u where id(u) in ('people/1-A', 'people/3-A')

WaitForCompletion

DeleteByQueryOperation is performed in the background on the server.
You have the option to wait for it using waitForCompletion.

// remove all document from server where Name == Bob and Age >= 29 using People collection
Operation operation = store.operations()
    .sendAsync(new DeleteByQueryOperation(new IndexQuery(
        "from People where Name = 'Bob' and Age >= 29"
    )));

operation.waitForCompletion();
from People where Name = 'Bob' and Age >= 29

Remarks

Map only indexes

DeleteByQueryOperation can only be performed on a map index. Executing it on map-reduce index will lead to an exception.

Batching and Concurrency

The deletion of documents matching a specified query is run in batches of size 1024. RavenDB doesn't do concurrency checks during the operation so it can happen than a document has been updated or deleted meanwhile.