Handling document relationships
One of the design principles that RavenDB adheres to is the idea that documents are independent, meaning all data required to process a document is stored within the document itself. However, this doesn't mean there should not be relations between objects.
There are valid scenarios where we need to define relationships between objects. By doing so, we expose ourselves to one major problem: whenever we load the containing entity, we are going to need to load data from the referenced entities too (unless we are not interested in them). While the alternative of storing the whole entity in every object graph it is referenced in seems cheaper at first, this proves to be quite costly in terms of database resources and network traffic.
RavenDB offers three elegant approaches to solve this problem. Each scenario will need to use one or more of them. When applied correctly, they can drastically improve performance, reduce network bandwidth and speedup development.
Denormalization
The easiest solution is to denormalize the data within the containing entity, forcing it to contain the actual value of the referenced entity in addition (or instead) of the foreign key.
Take this JSON document for example:
// Order document with id: orders/1234
{
"Customer": {
"Name": "Itamar",
"Id": "customers/2345"
},
Items: [
{
"Product": {
"Id": "products/1234",
"Name": "Milk",
"Cost": 2.3
},
"Quantity": 3
}
]
}
As you can see, the Order
document now contains denormalized data from both the Customer
and the Product
documents, which are saved elsewhere in full. Note we won't have copied all the customer properties into the order; instead we just clone the ones that we care about when displaying or processing an order. This approach is called denormalized reference.
The denormalization approach avoids many cross document lookups and results in only the necessary data being transmitted over the network, but it makes other scenarios more difficult. For example, consider the following entity structure as our start point:
public class Order
{
public string CustomerId { get; set; }
public Guid[] SupplierIds { get; set; }
public Referral Referral { get; set; }
public LineItem[] LineItems { get; set; }
public double TotalPrice { get; set; }
}
public class Customer
{
public string Id { get; set; }
public string Name { get; set; }
}
If we know that whenever we load an Order
from the database we will need to know the customer's name and address, we could decide to create a denormalized Order.Customer
field, and store those details in the directly in the Order
object. Obviously, the password and other irrelevant details will not be denormalized:
public class DenormalizedCustomer
{
public string Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
There wouldn't be a direct reference between the Order
and the Customer
. Instead, Order
holds a DenormalizedCustomer
, which contains the interesting bits from Customer
that we need whenever we process Order
objects.
But, what happens when the user's address is changed? We will have to perform an aggregate operation to update all orders this customer has made. And what if the customer has a lot of orders or changes their address frequently? Keeping these details in sync could become very demanding on the server. What if another process that works with orders needs a different set of customer properties? The DenormalizedCustomer
will need to be expanded, possibly to the point that the majority of the customer record is cloned.
Tip
Denormalization is a viable solution for rarely changing data, or for data that must remain the same despite the underlying referenced data changing over time.
Includes
Includes feature addresses the limitations of denormalization. Instead of one object containing copies of the properties from another object, it is only necessary to hold a reference to the second object. Then server can be instructed to pre-load the referenced document at the same time that the root object is retrieved. We can do this using:
Order order = session
.Include<Order>(x => x.CustomerId)
.Load("orders/1234");
// this will not require querying the server!
Customer customer = session
.Load<Customer>(order.CustomerId);
MultiLoadResult result = store
.DatabaseCommands
.Get(ids: new[] { "orders/1234" }, includes: new[] { "CustomerId" });
RavenJObject order = result.Results[0];
RavenJObject customer = result.Includes[0];
Above we are asking RavenDB to retrieve the Order
"orders/1234" and at the same time "include" the Customer
referenced by the Order.CustomerId
property. The second call to Load()
is resolved completely client side (i.e. without a second request to the RavenDB server) because the relevant Customer
object has already been retrieved (this is the full Customer
object not a denormalized version).
There is also a possibility to load multiple documents:
Order[] orders = session
.Include<Order>(x => x.CustomerId)
.Load("orders/1234", "orders/4321");
foreach (Order order in orders)
{
// this will not require querying the server!
Customer customer = session.Load<Customer>(order.CustomerId);
}
MultiLoadResult result = store
.DatabaseCommands
.Get(ids: new[] { "orders/1234", "orders/4321" }, includes: new[] { "CustomerId" });
List<RavenJObject> orders = result.Results;
List<RavenJObject> customers = result.Includes;
You can also use Includes with queries:
IList<Order> orders = session
.Query<Order, Orders_ByTotalPrice>()
.Customize(x => x.Include<Order>(o => o.CustomerId))
.Where(x => x.TotalPrice > 100)
.ToList();
foreach (Order order in orders)
{
// this will not require querying the server!
Customer customer = session
.Load<Customer>(order.CustomerId);
}
IList<Order> orders = session
.Advanced
.DocumentQuery<Order, Orders_ByTotalPrice>()
.Include(x => x.CustomerId)
.WhereGreaterThan(x => x.TotalPrice, 100)
.ToList();
foreach (Order order in orders)
{
// this will not require querying the server!
Customer customer = session
.Load<Customer>(order.CustomerId);
}
QueryResult result = store
.DatabaseCommands
.Query(
"Orders/ByTotalPrice",
new IndexQuery
{
Query = "TotalPrice_Range:{Ix100 TO NULL}"
},
includes: new[] { "CustomerId" });
List<RavenJObject> orders = result.Results;
List<RavenJObject> customers = result.Includes;
public class Orders_ByTotalPrice : AbstractIndexCreationTask<Order>
{
public Orders_ByTotalPrice()
{
Map = orders => from order in orders
select new
{
order.TotalPrice
};
}
}
Under the hood, this works because RavenDB has two channels through which it can return information in response to a load request. The first is the Results channel, through which the root object retrieved by the Load()
method call is returned. The second is the Includes channel, through which any included documents are sent back to the client. Client side, those included documents are not returned from the Load()
method call, but they are added to the session unit of work, and subsequent requests to load them are served directly from the session cache, without requiring any additional queries to the server.
One to many includes
Include can be used with a many to one relationship. In the above classes, an Order
has a property SupplierIds
which contains an array of references to Supplier
documents. The following code will cause the suppliers to be pre-loaded:
Order order = session
.Include<Order>(x => x.SupplierIds)
.Load("orders/1234");
foreach (Guid supplierId in order.SupplierIds)
{
// this will not require querying the server!
Supplier supplier = session.Load<Supplier>(supplierId);
}
MultiLoadResult result = store
.DatabaseCommands
.Get(ids: new[] { "orders/1234" }, includes: new[] { "SupplierIds" });
RavenJObject order = result.Results[0];
RavenJObject customer = result.Includes[0];
Again, the calls to Load()
within the foreach
loop will not require a call to the server as the Supplier
objects will already be loaded into the session cache.
Multi-loads are also possible:
Order[] orders = session
.Include<Order>(x => x.SupplierIds)
.Load("orders/1234", "orders/4321");
foreach (Order order in orders)
{
foreach (Guid supplierId in order.SupplierIds)
{
// this will not require querying the server!
Supplier supplier = session.Load<Supplier>(supplierId);
}
}
MultiLoadResult result = store
.DatabaseCommands
.Get(ids: new[] { "orders/1234", "orders/4321" }, includes: new[] { "SupplierIds" });
List<RavenJObject> orders = result.Results;
List<RavenJObject> customers = result.Includes;
Secondary level includes
An Include does not need to work only on the value of a top level property within a document. It can be used to load a value from a secondary level. In the classes above, the Order
contains a Referral
property which is of the type:
public class Referral
{
public string CustomerId { get; set; }
public double CommissionPercentage { get; set; }
}
This class contains an identifier for a Customer
. The following code will include the document referenced by that secondary level identifier:
Order order = session
.Include<Order>(x => x.Referral.CustomerId)
.Load("orders/1234");
// this will not require querying the server!
Customer customer = session.Load<Customer>(order.Referral.CustomerId);
MultiLoadResult result = store
.DatabaseCommands
.Get(ids: new[] { "orders/1234" }, includes: new[] { "Referral.CustomerId" });
RavenJObject order = result.Results[0];
RavenJObject customer = result.Includes[0];
Alternative way is to provide string based path:
Order order = session.Include("Referral.CustomerId")
.Load<Order>("orders/1234");
// this will not require querying the server!
Customer customer = session.Load<Customer>(order.Referral.CustomerId);
MultiLoadResult result = store
.DatabaseCommands
.Get(ids: new[] { "orders/1234" }, includes: new[] { "Referral.CustomerId" });
RavenJObject order = result.Results[0];
RavenJObject customer = result.Includes[0];
This secondary level include will also work with collections. The Order.LineItems
property holds a collection of LineItem
objects which each contain a reference to a Product
:
public class LineItem
{
public Guid ProductId { get; set; }
public string Name { get; set; }
public int Quantity { get; set; }
}
The Product
documents can be included using this syntax:
Order order = session
.Include<Order>(x => x.LineItems.Select(li => li.ProductId))
.Load("orders/1234");
foreach (LineItem lineItem in order.LineItems)
{
// this will not require querying the server!
Product product = session.Load<Product>(lineItem.ProductId);
}
MultiLoadResult result = store
.DatabaseCommands
.Get(ids: new[] { "orders/1234" }, includes: new[] { "LineItems.,ProductId" });
RavenJObject order = result.Results[0];
RavenJObject product = result.Includes[0];
when you want to load multiple documents.
The Select()
within the Include tells RavenDB which property of secondary level objects to use as a reference.
Conventions
When using string-based includes like:
Order order = session
.Include<Order>(x => x.Referral.CustomerId)
.Load("orders/1234");
// this will not require querying the server!
Customer customer = session.Load<Customer>(order.Referral.CustomerId);
MultiLoadResult result = store
.DatabaseCommands
.Get(ids: new[] { "orders/1234" }, includes: new[] { "Referral.CustomerId" });
RavenJObject order = result.Results[0];
RavenJObject customer = result.Includes[0];
you must remember to follow certain rules that must apply to the provided string path:
- Dots are used to separate properties e.g.
"Referral.CustomerId"
in example above means that ourOrder
contains propertyReferral
and that property contains another property calledCustomerId
. - Commas are used to indicate that property is a collection type e.g. List. So if our
Order
will have a list of LineItems and eachLineItem
will containProductId
property then we can create string path as follows:"LineItems.,ProductId"
. - Prefixes are used to indicate id prefix for non-string identifiers. e.g. if our
CustomerId
property in"Referral.CustomerId"
path is an integer then we should addcustomers/
prefix so the final path would look like"Referral.CustomerId(customers/)"
and for our collection example it would be"LineItems.,ProductId(products/)"
if theProductId
would be a non-string type.
Note
Prefix is not required for string identifiers, because they contain it by default.
Learning string path rules may be useful when you will want to query database using HTTP API.
curl -X GET "http://localhost:8080/databases/Northwind/queries/?include=LineItems.,ProductId(products/)&id=orders/1"
ValueType identifiers
The above Include
samples assume that the Id property being used to resolve a reference is a string and it contains the full identifier for the referenced document (e.g. the CustomerId
property will contain a value such as "customers/5678"
). Include can also work with Value Type identifiers. Given these entities:
public class Order2
{
public int CustomerId { get; set; }
public Guid[] SupplierIds { get; set; }
public Referral Referral { get; set; }
public LineItem[] LineItems { get; set; }
public double TotalPrice { get; set; }
}
public class Customer2
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Referral2
{
public int CustomerId { get; set; }
public double CommissionPercentage { get; set; }
}
The samples above can be re-written as follows:
Order2 order = session
.Include<Order2, Customer2>(x => x.CustomerId)
.Load("order2s/1234");
// this will not require querying the server!
Customer2 customer = session.Load<Customer2>(order.CustomerId);
MultiLoadResult result = store
.DatabaseCommands
.Get(ids: new[] { "order2s/1234" }, includes: new[] { "CustomerId" });
RavenJObject order = result.Results[0];
RavenJObject customer = result.Includes[0];
IList<Order2> orders = session
.Query<Order2, Order2s_ByTotalPrice>()
.Customize(x => x.Include<Order2, Customer2>(o => o.CustomerId))
.Where(x => x.TotalPrice > 100)
.ToList();
foreach (Order2 order in orders)
{
// this will not require querying the server!
Customer2 customer = session.Load<Customer2>(order.CustomerId);
}
IList<Order2> orders = session
.Advanced
.DocumentQuery<Order2, Order2s_ByTotalPrice>()
.Include("CustomerId")
.WhereGreaterThan(x => x.TotalPrice, 100)
.ToList();
foreach (Order2 order in orders)
{
// this will not require querying the server!
Customer2 customer = session.Load<Customer2>(order.CustomerId);
}
QueryResult result = store
.DatabaseCommands
.Query(
"Order2s/ByTotalPrice",
new IndexQuery
{
Query = "TotalPrice_Range:{Ix100 TO NULL}"
},
includes: new[] { "CustomerId" });
List<RavenJObject> orders = result.Results;
List<RavenJObject> customers = result.Includes;
public class Order2s_ByTotalPrice : AbstractIndexCreationTask<Order2>
{
public Order2s_ByTotalPrice()
{
Map = orders => from order in orders
select new
{
order.TotalPrice
};
}
}
Order2 order = session
.Include<Order2, Supplier>(x => x.SupplierIds)
.Load("order2s/1234");
foreach (Guid supplierId in order.SupplierIds)
{
// this will not require querying the server!
Supplier supplier = session.Load<Supplier>(supplierId);
}
MultiLoadResult result = store
.DatabaseCommands
.Get(ids: new[] { "order2s/1234" }, includes: new[] { "SupplierIds" });
RavenJObject order = result.Results[0];
List<RavenJObject> suppliers = result.Includes;
Order2 order = session
.Include<Order2, Customer2>(x => x.Referral.CustomerId)
.Load("order2s/1234");
// this will not require querying the server!
Customer2 customer = session.Load<Customer2>(order.Referral.CustomerId);
MultiLoadResult result = store
.DatabaseCommands
.Get(ids: new[] { "order2s/1234" }, includes: new[] { "Referral.CustomerId" });
RavenJObject order = result.Results[0];
RavenJObject customer = result.Includes[0];
Order2 order = session
.Include<Order2, Product>(x => x.LineItems.Select(li => li.ProductId))
.Load("orders/1234");
foreach (LineItem lineItem in order.LineItems)
{
// this will not require querying the server!
Product product = session.Load<Product>(lineItem.ProductId);
}
MultiLoadResult result = store
.DatabaseCommands
.Get(ids: new[] { "order2s/1234" }, includes: new[] { "LineItems.,ProductId" });
RavenJObject order = result.Results[0];
List<RavenJObject> products = result.Includes;
The second parameter to the generic Include<T, TInclude>
specifies which document collection the reference is pointing to. RavenDB will combine the name of the collection with the value of the reference property to find the full identifier of the referenced document. For example, from the first example, if the value of the Order.CustomerId
property is 56
, client will include the document with an Id of customer2s/56
from the database. The Session.Load<Customer2>()
method will be passed the value 56
and will look for then load the document customer2s/56
from the session cache.
Dictionary includes
Dictionary keys and values can also be used when doing includes. Consider following scenario:
public class Person
{
public string Id { get; set; }
public string Name { get; set; }
public Dictionary<string, string> Attributes { get; set; }
}
session.Store(
new Person
{
Id = "people/1",
Name = "John Doe",
Attributes = new Dictionary<string, string>
{
{ "Mother", "people/2" },
{ "Father", "people/3" }
}
});
session.Store(
new Person
{
Id = "people/2",
Name = "Helen Doe",
Attributes = new Dictionary<string, string>()
});
session.Store(
new Person
{
Id = "people/3",
Name = "George Doe",
Attributes = new Dictionary<string, string>()
});
Now we want to include all documents that are under dictionary values:
var person = session
.Include<Person>(x => x.Attributes.Values)
.Load("people/1");
var mother = session
.Load<Person>(person.Attributes["Mother"]);
var father = session
.Load<Person>(person.Attributes["Father"]);
Assert.Equal(1, session.Advanced.NumberOfRequests);
var result = store
.DatabaseCommands
.Get(new[] { "people/1" }, new[] { "Attributes.$Values" });
var include1 = result.Includes[0];
var include2 = result.Includes[1];
You can also include values from dictionary keys:
var person = session
.Include<Person>(x => x.Attributes.Keys)
.Load("people/1");
var result = store
.DatabaseCommands
.Get(new[] { "people/1" }, new[] { "Attributes.$Keys" });
Complex types
If values in dictionary are more complex e.g.
public class PersonWithAttribute
{
public string Id { get; set; }
public string Name { get; set; }
public Dictionary<string, Attribute> Attributes { get; set; }
}
public class Attribute
{
public string Ref { get; set; }
}
session.Store(
new PersonWithAttribute
{
Id = "people/1",
Name = "John Doe",
Attributes = new Dictionary<string, Attribute>
{
{ "Mother", new Attribute { Ref = "people/2" } },
{ "Father", new Attribute { Ref = "people/3" } }
}
});
session.Store(
new Person
{
Id = "people/2",
Name = "Helen Doe",
Attributes = new Dictionary<string, string>()
});
session.Store(
new Person
{
Id = "people/3",
Name = "George Doe",
Attributes = new Dictionary<string, string>()
});
We can do includes on specific properties also:
var person = session
.Include<PersonWithAttribute>(x => x.Attributes.Values.Select(v => v.Ref))
.Load("people/1");
var mother = session
.Load<Person>(person.Attributes["Mother"].Ref);
var father = session
.Load<Person>(person.Attributes["Father"].Ref);
Assert.Equal(1, session.Advanced.NumberOfRequests);
var result = store
.DatabaseCommands
.Get(new[] { "people/1" }, new[] { "Attributes.$Values,Ref" });
var include1 = result.Includes[0];
var include2 = result.Includes[1];
Combining Approaches
It is possible to combine the above techniques. Using the DenormalizedCustomer
from above and creating an order that uses it:
public class Order3
{
public DenormalizedCustomer Customer { get; set; }
public string[] SupplierIds { get; set; }
public Referral Referral { get; set; }
public LineItem[] LineItems { get; set; }
public double TotalPrice { get; set; }
}
We have the advantages of a denormalization, a quick and simple load of an Order
and the fairly static Customer
details that are required for most processing. But we also have the ability to easily and efficiently load the full Customer
object when necessary using:
Order3 order = session
.Include<Order3, Customer>(x => x.Customer.Id)
.Load("orders/1234");
// this will not require querying the server!
Customer customer = session.Load<Customer>(order.Customer.Id);
MultiLoadResult result = store
.DatabaseCommands
.Get(ids: new[] { "orders/1234" }, includes: new[] { "Customer.Id" });
RavenJObject order = result.Results[0];
RavenJObject customer = result.Includes[0];
This combining of denormalization and Includes could also be used with a list of denormalized objects.
It is possible to use Include on a query against a Live Projection. Includes are evaluated after the TransformResults
has been evaluated. This opens up the possibility of implementing Tertiary Includes (i.e. retrieving documents that are referenced by documents that are referenced by the root document).
Whilst RavenDB can support Tertiary Includes, before resorting to them you should re-evaluate your document model. Needing to use Tertiary Includes can be an indication that you are designing your documents along "Relational" lines.
Summary
There are no strict rules as to when to use which approach, but the general idea is to give it a lot of thought, and consider the implications each approach has.
As an example, in an e-commerce application it might be better to denormalize product names and prices into an order line object, since you want to make sure the customer sees the same price and product title in the order history. But the customer name and addresses should probably be references, rather than denormalized into the order entity.
For most cases where denormalization is not an option, Includes are probably the answer.