Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ravendb

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?

like image 898
Ryan Worsley Avatar asked Apr 13 '12 18:04

Ryan Worsley


1 Answers

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.

like image 122
alexn Avatar answered Feb 20 '23 04:02

alexn