我希望能够通过子列表中的约束来查询由计数排序的RavenDB中的前10个文档。这是我的实体:
public class Post
{
public string Title { get; set; }
public List<Like> Likes { get; set; }
}
public class Like
{
public DateTime Created { get; set; }
}
我尝试过以下查询:
var oneMonthAgo = DateTime.Today.AddMonths(-1);
session
.Query<Post>()
.OrderByDescending(x => x.Likes.Count(y => y.Created > oneMonthAgo))
.Take(10);
Raven投诉应该对索引时间而不是查询时间进行计数。我已经尝试使用以下代码将计数移动到索引:
public class PostsIndex : AbstractIndexCreationTask<Post>
{
public PostsIndex()
{
var month = DateTime.Today.AddMonths(-1);
Map = posts => from doc in posts
select
new
{
doc.Title,
LikeCount = doc.Likes.Count(x => x.Created > month),
};
}
}
添加此索引时,Raven会抛出错误500。
怎么办?
答案 0 :(得分:1)
你可以通过创建一个Map / Reduce索引来展平帖子/喜欢,然后查询它。
索引:
public class PostLikesPerDay : AbstractIndexCreationTask<Post, PostLikesPerDay.Result>
{
public PostLikesPerDay()
{
Map = posts => from post in posts
from like in post.Likes
select new Result
{
Title = post.Title,
Date = like.Created,
Likes = 1
};
Reduce = results => from result in results
group result by new
{
result.Title,
result.Date.Date
}
into grp
select new Result
{
Title = grp.Key.Title,
Date = grp.Key.Date,
Likes = grp.Sum(l => l.Likes)
};
}
public class Result
{
public string Title { get; set; }
public DateTime Date { get; set; }
public int Likes { get; set; }
}
}
查询:
using (var session = store.OpenSession())
{
var oneMonthAgo = DateTime.Today.AddMonths(-1);
var query = session.Query<PostLikesPerDay.Result, PostLikesPerDay>()
.Where(y => y.Date > oneMonthAgo)
.OrderByDescending(p => p.Likes)
.Take(10);
foreach (var post in query)
{
Console.WriteLine("'{0}' has {1} likes on {2:d}", post.Title, post.Likes, post.Date);
}
}