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.
List<Product> products = await asyncSession
     // 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>() 
    .ToListAsync();

// Results will be sorted by the 'UnitsInStock' value in descending order,
// with higher values listed first.
List<Product> products = session.Advanced
     // Query the index
    .DocumentQuery<Products_ByUnitsInStock.IndexEntry, Products_ByUnitsInStock>()
     // Apply filtering (optional)
    .WhereGreaterThan(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.
public class Products_ByUnitsInStock : AbstractIndexCreationTask<Product>
{
    public class IndexEntry
    {
        public int UnitsInStock { get; set; }
    }
    
    public Products_ByUnitsInStock()
    {
        Map = products => from product in products
            select new IndexEntry()
            {
                UnitsInStock = product.UnitsInStock
            };
    }
}
from index "Products/ByUnitsInStock"
where UnitsInStock > 10
order by UnitsInStock as long desc

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);
    }
}
List<Product> products = session
     // Query the index 
    .Query<Products_BySearchName.IndexEntry, Products_BySearchName>()
     // Call 'Search':
     // Pass the index-field that was configured for FTS and the term to search for.
     // Here we search for terms that start with "ch" within index-field 'Name'.
    .Search(x => x.Name, "ch*")
     // Call 'OrderBy':
     // Pass the other index-field by which to order the results.
    .OrderBy(x => x.NameForSorting)
    .OfType<Product>()
    .ToList();

// Running the above query on the NorthWind sample data, ordering by 'NameForSorting' field,
// we get the following order:
// =========================================================================================

// "Chai"
// "Chang"
// "Chartreuse verte"
// "Chef Anton's Cajun Seasoning"
// "Chef Anton's Gumbo Mix"
// "Chocolade"
// "Jack's New England Clam Chowder"
// "Pâté chinois"
// "Teatime Chocolate Biscuits"

// While ordering by the searchable 'Name' field would have produced the following order:
// ======================================================================================

// "Chai"
// "Chang"
// "Chartreuse verte"
// "Chef Anton's Cajun Seasoning"
// "Pâté chinois"
// "Chocolade"
// "Teatime Chocolate Biscuits"
// "Chef Anton's Gumbo Mix"
// "Jack's New England Clam Chowder"
List<Product> products = await asyncSession
     // Query the index 
    .Query<Products_BySearchName.IndexEntry, Products_BySearchName>()
     // Call 'Search':
     // Pass the index-field that was configured for FTS and the term to search for.
     // Here we search for terms that start with "ch" within index-field 'Name'.
    .Search(x => x.Name, "ch*")
     // Call 'OrderBy':
     // Pass the other index-field by which to order the results.
    .OrderBy(x => x.NameForSorting)
    .OfType<Product>()
    .ToListAsync();
List<Product> products = session.Advanced
     // Query the index
    .DocumentQuery<Products_BySearchName.IndexEntry, Products_BySearchName>()
     // Call 'Search':
     // Pass the index-field that was configured for FTS and the term to search for.
     // Here we search for terms that start with "ch" within index-field 'Name'.
    .Search("Name", "ch*")
     // Call 'OrderBy':
     // Pass the other index-field by which to order the results.
    .OrderBy("NameForSorting")
    .OfType<Product>()
    .ToList();
from index "Products/BySearchName" 
where search(Name, "ch*")
order by NameForSorting

Additional sorting options