RavenDb Returns only indexed fields

Suppose I have the following index:

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, }; } } 

If I completed it, RavenDb will return not only Id, Title, and CommentsCount, but the entire Post document. But I do not need the whole document (suppose it contains many other things).

As I donโ€™t know, now there are two solutions:

  • Mark the index fields as saved and call AsProjection for the query. I do not like this solution for performance and additional disk requirements. This is more a workaround than a solution.
  • Convert the map index to the MapReduce index by introducing some fake part of the reduction (equal to the map), which will actually reduce nothing. This seems like the best solution, but it is annoying to implement this fake Reduce part.

So why is there no more natural solution for this (or maybe I just donโ€™t know about it)? Is this a conceptual solution?

+4
source share
1 answer

You can use the Projections function for RavenDB to convert.

It just changes the shape of the Json document after RavenDB pulled it out of the doc repository, so the fields should not be marked as Stored for it to work

  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 }; } 

You still need .As<new type> when querying this index, otherwise RavenDB will complain. Something like that:

 session.Query<Post, PostTitleCommentsCount>() .Where(x => x.Title == "blah") .As<PostTitleCommentsCount>() .ToList(); 

It is most often used for combining, see this blog post for more information, but it works in this scenario.

+2
source

Source: https://habr.com/ru/post/1392999/


All Articles