Raven DB:如何删除给定类型的所有文档 [英] Raven DB: How can I delete all documents of a given type

查看:28
本文介绍了Raven DB:如何删除给定类型的所有文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更具体地说,在 Raven DB 中,我想创建一个具有类似签名的通用方法;

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

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

然后让 Raven DB 清除给定类型的所有文档.

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

我从 Ayende 对类似问题的其他帖子中了解到,您需要一个适当的索引来批量执行此操作.

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?

推荐答案

经过多次实验,我发现答案非常简单,虽然远非显而易见;

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.

如果您想使用这种方法来实际索引 T 的属性,那么您需要约束 T.例如,如果我有一个 IEntity,我的所有文档类都继承自该 IEntity,并且此类指定了一个属性 Id.然后'where T : IEntity' 将允许您在索引中使用该属性.

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.

在其他地方已经说过了,但同样值得注意的是,一旦你定义了一个静态索引,Raven 可能会使用它,这可能会导致你的查询似乎没有返回你插入的数据:

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 保存到磁盘查询

这篇关于Raven DB:如何删除给定类型的所有文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆