see on GitHub

Querying: Projections

There are couple of ways to perform projections in RavenDB:

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

The most basic projection can be done using selectFields() method:

Example I - Projecting Individual Fields of the Document

const results = session
    .query({ indexName: "Employees/ByFirstAndLastName" })
    .selectFields([ "FirstName", "LastName" ])
    .all();
class Employees_ByFirstAndLastName extends AbstractIndexCreationTask {
    constructor() {
        super();

        this.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.

const results = await session
    .query({ indexName: "Employees/ByFirstAndLastNameWithStoredFields" })
    .selectFields("FirstName", "LastName")
    .all();
class Employees_ByFirstAndLastNameWithStoredFields extends AbstractIndexCreationTask {
    constructor() {
        super();

        this.map = `docs.Employees.Select(employee => new {    
            FirstName = employee.FirstName,    
            LastName = employee.LastName
        })`;

        this.storeAllFields("Yes"); // FirstName and LastName fields can be retrieved directly from index
    }
}
from index 'Employees/ByFirstAndLastNameWithStoredFields'
select FirstName, LastName

Example III - Projecting Arrays and Objects

const queryData = new QueryData(
    [ "ShipTo", "Lines[].ProductName" ],
    [ "ShipTo", "Products" ]);

const results = await session.query(Order)
    .selectFields(queryData)
    .all();
class Orders_ByShipToAndLines extends AbstractIndexCreationTask {
    constructor() {
        super();

        this.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

const results = await session.advanced.rawQuery(`from Employees as e select {    
    FullName : e.FirstName + " " + e.LastName 
}`).all();
class Employees_ByFirstAndLastName extends AbstractIndexCreationTask {
    constructor() {
        super();

        this.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

const results = await session.advanced
.rawQuery(`declare function output(e) {     
        var format = function(p) { 
            return p.FirstName + " " + p.LastName; 
        };     

        return { FullName : format(e) }; 
    } from Employees as e select output(e)`)
    .all();
    
class Employees_ByFirstAndLastName extends AbstractIndexCreationTask {
    constructor() {
        super();

        this.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

const results = await session.advanced.rawQuery(
    `from Orders as o select {     
        Total: o.Lines.reduce(
            (acc , l) => acc += l.PricePerUnit * l.Quantity, 0) 
        }`).all();
class Orders_ByShipToAndLines extends AbstractIndexCreationTask {
    constructor() {
        super();

        this.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

const results = await session.advanced
    .rawQuery(
        `from Orders as o load o.Company as c select {     
            CompanyName: c.Name,    
            ShippedAt: o.ShippedAt
        }`).all();
class Orders_ByShippedAtAndCompany extends AbstractIndexCreationTask {
    constructor() {
        super();

        this.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

const results = await session.advanced
    .rawQuery(
    `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() 
        }`).all();
class Employees_ByFirstNameAndBirthday extends AbstractIndexCreationTask {
    constructor() {
        super();

        this.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

const results = await session.advanced
    .rawQuery(
        `from Employees as e select {     
            Date : new Date(Date.parse(e.Birthday)),     
            Name : e.FirstName.substr(0,3) 
        }`).all();
class Employees_ByFirstNameAndBirthday extends AbstractIndexCreationTask {
    constructor() {
        super();

        this.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

const results = await session.advanced
    .rawQuery(`from Employees as e select {     
        Name : e.FirstName,      
        Metadata : getMetadata(e)
    }`).all();
class Employees_ByFirstAndLastName extends AbstractIndexCreationTask {
    constructor() {
        super();

        this.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.