RavenDB查询,包含父级和最后一个子条目的投影, 用于特定日期范围

问题描述 投票:1回答:1

假设我有帖子和评论集,

public class Post {
 String title;
 List<Comment> comments;
}
public class Comment {
 Date date;
 String author;
 String comment;
}

我希望能够知道某个帖子标题在特定日期范围内的最新评论。结果显示为具有以下结构的投影:

public class Result {
 String postTitle;
 Date commentDate
 String commentAuthor;
 String comment;
}

我正在努力让它发挥作用,我尝试了一些方法,但无法做到正确。我有一个索引,但我不太确定如何才能获得子元素的最后一个条目。我收到了日期范围内的所有记录,而不仅仅是最后一条记录。

这是我的索引:

public Posts_LastCommentDateRange() {
    map = "docs.Posts.SelectMany(post => post.comments, (post, comment) => new {" +
        "    post.title," +
        "    commentDate = comment.date," +
        "    commentAuthor = comment.author," +
        "    comment.comment" +
        "})";   
}

这是我的查询:

List<Result> res = session.query( Result.class, Posts_LastCommentDateRange.class )          
          .whereEquals( "title", "RavenDB Date Range" )   
          .whereBetween( "commentDate", "2019-01-02T10:27:18.7970000Z", "2019-01-25T15:01:23.8750000Z" )
          .selectFields( Result.class )
          .toList();

任何帮助或方向将不胜感激。

谢谢

dictionary indexing ravendb reduce ravendb4
1个回答
0
投票

您可以使用索引仅使用linq Max方法输出帖子最新评论,而不是为每个帖子+评论存储一个结果。

map = docs.Posts.Select(post =>
                 {
                     var latestComment = post.comments.Max(a => a.date);
                     return new {
                                  title = post.title,
                                  commentDate = latestComment.date,
                                  commentAuthor = latestComment.author,
                                  comment = latestComment.comment
                                 };
                }); 

因此,您的索引基本上会迭代您的帖子并输出仅包含最新评论的记录。然后您的查询将不必检查绝对不是最新的评论。

© www.soinside.com 2019 - 2024. All rights reserved.