What Indexes Are


  • Indexes are server-side functions that define which fields and what values documents can be searched on.
    They are the only way to satisfy queries in RavenDB.

  • The indexing process is performed in the background and is triggered whenever data is added or changed.
    This approach allows the server to respond quickly even when large amounts of data have changed and avoid costly table scan operations.

  • The core of every index is its mapping function, that utilizes LINQ-like syntax.
    The result of this mapping is converted to a Lucene index entry which is persisted for future use to avoid re-indexing each time the query is issued and keep response times minimal.

  • This page shows a basic example for the creation, deployment, and usage of an index.
    Additional examples are available, among other places, on the Indexing Basics and Map Indexes pages.

  • In this page:

Basic Example

In the below example we create an index that maps documents from the Employees collection and enables querying by FirstName, LastName, or both.

  • First, we need to create an index.
    One way to create it is to use the AbstractIndexCreationTask, but there are other ways available as well (you can read about them here).

    public class Employees_ByFirstAndLastName : AbstractIndexCreationTask<Employee>
    {
        public Employees_ByFirstAndLastName()
        {
            Map = employees => from employee in employees
                               select new
                               {
                                   FirstName = employee.FirstName,
                                   LastName = employee.LastName
                               };
        }
    }
  • The next step is to send an index to a server (more about index deployment options can be found here) so the indexing process can start indexing documents.

    // save index on server
    new Employees_ByFirstAndLastName().Execute(store);
  • Now, our index can be queried and indexed results can be returned.

    IList<Employee> results = session
        .Query<Employee, Employees_ByFirstAndLastName>()
        .Where(x => x.FirstName == "Robert")
        .ToList();

Remarks

Remember

A frequent mistake is to handle indexes as SQL Views, but they are not analogous.
The result of a query for the given index is a full document, not only the fields that were indexed.

This behavior can be altered by storing fields and applying projections.