tpx86
tpx86

Reputation: 229

RavenDB - retrieving part of document

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 ?

Upvotes: 17

Views: 2075

Answers (3)

David Hoffman
David Hoffman

Reputation: 157

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?

Upvotes: 5

Ayende Rahien
Ayende Rahien

Reputation: 22956

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

Upvotes: 32

Daniel Lang
Daniel Lang

Reputation: 6839

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.

Upvotes: 2

Related Questions