Recursive AI

Aggregate search results by month in C#

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

A date histogram counts matching documents in calendar buckets. OneIndex’s date buckets use UTC.

Terminal
dotnet add package RecursiveAI.OneIndex --prerelease

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

C#
using OneIndex;
using OneIndex.Aggregations;
 
using var index =
    SearchIndex.InMemory<Entry>();
index.Upsert(new Entry {
    Added = DateTime.UtcNow });
index.Commit();
var result = index.Search()
    .Aggregate(a => a.DateHistogram(
    "months", x => x.Added, DateInterval.Month)).Execute();
var months = result.Aggregations
    .Get<BucketsResult>("months");
Console.WriteLine(months.Buckets[0].DocCount);
 
public class Entry
{
    [SearchId]
    public string Id { get; set; } = "1";
    [Sortable]
    public DateTime Added { get; set; }
}
Text
1

Unzip the example, then dotnet run.

The full program

The download indexes three release entries and one draft, using explicit UTC dates. Search("release") limits the counts to documents matching “release”. Take(1) returns one hit, but the monthly counts include all three releases. This example uses OneIndex 0.4.0-preview.2, a preview release.

C#
using OneIndex;
using OneIndex.Aggregations;
 
using var index = SearchIndex.InMemory<Entry>();
index.Upsert([
    new() { Id = "a", Text = "release", Added = new(2026, 1, 5, 0, 0, 0, DateTimeKind.Utc) },
    new() { Id = "b", Text = "release", Added = new(2026, 1, 20, 0, 0, 0, DateTimeKind.Utc) },
    new() { Id = "c", Text = "release", Added = new(2026, 3, 1, 0, 0, 0, DateTimeKind.Utc) },
    new() { Id = "d", Text = "draft", Added = new(2026, 2, 1, 0, 0, 0, DateTimeKind.Utc) }
]);
index.Commit();
var result = index.Search("release").Take(1)
    .Aggregate(a => a.DateHistogram(
        "months", x => x.Added, DateInterval.Month)).Execute();
Console.WriteLine($"Returned hits: {result.Count}");
Console.WriteLine($"Matching documents: {result.TotalHits}");
var months = result.Aggregations.Get<BucketsResult>("months");
foreach (var bucket in months.Buckets)
    Console.WriteLine($"{bucket.Key.Text}: {bucket.DocCount}");
 
public class Entry
{
    [SearchId] public string Id { get; set; } = "";
    [FullText] public string Text { get; set; } = "";
    [Sortable] public DateTime Added { get; set; }
}

dotnet run prints:

Text
Returned hits: 1
Matching documents: 3
2026-01-01T00:00:00.000Z: 2
2026-02-01T00:00:00.000Z: 0
2026-03-01T00:00:00.000Z: 1

[Sortable] stores the date property in a column that the histogram can read; documents without a date value enter no bucket.

Variations

To group the same matching documents by calendar quarter instead, replace the result query and print loop with:

C#
var result = index.Search("release").Take(1)
    .Aggregate(a => a.DateHistogram(
        "quarters", x => x.Added, DateInterval.Quarter)).Execute();
var quarters = result.Aggregations.Get<BucketsResult>("quarters");
foreach (var bucket in quarters.Buckets)
    Console.WriteLine($"{bucket.Key.Text}: {bucket.DocCount}");
Text
2026-01-01T00:00:00.000Z: 3

Faceted search · Full-text search

The short answer

Attach DateHistogram to the search with DateInterval.Month, then read a BucketsResult from result.Aggregations by its request name. OneIndex computes the histogram over every matching document, not only the hits returned by Take. Mark the DateTime property [Sortable] to store the date column the histogram reads.

The short snippet creates one entry and prints its bucket count. The download uses fixed input dates so you can see the month labels, the empty February bucket and a March entry that still contributes when the hit limit is one. No input file or service is needed.

What is a date histogram aggregation?

A date histogram groups timestamps into time intervals and counts the matching documents in each interval. In OneIndex, each bucket key identifies its start: Key.Text is ISO 8601, while Key.Whole holds milliseconds from the epoch. The example prints the textual key so the UTC boundary remains visible. Use that key, rather than the position of a bucket in an array, when attaching counts to chart labels.

For a monthly search chart, the difference between collecting hits and aggregating matches is essential. Grouping only the documents in the first page would make the chart depend on page size and relevance order. The downloaded program deliberately requests one hit. Its histogram still counts two January releases and one March release, because all matching documents feed the aggregation. The draft does not count, even though its timestamp falls between those months: it fails the search query.

A document contributes once to a bucket, even when several of its field values fall into that bucket. A document missing the date contributes to none. These are document counts, not counts of occurrences of a date value. The aggregation documentation defines those rules for all bucket aggregations.

How do you aggregate search results by month?

Use the search’s aggregation builder as in the full program, with a name such as months that you reuse when retrieving the result. Leave the hit limit at the value your UI needs; it does not set the population of the histogram. Search text and filters do set that population, so change them together with the chart when the user refines a search.

Choose the calendar month interval rather than approximating a month with a fixed number of days. OneIndex offers calendar seconds, minutes, hours, days, weeks, months, quarters and years. Weeks start on Monday. Its date histograms use UTC buckets; this example does not promise local-time month boundaries. Decide whether UTC grouping matches your reporting requirement before using the counts as business-month totals.

Empty intervals between the first and last occupied buckets are filled by default. That is why February appears with zero releases even though it contains a draft. A zero month is different from a missing date: it describes a gap in the matched time series, not a document without a date. The example does not extend the series outside its first and last populated months.

The quarter variation rolls all three releases into the bucket beginning January 1. Aggregations require visiting every match; reducing Take only reduces returned hits, not the aggregation’s work. For monthly charts, keep the search filters as specific as the chart actually needs rather than assuming the top-hit limit restricts counting.

All oneindex recipes