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 ?
To create a collection you need to create an entity with instance of a Class as parameter.
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.
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
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With