---
title: "Regex search over indexed keywords in C#"
url: https://recursiveai.org/oneindex/cookbook/search-indexed-keywords-with-regex/
description: "Use OneIndex RegexQuery to match whole product IDs in a C# search index. Run a local SKU example and cap the number of matching terms."
version: "0.4.0-preview.2"
---

# 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.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneIndex) · [GitHub](https://github.com/recursive-ai-oss/oneindex-csharp) · [Docs](https://recursiveai.org/oneindex/docs/) · [Download example (.zip)](https://recursiveai.org/oneindex/cookbook/search-indexed-keywords-with-regex/search-indexed-keywords-with-regex.zip)

Use `RegexQuery` with `AB-[0-9]{3}` to match whole product IDs like `AB-042`.

```shell
dotnet add package RecursiveAI.OneIndex --prerelease
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
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](https://recursiveai.org/oneindex/cookbook/search-indexed-keywords-with-regex/search-indexed-keywords-with-regex.zip) 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

```csharp
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:

```csharp
var query = new RegexQuery("sku", "(AB|CD)-[0-9]{3}");
```

```text
2
```

## Related recipes

- [Search documents by word prefix](https://recursiveai.org/oneindex/cookbook/search-documents-by-word-prefix/)
- [Read stored fields from a search hit](https://recursiveai.org/oneindex/cookbook/read-stored-fields-from-search-hit/)

## 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](https://recursiveai.org/oneindex/docs/term-dictionary/#regular-expression-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.

## How do you limit the number of matches in a regex search?

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](https://recursiveai.org/oneindex/docs/queries/#prefix-fuzzy-and-regular-expression).
