RavenDB index creation error: index already exists

RavenDB index creation error: index already exists

我正在尝试使用 RavenDb 创建索引供以后使用(例如使用索引进行大量删除)。

据我所知,最好的做法是在应用程序启动时创建索引,不需要检查索引是否已经存在,因为在这种情况下,它会被简单地更新(以防万一发生了变化).

考虑到我尝试在 global.asax application_start 事件中构建自己的索引(因为我在 MVC 应用程序中进行游戏)。这是我创建索引的代码:

store.DatabaseCommands.PutIndex("Xlns/ProductItems/ByCatalogueId",
      new IndexDefinitionBuilder<ProductItem>
          {
              Map = items => from product in items
                             select new
                                    {
                                       CatalogueId = product.CatalogueId
                                    }
           }
);

很简单,不是吗? 太糟糕了,当我第一次在一个空的 RavenDB 上启动应用程序时,它没有引发任何错误(即使我似乎无法使用索引),并且从第二次开始,它给了我这个错误:Cannot put index: Xlns/ProductItems/ByCatalogueId, index already exists

(不那么)有趣的是,我无法使用 RavenDB studio 在任何地方看到索引,而且我无法使用它来查询。所以看起来索引不可用但系统以某种方式知道?

首先,一个建议:让你的索引是 类。这样您就可以稍后使用索引类型强类型查询:

public class ProductItems_ByCatalogueId : AbstractIndexCreationTask<ProductItem>
{
    public ProductItems_ByCatalogueId()
    {
        Map = items => from product in items
                       select new
                       {
                           CatalogueId = product.CatalogueId
                       }
    }
}

然后,使用一行代码在程序集中安装所有索引:

// Inside Global.asax, inside .Initialize():
IndexCreation.CreateIndexes(this.GetType().Assembly, store); 

现在您的索引已准备就绪。要使用此索引进行查询:

var products = ravenSession.Query<ProductItem, ProductItems_ByCatalogueId>()
    .Where(...)

与:

    documentStore.DatabaseCommands.GetIndex("BlogPosts/ByTitles")

知道一个索引是否存在,就知道要不要加; ravendb 文档建议使用 类 来定义静态索引:http://ravendb.net/docs/article-page/2.5/csharp/client-api/querying/static-indexes/defining-static-index

Judah Himango 的例子与您在 link

中找到的完全(并且正确)