Recursive AI

Customize search ranking rules in C#

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

Rank by matched query words, then by price.

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 =
    SearchIndex.InMemory<Product>();
index.Upsert([
    new() { Id = "a", Text = "red shoes",
        Price = 90 },
    new() { Id = "b", Price = 20,
        Text = "red shoes for walking" +
               " in the park" },
    new() { Id = "c", Text = "red hat",
        Price = 5 }
]);
index.Commit();
var ranked = index.Search("red shoes")
    .RankingRules("words", "Price:asc")
    .Execute();
Console.WriteLine("Rules: " +
    string.Join(", ", ranked.Select(
        h => h.Id)));
var relevance = index.Search("red shoes")
    .RankByRelevance().Execute();
Console.WriteLine("Relevance: " +
    string.Join(", ", relevance.Select(
        h => h.Id)));
 
public class Product
{
    [SearchId]
    public string Id { get; set; } = "";
    [FullText]
    public string Text { get; set; } = "";
    [Sortable]
    public int Price { get; set; }
}
Text
Rules: b, a, c
Relevance: a, b

The words rule ORs the search words: matching either “red” or “shoes” is enough. That is why the rule-ranked query includes the partial match c, which contains only “red”; the relevance query requires both words.

The download pins OneIndex to 0.4.0-preview.2; the package’s source generator builds the mapping from the attributed class.

A field rule must name a column-backed property; use [Sortable] on the field as the example does.

Unzip the example, then dotnet run.

Variations

Reverse the price rule, keeping word coverage first. Replace the var ranked statement in the snippet at the top:

C#
var ranked = index.Search("red shoes")
    .RankingRules("words", "Price:desc")
    .Execute();
Text
Rules: a, b, c
Relevance: a, b

The short answer

Call RankingRules on a text search to supply an ordered list of criteria. In the example, words puts documents matching more query words first, then Price:asc puts the cheaper document first within that bucket. Call RankByRelevance to ignore declared rules and use the ordinary relevance score. Rules are opt-in; without them OneIndex ranks by BM25F with a term-proximity bonus, the standard text relevance score.

How does search ranking work?

With rules enabled, the engine sorts matching documents by a tuple of rule values, in the order you supplied. The first different rule decides the order. Relevance score breaks ties after all rules; the document identifier breaks any remaining tie. This is not a weighted sum in which a strong later rule can cancel an earlier one.

The full program searches for “red shoes”. Products a and b match both words; c matches only “red”. With words first, c stays below both shoes even though it is cheapest. Among the two shoes, Price:asc places the cheaper b before a. If price were the first rule, cheap products could outrank documents with more matching words. Choose that ordering only when it reflects the behavior you want.

There is another important effect: with the words rule, query words are OR-ed. Without it, every word must match. That is why the rule-ranked results contain c, while the relevance search returns only a and b. Switching ranking mode can change the matching set, not just shuffle the same hits. The ranking-rule documentation describes the matching and tie-breaking behavior.

How do you customize search ranking rules in C#?

Apply RankingRules to an individual query when the choice belongs to that search screen or request. Declare [RankingRules(...)] on the mapped document type when the same rules should apply by default. A query-level rule list replaces the declared list rather than appending to it. RankByRelevance bypasses the declared list for that query.

The supported built-in rules are words, typo, proximity, attribute, sort and exactness. A field rule names a property followed by :asc or :desc. That property needs a column, supplied by [Sortable], [Filterable] or [Facet]. The example makes Price sortable. Missing values sort last. Rules do not manufacture synonyms or typo candidates; those come from the text-search configuration.

A built-in rule or field can appear only once, with at most 12 rules in a list. Keep the list as short as the product requirement allows. Each extra rule creates another way for the final order to diverge from plain relevance, so test representative queries rather than assuming that a longer list is more relevant.

How do you sort search results by relevance in C#?

Use RankByRelevance as the program does. It restores score-based ranking for that query even if the document type declares rules. This is a useful baseline for comparing a short catalog query with a longer natural-language query. The docs recommend the default relevance ranking for long natural-language queries rather than prioritizing the number of matched words.

Rule-based ranking visits all matches and reports an exact TotalHits. Filters, facets, aggregations, highlights and explanations still work. ScoreBy shapes the relevance score used as the final ranking key; it does not move that score ahead of earlier rules. Distinct cannot be combined with ranking rules, and hybrid searches ignore them because hybrid results rank by fused position. Choose the ranking mode for the retrieval path you are actually using.

All oneindex recipes