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

后端 未结 4 857
旧巷少年郎
旧巷少年郎 2021-02-04 04:52

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

public void Clear() {...

Then have Raven DB cl

4条回答
  •  爱一瞬间的悲伤
    2021-02-04 05:29

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

    public void Clear()
    {
        session.Advanced.DocumentStore.DatabaseCommands.PutIndex(indexName, new IndexDefinitionBuilder
        {
            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

提交回复
热议问题