Querying: Projections
There are couple of ways to perform projections in RavenDB:
- projections using SelectFields
- using OfType
What are Projections and When to Use Them
When performing a query, we usually pull the full document back from the server.
However, we often need to display the data to the user. Instead of pulling the whole document back and picking just what we'll show, we can ask the server to send us just the details we want to show the user and thus reduce the amount of traffic on the network.
The savings can be very significant if we need to show just a bit of information on a large document.
A good example in the sample data set would be the order document. If we ask for all the Orders where Company is "companies/65-A", the size of the result that we get back from the server is 19KB.
However, if we perform the same query and ask to get back only the Employee and OrderedAt fields, the size of the result is only 5KB.
Aside from allowing you to pick only a portion of the data, projection functions give you the ability to rename some fields, load external documents, and perform transformations on the results.
Projections are Applied as the Last Stage in the Query
It is important to understand that projections are applied after the query has been processed, filtered, sorted, and paged. The projection doesn't apply to all the documents in the database, only to the results that are actually returned.
This reduces the load on the server significantly, since we can avoid doing work only to throw it immediately after. It also means that we cannot do any filtering work as part of the projection. You can filter what will be returned, but not which documents will be returned. That has already been determined earlier in the query pipeline.
The Cost of Running a Projection
Another consideration to take into account is the cost of running the projection. It is possible to make the projection query expensive to run. RavenDB has limits on the amount of time it will spend in evaluating the projection, and exceeding these (quite generous) limits will fail the query.
Projections and Stored Fields
If a projection function only requires fields that are stored, then the document will not be loaded from storage and all data will come from the index directly. This can increase query performance (by the cost of disk space used) in many situations when whole document is not needed. You can read more about field storing here.
SelectFields
selectFields
method:
Example I - Projecting Individual Fields of the Document
List<FirstAndLastName> results = session
.query(Employee.class, Employees_ByFirstAndLastName.class)
.selectFields(FirstAndLastName.class, "FirstName", "LastName")
.toList();
public static class Employees_ByFirstAndLastName extends AbstractIndexCreationTask {
public Employees_ByFirstAndLastName() {
map = "docs.Employees.Select(employee => new {" +
" FirstName = employee.FirstName," +
" LastName = employee.LastName" +
"})";
}
}
from index 'Employees/ByFirstAndLastName'
select FirstName, LastName
This will issue a query to a database, requesting only FirstName
and LastName
from all documents that index entries match query predicate from Employees/ByFirstAndLastName
index. What does it mean? If an index entry matches our query predicate, then we will try to extract all requested fields from that particular entry. If all requested fields are available in there, then we do not download it from storage. The index Employees/ByFirstAndLastName
used in the above query is not storing any fields, so the documents will be fetched from storage.
Example II - Projecting Stored Fields
If we create an index that stores FirstName
and LastName
and it requests only those fields in query, then the data will come from the index directly.
List<FirstAndLastName> results = session
.query(Employee.class, Employees_ByFirstAndLastNameWithStoredFields.class)
.selectFields(FirstAndLastName.class, "FirstName", "LastName")
.toList();
public static class Employees_ByFirstAndLastNameWithStoredFields extends AbstractIndexCreationTask {
public Employees_ByFirstAndLastNameWithStoredFields() {
map = "docs.Employees.Select(employee => new {" +
" FirstName = employee.FirstName," +
" LastName = employee.LastName" +
"})";
storeAllFields(FieldStorage.YES); // firstName and lastName fields can be retrieved directly from index
}
}
from index 'Employees/ByFirstAndLastNameWithStoredFields'
select FirstName, LastName
Example III - Projecting Arrays and Objects
QueryData queryData = new QueryData(new String[]{"ShipTo", "Lines[].ProductName"},
new String[]{"ShipTo", "Products"});
List<ShipToAndProducts> results = session.query(Order.class)
.selectFields(ShipToAndProducts.class, queryData)
.toList();
public static class Orders_ByShipToAndLines extends AbstractIndexCreationTask {
public Orders_ByShipToAndLines() {
map = "docs.Orders.Select(order => new {" +
" ShipTo = order.ShipTo," +
" Lines = order.Lines" +
"})";
}
}
from index 'Orders/ByShipToAndLines' as o
select
{
ShipTo: o.ShipTo,
Products : o.Lines.map(function(y){return y.ProductName;})
}
Example IV - Projection with Expression
List<FullName> results = session.advanced().rawQuery(FullName.class, "from Employees as e " +
"select {" +
" FullName : e.FirstName + \" \" + e.LastName " +
"}").toList();
public static class Employees_ByFirstAndLastName extends AbstractIndexCreationTask {
public Employees_ByFirstAndLastName() {
map = "docs.Employees.Select(employee => new {" +
" FirstName = employee.FirstName," +
" LastName = employee.LastName" +
"})";
}
}
from index 'Employees/ByFirstAndLastName' as e
select
{
FullName : e.FirstName + " " + e.LastName
}
Example V - Projection with declared function
List<Employee> results = session.advanced().rawQuery(Employee.class, "declare function output(e) { " +
" var format = function(p){ return p.FirstName + \" \" + p.LastName; }; " +
" return { FullName : format(e) }; " +
"} " +
"from Employees as e select output(e)").toList();
public static class Employees_ByFirstAndLastName extends AbstractIndexCreationTask {
public Employees_ByFirstAndLastName() {
map = "docs.Employees.Select(employee => new {" +
" FirstName = employee.FirstName," +
" LastName = employee.LastName" +
"})";
}
}
declare function output(e) {
var format = function(p){ return p.FirstName + " " + p.LastName; };
return { FullName : format(e) };
}
from index 'Employees/ByFirstAndLastName' as e select output(e)
Example VI - Projection with Calculation
List<Total> results = session.advanced().rawQuery(Total.class, "from Orders as o " +
"select { " +
" Total : o.Lines.reduce( " +
" (acc , l) => acc += l.PricePerUnit * l.Quantity, 0) " +
"}").toList();
public static class Orders_ByShipToAndLines extends AbstractIndexCreationTask {
public Orders_ByShipToAndLines() {
map = "docs.Orders.Select(order => new {" +
" ShipTo = order.ShipTo," +
" Lines = order.Lines" +
"})";
}
}
from index 'Orders/ByShipToAndLines' as o
select {
Total : o.Lines.reduce(
(acc , l) => acc += l.PricePerUnit * l.Quantity, 0)
}
Example VII - Projection Using a Loaded Document
List<OrderProjection> results = session.advanced().rawQuery(OrderProjection.class, "from Orders as o " +
"load o.company as c " +
"select { " +
" CompanyName: c.Name," +
" ShippedAt: o.ShippedAt" +
"}").toList();
public static class Orders_ByShippedAtAndCompany extends AbstractIndexCreationTask {
public Orders_ByShippedAtAndCompany() {
map = "docs.Orders.Select(order => new {" +
" ShippedAt = order.ShippedAt," +
" Company = order.Company" +
"})";
}
}
from index 'Orders/ByShippedAtAndCompany' as o
load o.Company as c
select {
CompanyName: c.Name,
ShippedAt: o.ShippedAt
}
Example VIII - Projection with Dates
List<EmployeeProjection> results = session.advanced().rawQuery(EmployeeProjection.class, "from Employees as e " +
"select { " +
" DayOfBirth : new Date(Date.parse(e.Birthday)).getDate(), " +
" MonthOfBirth : new Date(Date.parse(e.Birthday)).getMonth() + 1, " +
" Age : new Date().getFullYear() - new Date(Date.parse(e.Birthday)).getFullYear() " +
"}").toList();
public static class Employees_ByFirstNameAndBirthday extends AbstractIndexCreationTask {
public Employees_ByFirstNameAndBirthday() {
map = "docs.Employees.Select(employee => new {" +
" FirstName = employee.FirstName," +
" Birthday = employee.Birthday" +
"})";
}
}
from index 'Employees/ByFirstNameAndBirthday' as e
select {
DayOfBirth : new Date(Date.parse(e.Birthday)).getDate(),
MonthOfBirth : new Date(Date.parse(e.Birthday)).getMonth() + 1,
Age : new Date().getFullYear() - new Date(Date.parse(e.Birthday)).getFullYear()
}
Example IX - Projection with Raw JavaScript Code
List<EmployeeProjection> results = session.advanced().rawQuery(EmployeeProjection.class, "from Employees as e " +
"select { " +
" Date : new Date(Date.parse(e.Birthday)), " +
" Name : e.FirstName.substr(0,3) " +
"}").toList();
public static class Employees_ByFirstNameAndBirthday extends AbstractIndexCreationTask {
public Employees_ByFirstNameAndBirthday() {
map = "docs.Employees.Select(employee => new {" +
" FirstName = employee.FirstName," +
" Birthday = employee.Birthday" +
"})";
}
}
from index 'Employees/ByFirstNameAndBirthday' as e
select {
Date : new Date(Date.parse(e.Birthday)),
Name : e.FirstName.substr(0,3)
}
Example X - Projection with Metadata
List<Employee> results = session.advanced().rawQuery(Employee.class, "from Employees as e " +
"select {" +
" Name : e.FirstName, " +
" Metadata : getMetadata(e)" +
"}").toList();
public static class Employees_ByFirstAndLastName extends AbstractIndexCreationTask {
public Employees_ByFirstAndLastName() {
map = "docs.Employees.Select(employee => new {" +
" FirstName = employee.FirstName," +
" LastName = employee.LastName" +
"})";
}
}
from index 'Employees/ByFirstAndLastName' as e
select {
Name : e.FirstName,
Metadata : getMetadata(e)
}
OfType
OfType
is a client-side projection. You can read more about it here.
Projections and the Session
Because you are working with projections and not directly with documents, they are not tracked by the session. Modifications to a projection will not modify the document when saveChanges
is called.