Raven DB: How can I delete all documents of a given type

Ryan Worsley picture Ryan Worsley · Apr 13, 2012 · Viewed 10.3k times · Source

More specifically in Raven DB, I want to create a generic method with a signature like;

public void Clear<T>() {...

Then have Raven DB clear all documents of the given type.

I understand from other posts by Ayende to similar questions that you'd need an index in place to do this as a batch.

I think this would involve creating an index that maps each document type - this seems like a lot of work.

Does anyone know an efficient way of creating a method like the above that will do a set delete directly in the database?

Answer

alexn picture alexn · Oct 24, 2012

I assume you want to do this from the .NET client. If so, use the standard DocumentsByEntityName index:

var indexQuery = new IndexQuery { Query = "Tag:" + collectionName };
session.Advanced.DocumentStore.DatabaseCommands.DeleteByIndex(
   "Raven/DocumentsByEntityName", 
   indexQuery, 
   new BulkOperationOptions { AllowStale = true });

var hilo = session.Advanced.DocumentStore.DatabaseCommands.Get("Raven/H‌​ilo/", collectionName);
if (hilo != null) {
    session.Advanced.DocumentStore.DatabaseCommands.Delete(hilo.‌​Key, hilo.Etag);
}

Where collectionName is the actual name of your collection.

The first operation deletes the items. The second deletes the HiLo file.

Also check out the official documentation - How to delete or update documents using index.