2013-02-27 113 views
2

儘管我對使用RavenDB作爲OLTP應用程序存儲的想法感到非常興奮,但我在Linq/Map-Reduce索引實現方面有點麻煩。RavenDB複雜索引

這裏是我想要做的事 - 我的文檔 -

Event { 
    UserId: "1", 
    Location : "X", 
    EventDate : "1/1/2010", 
    EventType : "type A" 
} 
... 
Event { 
    UserId: "2", 
    Location : "Y", 
    EventDate : "1/1/2011", 
    EventType : "type B" 
} 

應該執行的操作查詢/索引

「給我算對特定用戶的不同事件

Location | Count(EventA) | Count(EventB) 
--------------------------------------- 
X  | 10   |  2 
Y  | 4   | 22 
:通過位置,事件」

結果示例分組特定日期範圍

我相信這應該是直截了當的。我可能只是想念一些東西。

謝謝你的幫助!

回答

1

你在問什麼是報告的典型案例。 RavenDB並不適合(http://ravendb.net/docs/server/bundles/index-replication)。您的問題類似於SQL Server Analysis Services中多維數據集的結構。

enter image description here

在這種情況下的問題是時間範圍。如果範圍是固定的,比如說我想知道每個月的情況,你可以在索引中做到這一點,但如果範圍是臨時的,那麼我相信在Raven中這是不可能的,通過使用索引並且可能不是一個查詢,因爲你必須做分組客戶端,因此將不得不檢索大量的文檔(遠遠超過Raven的默認值128)。

但萬一有人通過例如在我們省略的時間範圍的索引搜索的多組,然後以下索引的實現,其中結果是由用戶標識分組,位置和事件類型可以是一種解決方案:

public class Index : AbstractIndexCreationTask<Index.Result> 
{ 
    public class Result 
    { 
     public string UserId { get; set; } 
     public string Location { get; set; } 
     public string EventType { get; set; } 
     public int Count { get; set; } 
    } 

    public Index() 
    { 
     Map = events => from e in events 
         select new Result 
         { 
          UserId = e.UserId, 
          Location = e.Location, 
          EventType = e.EventType, 
          Count = 1 
         }; 

     Reduce = results => from result in results 
          group result by new { result.UserId, result.Location, result.EventType } 
           into g 
           select new Result 
           { 
            UserId = g.Key.UserId, 
            Location = g.Key.Location, 
            EventType = g.Key.EventType, 
            Count = g.Sum(x => x.Count) 
           }; 
    } 
} 

這會給你這樣的結果

UserId | Location | EventType  | Count 
------------------------------------------- 
1  | X  | A    |  2 
1  | X  | B    |  4 
1  | Y  | A    | 22 
1  | Y  | B    |  6 
2  | X  | A    |  7 
2  | X  | B    |  3 
2  | Y  | A    |  9 
2  | Y  | B    | 16 

然後,您可以查詢該指數和做對查詢結果的附加分組。

+1

很好的答案。你遇到了問題的核心 - 你不能有任意的日期範圍。如果你想讓他們每天,每週,每月等分組,那麼你可以。可能使用多個索引並將結果交叉使其感覺更加隨意。我一直在計劃一會兒... – 2013-02-28 20:37:13