2016-03-02 82 views
0

我正在尝试使用RavenDb创建索引以供以后使用(例如,使用索引进行大规模删除)。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工作室在任何地方看到索引,我无法用它来查询。所以看起来索引不可用,但是以某种方式知道系统?

回答

0

首先,一个建议:让你的索引成为类。你能强烈地后键入查询使用的索引类型这样的话:

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

现在你的指数是准备:

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

然后,使用一个单一的代码行安装所有的索引在汇编去。要查询使用该索引:

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