What are indexes?
Indexes are server-side functions that define using which fields (and what values) document can be searched on and are the only way to satisfy queries in RavenDB. The whole indexing process is done in the background and is triggered whenever data is added or changed. This approach allows the server to respond quickly even when the large amounts of data have changed and avoid costly table scans operations, however implication of this choice is that the results might be stale (you can read more about staleness implications and the ways to handle it here).
The core of every index is its mapping function with LINQ-like syntax and the result of such a mapping is converted to Lucene index entry, which is persisted for future use to avoid re-indexation each time the query is issued and to achieve fast response times.
In our example, we will create an index that will map documents from the
Employees collection and enable querying by
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>
Map = employees => from employee in employees
FirstName = employee.FirstName,
LastName = employee.LastName
- next step is to send an index to a server (more about index deployment options can be found here), so indexing process can start indexing documents.
// save index on server
- now, our index can be queried, and indexed results can be returned.
IList<Employee> results = session
.Where(x => x.FirstName == "Robert")
More examples with detailed descriptions can be found here.
A frequent mistake is to treat indexes as SQL Views, but this is not the case. 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 doing projections.