RavenDB 2.x  Beginner's Guide
上QQ阅读APP看书,第一时间看更新

Time for action – creating an Index

You will create your first Index using the Management Studio's Indexes screen.

  1. In the Management Studio, select the Indexes tab and click on it to display the Indexes screen.
  2. Click on the New Index button in the toolbar to open the Edit Index screen.
  3. Name the new index TotalOrdersPerCustomer.
  4. In the Maps section, enter the following code snippet:
    from order in docs.Orders
    select new {CustomerId = order.CustomerId,TotalCost = order.Units * order.UnitCost}
  5. Click on the Save Index button to save the index which will appear in the available indexes list.
    Note

    The Management Studio will not save the index if it detects an error in the LINQ query.

  6. Click on the Indexes link to return to the Indexes screen.

What just happened?

We created our first index named TotalOrdersPerCustomer using the Management Studio. This index contains, for now, a single Map function which is a LINQ query that returns a two-column dataset, one of which is a calculated column.

The first column named CustomerId will contain the CustomerId field value. The second column is a calculated field named TotalCost and will contain the operation result of the Units * UnitCost.

Executing a query against an Index

To query the index, RavenDB executes the Map/Reduce implementation in the background and returns the query execution result which is displayed by the Management Studio. The indexing operation is triggered when new indexes are created/updated or when documents are created/updated. Internally, the implementation for this background operation makes heavy use of Etags to allow for incremental index building.

Clicking on the index name from the indexes list in the Indexes screen will query that index and the query result is displayed on the Query Index screen. By default, the Query Index screen displays result matching documents, but this can be changed using the Query Options button in the Query Index screen toolbar.