Skip to main content

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

DeleteByQueryOperation DeleteByQueryOperation<TEntity, TIndexCreator>(
Expression<Func<TEntity, bool>> expression,
QueryOperationOptions options = null)
where TIndexCreator : AbstractIndexCreationTask, new();

DeleteByQueryOperation DeleteByQueryOperation<TEntity>(
string indexName, Expression<Func<TEntity, bool>> expression,
QueryOperationOptions options = null);

DeleteByQueryOperation DeleteByQueryOperation(
IndexQuery queryToDelete, QueryOperationOptions options = null);
ParametersTypeDescription
indexNamestringName of an index to perform a query on
expressionExpression<Func<T, bool>>The LINQ expression (the query that will be performed)
queryToDeleteIndexQueryHolds all the information required to query an index
optionsQueryOperationOptionsHolds different setting options for base operations

Example I

// remove all documents from the server where Name == Bob using Person/ByName index
var operation = store
.Operations
.Send(new DeleteByQueryOperation<Person>("Person/ByName", x => x.Name == "Bob"));

Example II

// remove all documents from the server where Age > 35 using Person/ByAge index
var operation = store
.Operations
.Send(new DeleteByQueryOperation<Person, Person_ByAge>(x => x.Age < 35));

Example III

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

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
var operation = store
.Operations
.Send(new DeleteByQueryOperation(new IndexQuery
{
Query = "from People where Name = 'Bob' and Age >= 29"
}));

operation.WaitForCompletion(TimeSpan.FromSeconds(15));

Remarks

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

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.