Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RavenDB - retrieving part of document

Tags:

ravendb

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 ?

like image 881
tpx86 Avatar asked Oct 19 '11 23:10

tpx86


People also ask

How do you create a collection in RavenDB?

To create a collection you need to create an entity with instance of a Class as parameter.

How does RavenDB work?

RavenDB takes the query, analyses it and extracts an index which can answer the query. Also, it has the ability to auto generate indexes from your queries. RavenDB uses JSON (JavaScript Object Notation) to store documents. JSON is a way to serialize data and is a lightweight data-interchange format.


2 Answers

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

like image 56
Ayende Rahien Avatar answered Sep 22 '22 05:09

Ayende Rahien


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?

like image 38
David Hoffman Avatar answered Sep 20 '22 05:09

David Hoffman