Skip to main content

Sort Index Query Results

Order by index-field value

  • Use OrderBy or OrderByDescending to order the results by the specified index-field.
List<Product> products = session
// Query the index
.Query<Products_ByUnitsInStock.IndexEntry, Products_ByUnitsInStock>()
// Apply filtering (optional)
.Where(x => x.UnitsInStock > 10)
// Call 'OrderByDescending', pass the index-field by which to order the results
.OrderByDescending(x => x.UnitsInStock)
.OfType<Product>()
.ToList();

// Results will be sorted by the 'UnitsInStock' value in descending order,
// with higher values listed first.

Ordering Type:

  • By default, the OrderBy methods will determine the OrderingType from the property path expression
    and specify that ordering type in the generated RQL that is sent to the server.

  • E.g. in the above example, ordering by x => x.UnitsInStock will result in OrderingType.Long
    because that property data type is an integer.

  • Different ordering can be forced.
    See section Force ordering type for all available ordering types.
    The same syntax used with dynamic queries also applies to queries made on indexes.

Order results when index-field is searchable

  • When configuring an index-field for full-text search, the content of the index-field is broken down into terms at indexing time. The specific tokenization depends on the analyzer used.

  • When querying such index, if you order by that searchable index-field, results will come back sorted based on the terms, and not based on the original text of the field.

  • To overcome this, you can define another index-field that is not searchable and sort by it.

public class Products_BySearchName : AbstractIndexCreationTask<Product>
{
public class IndexEntry
{
// Index-field 'Name' will be configured below for full-text search
public string Name { get; set; }

// Index-field 'NameForSorting' will be used for ordering query results
public string NameForSorting { get; set; }
}

public Products_BySearchName()
{
Map = products => from product in products
select new
{
// Both index-fields are assigned the same content (the 'Name' from the document)
Name = product.Name,
NameForSorting = product.Name
};

// Configure only the 'Name' index-field for FTS
Indexes.Add(x => x.Name, FieldIndexing.Search);
}
}

Additional sorting options