RavenDB - retrieving part of document

大憨熊 提交于 2019-12-18 18:56:22

问题


I am playing with Raven DB for few days and I would like to use it as a storage for my Web chat application. I have document which contains some user data and chat history - which is big collection chat messages.

Each time I load user document chat history is also loaded, even if I need only few fields like: user name, password and email.

My question is: how to load only part of document from database ?


回答1:


Tomek,

You can't load a partial document, but you can load a projection.

session.Query<User>()
   .Where(x=>x.Name == name)
   .Select( x=> new { x.Name, x.Email });

That will load only the appropriate fields




回答2:


From what I've seen you can do this (based on the original "User" scenario above):

public class UserSummary
{
    public string Name { get; set; }
    public string Email { get; set; }
}

Then you can do this:

documentSession.Query<User>().AsProjection<UserSummary>();

Looking at the Raven server it spits this out as part of the query:

?query=&pageSize=128&fetch=Name&fetch=Email&fetch=Id

So it looks like it is querying and returning only a subset of the original object, which is good.

This also works:

documentSession.Query<User>().Select( x=> new User { Name = x.Name, Email= x.Email })

But I don't think that is as clean as returning a UserSummary object.

Some follow up questions to those who have posted responses:

The link to RaccoonBlog has this example:

https://github.com/ayende/RaccoonBlog/blob/master/RaccoonBlog.Web/Infrastructure/Indexes/PostComments_CreationDate.cs

Would that method be preferred over the .AsProjection()? What is the difference between the two approaches?




回答3:


Tomek, you cannot load only a part of the document.

However, I understand the problem in your case. I recommend to use two seperate documents for each user: One that actually contains the users data (name, passwordhash, email, etc.) and one that contains all the users messages. That way, it is still very cheap to load all the messages of a user and also to load a list of user for general purposes.

This is actually quite similar to how one would model a blog-domain, where you have a post and the posts comments. Take a look at RaccoonBlog to see how this works.



来源:https://stackoverflow.com/questions/7829379/ravendb-retrieving-part-of-document

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!