Recursive AI

Run a search query from JSON in C#

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

JSON requests describe searches over indexed documents, not JSON-file contents.

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 { Title = "overdue" });
index.Commit();
var hits = index.Parse("""
    {"v":1,"q":"overdue","limit":5}
    """);
Console.WriteLine(hits.Count());
public class Note
{
    [SearchId]
    public string Id { get; set; } = "a";
    [FullText]
    public string Title { get; set; } = "";
}
Text
1

Unzip the example, then dotnet run.

The full program

The program searches for an overdue title, re-prints the request in normalized form, then catches a misspelled field name. 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();
const string json = """
{"v":1,"query":{"type":"term","field":"Title","value":"overdue"},"limit":5}
""";
Console.WriteLine("Matches: " + string.Join(", ", index.Parse(json).Select(h => h.Id)));
Console.WriteLine(QueryJson.Write(QueryJson.Read(json, index.Schema)));
try { index.Parse("""{"v":1,"query":{"type":"term","field":"Titel","value":"overdue"}}"""); }
catch (QueryParseException error)
{
    Console.WriteLine($"{error.GetType().Name}: path {error.Path}; 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
{"v":1,"query":{"type":"term","field":"Title","value":"overdue"},"limit":5}
QueryParseException: path $.query.field; suggestion Title

Invalid request properties or field names throw QueryParseException with a JSON path and, where available, a suggestion.

Variations

Run a numeric filter without scoring text. Insert this before the full program’s Note class:

C#
var filtered = index.Parse("""
    {"v":1,"filter":"Total >= 100","countExactly":true}
    """).Execute();
Console.WriteLine($"Filtered: {filtered.TotalHits}");

The added output is:

Text
Filtered: 3

Full-text search · Boolean queries · Phrase search · Sparse vectors


The short answer

Call index.Parse(json) to read a JSON search request against an existing OneIndex schema, then enumerate it or call Execute(). Use QueryJson.Read and QueryJson.Write to obtain a canonical representation. A request describes how to search documents already in the index; it is not a JSONPath expression or a way to search inside an arbitrary JSON string.

How do I run a search query from a JSON object in C#?

The required v property identifies request format version 1. The top snippet supplies q, which is forgiving user text, and limit. The full program instead uses a structured term node with a named field. All its JSON inputs appear inline, so no request file or HTTP endpoint is needed to reproduce the result.

A request can contain both q and query; when it does, both must match. filter narrows candidates without adding score and accepts a filter string or a query node. A request with neither q nor query starts from every document. This is why the variation can select documents by their numeric total alone.

Use the structured form when a caller already knows the desired field and operation. Use q for words someone types into a search box. A full-text term node takes a single already-analyzed term; it does not analyze an arbitrary sentence a second time. Phrase nodes similarly take analyzed terms in an array. The field’s analyzer and the query representation must agree.

What is the JSON search query syntax?

Parsing checks field names against the index schema and checks which query kinds each field permits. It also rejects unknown request properties. The full program deliberately names Titel, prints the resulting $.query.field path and shows the suggested Title spelling. Catch QueryParseException and display its diagnostic near the corresponding request property rather than returning a successful empty search.

This validation goes beyond syntactically valid JSON. A well-formed object can still contain an unknown field, a wrong value kind or an unsupported request version. Conversely, q is intentionally forgiving text; it is not the strict Boolean language. To carry that language in JSON, the documented strict node accepts a text property and retains the inner parser’s location in the error message.

The request reference documents size and nesting caps. It also caps result windows: limit and offset each range from 0 to 10,000, and their sum cannot exceed 10,000. The default limit is 20. Request countExactly: true when a UI needs an exact total rather than the default lower bound. A result limit and an exact total answer different questions.

Read a QueryRequest with QueryJson.Read(json, index.Schema), then pass it to QueryJson.Write. The full program prints the actual canonical output. This normalizes the query representation; it is not a promise to preserve whitespace, input property order or the original user-text spelling.

Canonical JSON is useful for showing what your application accepted or storing a query as data. Keep the schema available when reading it again: version 1 describes the request format, not the fields in your application. Renaming a searchable property can invalidate a saved request that references the old name. The schema check exposes that mismatch at read time. The example performs all these operations in process and makes no assumption about a web framework or transport.

All oneindex recipes