Recursive AI

Sort full-text search results by price in C#

OneIndex is a free, open-source search library for .NET from Recursive AI. MIT or Apache-2.0, preview, runs in-process.

Use OrderBy to sort matching products by price instead of relevance.

Terminal
dotnet add package RecursiveAI.OneIndex --prerelease

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

C#
using OneIndex;
using var index = MakeIndex();
foreach (var hit in index.Search("mug")
    .OrderBy(x => x.Cents))
    Console.WriteLine(hit.Document.Cents);
 
SearchIndex<Product> MakeIndex()
{
    var index = SearchIndex.InMemory<Product>();
    index.Upsert([
        new() { Id = "b", Cents = 1200 },
        new() { Id = "a", Cents = 900 }
    ]);
    index.Commit();
    return index;
}
 
public class Product
{
    [SearchId]
    public string Id { get; set; } = "";
    [FullText]
    public string Name { get; set; } = "Mug";
    [Sortable] public int Cents { get; set; }
}

Prints the prices in cents, lowest first.

Text
900
1200

Any [Sortable] numeric field sorts the same way: integers (sbyte, byte, short, ushort, int, uint, long) and fractional numbers (float, double). Dates sort by timestamp.

Unzip the example, then dotnet run.

The full program

The download searches five products: four mugs, including two with the same price and one without a price, and a plate that doesn’t match. The query asks for the three cheapest matches. The download pins OneIndex 0.4.0-preview.2.

C#
using OneIndex;
 
using var index = SearchIndex.InMemory<Product>();
index.Upsert([
    new() { Id = "b", Name = "Travel mug", Cents = 900 },
    new() { Id = "c", Name = "Ceramic mug", Cents = 1200 },
    new() { Id = "a", Name = "Steel mug", Cents = 900 },
    new() { Id = "d", Name = "Mystery mug" },
    new() { Id = "e", Name = "Plate", Cents = 500 }
]);
index.Commit();
 
var results = index.Search("mug")
    .OrderBy(x => x.Cents)
    .Take(3).Execute();
Console.WriteLine($"Matches: {results.TotalHits}");
foreach (var hit in results)
    Console.WriteLine($"{hit.Id}: {hit.Document.Cents} cents");
 
public class Product
{
    [SearchId] public string Id { get; set; } = "";
    [FullText] public string Name { get; set; } = "";
    [Sortable] public int? Cents { get; set; }
}

dotnet run prints:

Text
Matches: 4
a: 900 cents
b: 900 cents
c: 1200 cents

If the property has no sortable column, OrderBy throws ArgumentException; mark the numeric property [Sortable] before building the index.

Variations

To show the highest prices first, replace the query and print loop in the download with this. Missing prices still go last.

C#
var results = index.Search("mug")
    .OrderByDescending(x => x.Cents).Take(4);
foreach (var hit in results)
{
    var cents = hit.Document.Cents;
    Console.WriteLine(cents is int price
        ? $"{hit.Id}: {price} cents"
        : $"{hit.Id}: no price");
}
Text
c: 1200 cents
a: 900 cents
b: 900 cents
d: no price

Full-text search · Page search results with a cursor

The short answer

Mark the numeric price property [Sortable] and call .OrderBy(x => x.Cents) on the full-text query before taking a page of hits. Text determines which products match. Price determines which of those products comes first. In the example, an equally cheap product with ID a sorts before b even though it was inserted later.

How do you sort full-text search results by a numeric field?

Use separate fields for the text users search and the number they sort on. In the download, [FullText] makes Name searchable, while [Sortable] keeps Cents in a column for numeric comparison. The search doesn’t parse prices out of product names or sort a formatted display price. If you index 900 and 1200 as strings, their first characters put "1200" ahead of "900" in text order; the numeric column gives the intended order. Format the number for display after retrieving the hits.

Set the order on the query itself rather than sorting the page after it comes back. In the example, a cheaper plate is not a candidate because it doesn’t match “mug.” The query orders all four mugs and then selects three, so TotalHits is four. Sorting just the three hits returned by a relevance query could miss a cheaper mug outside that page. In OneIndex, a sort without a score key doesn’t compute relevance scores; the hit’s Score is zero even if its text matches.

What happens when two search results have the same price?

If you add ThenBy, that key breaks ties. For example, if Stock is another [Sortable] numeric property, this puts lower stock first among products with the same price:

C#
var results = index.Search("mug").OrderBy(x => x.Cents).ThenBy(x => x.Stock);

Without ThenBy, OneIndex compares the document identifiers in UTF-8 byte order. That’s why the two 900-cent products come out as a, then b, even when you switch to descending price. The ID tie-break also keeps the order across segment merges, which can change internal document numbers.

A missing price is different from a zero price. The example uses int?, so an unpriced product has no numeric value and sorts last in either direction. Use zero only when you want the product treated as free. The sorting docs describe how to request missing values first and how the same tie-break works with cursor paging.

All oneindex recipes