2016-03-02 48 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(...)