Recursive AI

Filter search results by date range in C#

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

Set IncludeUpper = false in a RangeQuery to exclude the start of the next period.

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 start = new DateTimeOffset(2026, 11, 1,
    0, 0, 0, TimeSpan.Zero);
var end = start.AddMonths(1);
var storage = new MemoryStorage();
using var writer =
    IndexWriter.Open(storage, Schema());
Seed(writer, start, end);
 
using var view = IndexSnapshot.Open(storage);
var search = SnapshotSearch.CreateSearcher(view);
var range = new RangeQuery("published",
    FieldValue.FromDate(start), FieldValue.FromDate(end))
{
    IncludeLower = true,
    IncludeUpper = false
};
var result = search.Search(range, 10);
Console.WriteLine($"Matches: {result.TotalHits}");
 
static Schema Schema()
{
    return new SchemaBuilder()
        .Id("id").Date("published").Build();
}
 
static void Seed(IndexWriter writer,
    DateTimeOffset start, DateTimeOffset end)
{
    foreach (var (id, date) in new[] {
        ("old", start.AddMilliseconds(-1)),
        ("first", start),
        ("last", end.AddMilliseconds(-1)),
        ("next", end) })
        writer.Upsert(new Document().Add("id", id)
            .Add("published", date));
    writer.Commit();
}

Unzip the example, then dotnet run.

Text
Matches: 2

The full program

C#
using OneIndex.Index;
using OneIndex.Search;
using OneIndex.Storage;
 
var start = new DateTimeOffset(2026, 11, 1,
    0, 0, 0, TimeSpan.Zero);
var end = start.AddMonths(1);
var storage = new MemoryStorage();
using var writer =
    IndexWriter.Open(storage, Schema());
Seed(writer, start, end);
 
using var view = IndexSnapshot.Open(storage);
var search = SnapshotSearch.CreateSearcher(view);
var range = new RangeQuery("published",
    FieldValue.FromDate(start), FieldValue.FromDate(end))
{
    IncludeLower = true,
    IncludeUpper = false
};
var result = search.Search(range, 10);
foreach (var hit in result.Hits)
{
    var leaf = search.Context.Leaves
        .Last(leaf => leaf.DocBase <= hit.DocId);
    var doc = leaf.Reader.StoredFields!
        .GetDocument(hit.DocId - leaf.DocBase);
    Console.WriteLine(doc.Get("id").AsText());
}
 
static Schema Schema()
{
    return new SchemaBuilder()
        .Id("id").Date("published").Build();
}
 
static void Seed(IndexWriter writer,
    DateTimeOffset start, DateTimeOffset end)
{
    foreach (var (id, date) in new[] {
        ("old", start.AddMilliseconds(-1)),
        ("first", start),
        ("last", end.AddMilliseconds(-1)),
        ("next", end) })
        writer.Upsert(new Document().Add("id", id)
            .Add("published", date));
    writer.Commit();
}
Text
first
last

first lands exactly on the inclusive start; last is one millisecond before the end. The example excludes old and next, just outside that window. To print each stored id rather than just the count, the program finds the segment that owns the hit and subtracts the segment’s DocBase because StoredFields.GetDocument takes a segment-local ID, not a global hit ID.

If a document has no published value, a range on that field won’t match it.

Variations

Include everything on or after the start. Replace the range declaration with an open upper bound:

C#
var range = new RangeQuery("published",
    FieldValue.FromDate(start), null);
Text
Matches: 3

The short answer

Define a date field in the OneIndex schema, add dates as DateTimeOffset values, and search with a RangeQuery on that field. Convert both bounds with FieldValue.FromDate. Set IncludeLower = true and IncludeUpper = false to get dates on or after the start and strictly before the end. Both flags default to true, so leaving the upper flag at its default would include a document dated exactly at the start of the next period.

How do you search with a date range?

For November 2026 in UTC, use midnight on November 1 as the start and midnight on December 1 as the end. That includes any indexed time on November 30 without inventing a “last moment of the day.” December can start exactly where November ends, and no document belongs to both periods just because its timestamp is midnight. For an open-ended range, use null for the missing bound rather than making up a minimum or maximum date.

OneIndex stores date values as UTC milliseconds since the Unix epoch. Pass deliberate offsets when turning dates into timestamps. If a user picks calendar dates in a local time zone, determine the start and following midnight in that zone before passing their instants to the query. The UTC example uses TimeSpan.Zero for both boundaries; it isn’t a recipe for interpreting dates in the machine’s local time zone.

How do you filter search results by date without making newer items rank higher?

A date range answers whether a document belongs in the result, not whether it should rank first. On its own, RangeQuery scores each match with the same boost, so this example doesn’t sort by date. When you also have a text query, use the range as a filter clause in a Boolean query: the date check is required but doesn’t add to the score. That lets the text match still determine relevance inside the date window. If the field has several date values, any one in range is enough to match; a missing date never matches.

To try this with the snippet at the top, update the return statement in Schema():

C#
return new SchemaBuilder().Id("id")
    .Text("body").Date("published").Build();

In Seed(), replace the writer.Upsert call inside the loop:

C#
writer.Upsert(new Document().Add("id", id)
    .Add("published", date).Add("body", "coffee"));

Then replace var result = search.Search(range, 10); with the following. BooleanQuery, TermQuery and Occur come from OneIndex.Search, already imported in the snippet.

C#
var query = new BooleanQuery([
    new(new TermQuery("body", "coffee"), Occur.Must),
    new(range, Occur.Filter)
]);
var result = search.Search(query, 10);
Text
Matches: 2
All oneindex recipes