假设我有以下索引:
public class PostsForList: AbstractIndexCreationTask<Post, PostsForList.ReduceResult>
{
public class ReduceResult
{
public string Id { get; set; }
public string Title { get; set; }
public long CommentsCount { get; set; }
}
public PostsForList()
{
Map = posts => from post in posts
select
new
{
Id = post.Id,
Title = post.Title,
CommentsCount = post.Comments,
};
}
}
如果我执行它,RavenDb 不仅会返回 Id、Title 和 CommentsCount,还会返回整个 Post 文档。但是我不需要整个文档(假设它包含很多其他内容)。
正如我所理解的,现在有两种解决方案:
查询的 AsProjection。我不喜欢
此解决方案受性能和额外磁盘空间消耗的原因影响。
它更像是解决方法而不是解决方案。
实际上不会减少任何东西。它看起来像更好的解决方案,但它
实现这个假的 Reduce 部分很烦人。
那么为什么没有更自然的解决方案(或者我可能只是不知道)?它是一个概念性的解决方案吗?
最佳答案
您可以使用 Projections feature使用 RavenDB 进行转换。
这只是在 RavenDB 从文档存储中提取 Json 文档后改变了它的形状,因此字段不必标记为 Stored
让它工作
public PostsForList()
{
Map = posts => from post in posts
select
new
{
Id = post.Id,
Title = post.Title,
CommentsCount = post.Comments,
};
TransformResults =
(database, posts) => from post in posts
select new { post.Id, post.Title, post.CommentsCount };
}
您还需要我们
.As<new type>
当你查询这个索引时,否则 RavenDB 会报错。像这样的东西:session.Query<Post, PostTitleCommentsCount>()
.Where(x => x.Title == "blah")
.As<PostTitleCommentsCount>()
.ToList();
它最常用于允许连接,参见 this blog post 了解更多信息,但也适用于这种情况。
关于.net - RavenDb 仅返回索引字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9007415/