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();

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

谢谢

4

1 回答 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
                                 };
                }); 

因此,您的索引基本上是遍历您的帖子并输出仅包含最新评论的记录。这样您的查询就不必检查绝对不是最新的评论。

于 2019-03-31T23:44:02.803 回答