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

两盒软妹~` 提交于 2019-12-02 22:40:46
alexn

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.

Ryan Worsley

After much experimentation I found the answer to be quite simple, although far from obvious;

public void Clear<T>()
{
    session.Advanced.DocumentStore.DatabaseCommands.PutIndex(indexName, new IndexDefinitionBuilder<T>
    {
        Map = documents => documents.Select(entity => new {})
    });

    session.Advanced.DatabaseCommands.DeleteByIndex(indexName, new IndexQuery());
}

Of course you almost certainly wouldn't define your index and do your delete in one go, I've put this as a single method for the sake of brevity.

My own implementation defines the indexes on application start as recommended by the documentation.

If you wanted to use this approach to actually index a property of T then you would need to constrain T. For example if I have an IEntity that all my document classes inherit from and this class specifies a property Id. Then a 'where T : IEntity' would allow you to use that property in the index.

It's been said in other places, but it's also worth noting that once you define a static index Raven will probably use it, this can cause your queries to seemingly not return data that you've inserted:

RavenDB Saving to disk query

I had this problem as well and this is the solution that worked for me. I'm only working in a test project, so this might be slow for a bigger db, but Ryan's answer didn't work for me.

    public static void ClearDocuments<T>(this IDocumentSession session)
    {
        var objects = session.Query<T>().ToList();
        while (objects.Any())
        {
            foreach (var obj in objects)
            {
                session.Delete(obj);
            }

            session.SaveChanges();
            objects = session.Query<T>().ToList();
        }
    }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!