Recursive AI

Regex search over indexed keywords 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 RegexQuery with AB-[0-9]{3} to match whole product IDs like AB-042.

Terminal
dotnet add package RecursiveAI.OneIndex --prerelease

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

C#
using OneIndex.Index;
using OneIndex.Search;
using OneIndex.Storage;
 
var query = new RegexQuery(
    "sku", "AB-[0-9]{3}");
var options = new QueryEngineOptions
    { MaxExpandedTerms = 16 };
using var view = IndexSnapshot.Open(
    BuildIndex());
var search = SnapshotSearch.CreateSearcher(
    view, options);
var hits = search.Search(query, 10);
Console.WriteLine(hits.TotalHits);
 
static MemoryStorage BuildIndex()
{
    var store = new MemoryStorage();
    var schema = new SchemaBuilder()
        .Keyword("sku").Build();
    using var writer =
        IndexWriter.Open(store, schema);
    string[] skus = ["AB-042", "AB-4200", "CD-105"];
    foreach (var sku in skus)
        writer.Add(new Document()
            .Add("sku", sku));
    writer.Commit();
    return store;
}

The example is the full program below: unzip it and dotnet run. To run only the code above, paste it into Program.cs of a new dotnet new console project and dotnet run.

Text
1

The full program

C#
using OneIndex.Index;
using OneIndex.Search;
using OneIndex.Storage;
 
var query = new RegexQuery(
    "sku", "AB-[0-9]{3}");
var options = new QueryEngineOptions
    { MaxExpandedTerms = 16 };
using var view = IndexSnapshot.Open(
    BuildIndex());
var search = SnapshotSearch.CreateSearcher(
    view, options);
var results = search.Search(query, 10);
Console.WriteLine(results.TotalHits);
foreach (var hit in results.Hits)
{
    var leaf = search.Context.Leaves.Last(x => x.DocBase <= hit.DocId);
    var fields = leaf.Reader.StoredFields
        ?? throw new InvalidOperationException(
        "Expected stored fields.");
    var product = fields.GetDocument(hit.DocId - leaf.DocBase);
    Console.WriteLine(product.Get("sku").AsText());
}
 
static MemoryStorage BuildIndex()
{
    var store = new MemoryStorage();
    var schema = new SchemaBuilder()
        .Keyword("sku").Build();
    using var writer =
        IndexWriter.Open(store, schema);
    string[] skus = ["AB-042", "AB-4200", "CD-105"];
    foreach (var sku in skus)
        writer.Add(new Document()
            .Add("sku", sku));
    writer.Commit();
    return store;
}
Text
1
AB-042

search.Context.Leaves.Last(x => x.DocBase <= hit.DocId) finds the index segment that holds the hit so the program can read its stored SKU.

The count is for AB-042. AB-4200 has four digits and CD-105 has a different prefix. If more than 16 distinct terms match, the search throws TooManyTermsException instead of silently dropping matches.

Variations

Match two prefixes. Replace the query line to include both AB and CD, still followed by exactly three digits:

C#
var query = new RegexQuery("sku", "(AB|CD)-[0-9]{3}");
Text
2

The short answer

Index your IDs in a keyword field and pass that field and a pattern to RegexQuery. The expression has to match the entire indexed term. Set MaxExpandedTerms on the searcher to bound the number of distinct matching terms it can score.

How do you use regex search on an indexed field?

A RegexQuery matches terms in the field’s term dictionary, not substrings in the original documents. With a keyword field, the whole SKU is one term, including the dash. In a full-text field, the match unit would instead be whatever tokens your analyzer indexed. Use a keyword field when punctuation and token boundaries are part of the identifier you want to match.

AB-[0-9]{3} means a literal AB- followed by exactly three ASCII digits. It doesn’t match a value that contains that shape with extra characters on either end. The term dictionary syntax is not the same as System.Text.RegularExpressions: it rejects ^, $, look-around, and backreferences. You don’t need anchors because the end-to-end match is built in.

Decide whether you mean distinct terms or returned documents. The 10 in Search(query, 10) caps the returned hits. It doesn’t prevent a pattern from expanding to hundreds of terms. Conversely, if several products share one SKU, that SKU uses only one slot in the distinct-term budget but can match several documents.

MaxExpandedTerms defaults to 1,024 across all segments in the snapshot. Keep the default overflow policy (Throw) if completeness matters; on overflow, narrow the pattern rather than presenting a partial answer as complete. KeepMostFrequent is an explicit opt-in to drop terms outside the cap, keeping those found in the most documents. Terms present only in deleted documents can still count toward the cap until a merge removes them. See expanding queries.

All oneindex recipes