2012-01-24 38 views
2

我有以下郵政實體:RavenDb MapReduce的指標有三個從宗地圖

public class Post 
{ 
    public string Id {get;set;} 
    public string Text {get;set;} 
    public IList<Vote> Votes {get;set;} 
    public IList<Comment> Comments {get;set;} 
} 

上崗我需要檢索標識,文字,評分(投票的總和),CommentsCount的名單。我試圖創建以下MapReduce索引:

public class PostsForList: AbstractIndexCreationTask<Post, PostsForList.ReduceResult> 
{ 
    public class ReduceResult 
    { 
    public string Id { get; set; } 
    public string Text { get; set; } 
    public long Rating { get; set; } 
    public long CommentsCount { get; set; } 
    } 

    public PostsForList() 
    { 
    Map = posts => from post in posts 
           from comment in post.Comments 
           from vote in post.Votes 
           select 
           new 
           { 
            Id = post.Id, 
            Text = post.Text, 
            Rating = vote.Value /* 1 or -1 */ 
            CommentsCount = 1, 
           }; 

    Reduce = results => from result in results 
         group result by result.Id 
         into grouped 
         select 
          new 
          { 
          Id = grouped.Key, 
          Text = grouped.Select(x => x.Text).First(), 
          Rating = grouped.Sum(x => x.Rating) 
          CommentsCount = grouped.Sum(x => x.Rating), 
          }; 
    } 
} 

最初對我來說看起來很合理。但看起來像我的地圖與三個從子句將無法正常工作。我看到的唯一的其他解決方案是使用MultiMap索引和兩張地圖(一個用於投票,另一個用於評論)。但是,使用MultiMap索引時,兩個索引都查詢同一個文檔,看起來有點奇怪......還有其他解決方案嗎?

回答

3

Idsa,這裏不需要定義索引。兩個集合,VotesComments是文檔的一部分,所以只使用它們:

var posts = documentSession.Query<Post>() 
    .Skip(CurrentPage*PageSize) 
    .Take(PageSize) 
    .ToList(); // here is the db-call! all following is just in-memory 

var viewModelPosts = from post in posts 
         select new 
          { 
           post.Id, 
           post.Text, 
           Rating = post.Votes.Sum(x => x.Value), 
           CommentsCount = post.Comments.Count 
          }; 

更新: 我你真的要預先計算的結果,看看這裏:http://daniellang.net/using-an-index-as-a-materialized-view-in-ravendb/

+0

但我不想檢索所有評論和投票給客戶。我想計算服務器端的評級和VotesCount – SiberianGuy

+2

好的,在這種情況下沒有太多的價值,但它肯定是可能的,而且事實上非常簡單。我寫了一篇博客文章解釋:http://daniellang.net/using-an-index-as-a-materialized-view-in-ravendb/ –

+0

非常感謝您的幫助!請將您的博客帖子鏈接放入答案 – SiberianGuy