Recursive AI

Parse a Boolean search query in C#

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

Boolean search combines required, optional and excluded terms.

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<Note>();
index.Upsert(new Note { Id = "a", Title = "late" });
index.Commit();
var hits = index.SearchStrict(
    "Title:(late OR overdue) " +
    "AND NOT Title:paid");
Console.WriteLine(hits.Count());
public class Note
{
    [SearchId]
    public string Id { get; set; } = "";
    [FullText]
    public string Title { get; set; } = "";
}
Text
1

SearchStrict parses and runs the query; to obtain a query object separately, use StrictQuery.Parse(text, index.Schema) as shown in the strict parser docs.

Unzip the example, then dotnet run.

The full program

Runs a fielded AND/OR/NOT query with a numeric range, then reports the location and suggested field for a typed parse error. All documents are created inline in an in-memory index.

This example uses preview 0.4.0-preview.2; APIs and file formats may change between previews.

C#
using OneIndex;
using OneIndex.Queries;
using var index = SearchIndex.InMemory<Note>();
index.Upsert([
    new() { Id = "a", Title = "overdue", Tags = "invoice", Total = 120 },
    new() { Id = "b", Title = "late", Tags = "draft", Total = 150 },
    new() { Id = "c", Title = "late", Tags = "invoice", Total = 50 },
    new() { Id = "d", Title = "paid", Tags = "invoice", Total = 200 }
]);
index.Commit();
var hits = index.SearchStrict(
    "Title:(overdue OR late) AND NOT Tags:draft AND Total:[100 TO *]");
Console.WriteLine("Matches: " + string.Join(", ", hits.Select(h => h.Id)));
try { index.SearchStrict("Titel:overdue"); }
catch (QueryParseException error)
{
    Console.WriteLine($"{error.GetType().Name}: offset {error.Offset}; suggestion {error.Suggestion}");
}
public class Note
{
    [SearchId] public string Id { get; set; } = "";
    [FullText] public string Title { get; set; } = "";
    [Keyword] public string Tags { get; set; } = "";
    [Filterable] public int Total { get; set; }
}

dotnet run prints:

Text
Matches: a
QueryParseException: offset 0; suggestion Title

A malformed query or unknown field throws QueryParseException; the full program catches the misspelled field and prints its suggestion.

Variations

Parse and print syntax without executing it. Insert this before the full program’s Note class:

C#
var tree = StrictQuery.ParseSyntax("late OR overdue");
Console.WriteLine(StrictQuery.Print(tree));

The added output is:

Text
late OR overdue

Full-text search · Query JSON · Phrase search · Sparse vectors


The short answer

Use index.SearchStrict(text) to parse and execute a Boolean search expression in C#. Use StrictQuery.Parse(text, index.Schema) when you need a query object to compose before execution. This is search syntax over an index, not bool.Parse and not a general C# expression evaluator. The full program requires an overdue or late title, excludes the draft tag and requires a total of at least 100.

Title:(overdue OR late) AND NOT Tags:draft AND Total:[100 TO *] requires an overdue or late title, excludes drafts and selects totals of at least 100.

Create a document type with searchable fields, upsert documents, commit, then call SearchStrict. Field names come from the document schema and are case-sensitive. In this example, Title is analyzed full text, Tags is an exact keyword and Total is numeric. The same parser therefore turns a word into a text query on Title, an exact match on Tags and a range on Total.

Choose strict parsing when your interface exposes a query language, such as an advanced-search editor or a saved-query form. For an ordinary search box, index.Search(text) is the forgiving alternative: its user-text grammar accepts input without throwing a parse error. Switching to strict search changes the grammar; it is not just a stricter setting for the same parser.

How do AND, OR and NOT work in a search query?

In the strict grammar, NOT binds first, then AND, then OR. Adjacent operands imply AND. Consequently, a b OR c means (a AND b) OR c. Parentheses make the intended grouping explicit. Operators must be uppercase and unescaped: lowercase “and” is a searchable word, not an operator.

A field prefix applies to the next value. Before a group, it applies to every unqualified atom inside that group. Title:(overdue OR late) searches both words in Title. An explicitly qualified operand inside the group keeps its own field. An unqualified text operand instead searches the schema’s full-text fields.

[100 TO *] includes 100 and has no upper bound. Square brackets include an endpoint; braces exclude it. Numeric and date fields support ranges, but a range needs a field. In the full program, document b is excluded by its draft tag, c falls below the total, and d lacks either title word. Only a survives all clauses. This illustrates selection; scores are not Boolean truth values.

Catch QueryParseException around parsing. It carries Offset, Length, one-based Line and Column, Expected and Suggestion. Offsets are UTF-16 indexes, so they can identify the failing span in a .NET string. The example misspells Title as Titel; its suggestion names the schema field instead of silently searching nothing.

Use ParseSyntax when you only need a syntax tree, for example to reformat an editor’s contents. It does not check fields against a schema. StrictQuery.Print produces syntax that reads back to an equal tree, ignoring source positions; it adds explicit operators and parentheses rather than preserving the original formatting. Use schema-aware parsing before executing or accepting a saved query. The parser also rejects inputs beyond its documented character, nesting and node limits rather than accepting an unbounded expression.

All oneindex recipes