Search code examples
c#full-text-searchravendbfaceted-search

Grouping on search result - RavenDB


I have an index which displays text search results. Results are always displayed only for a single month.

I need to show how many results does each month has. Example is at the bottom.

I understand that Faceted search should do the job, but creating/generating ranges manualy is not possible and it would result in huge amount of ranges. I tried everything from official documentation, even ResultTransformers which is not the right tool. So I hope I must have overlooked something.

Map = transactions => from transaction in transactions
select new
    {
        Description = new object[] { transaction.Description, transaction.Items.Select(i => i.Name), transaction.Documents.Select(i => i.Name) },
        Account_UserName = transaction.Account.UserName,
        Time = transaction.Time
    };

Result I expect is something like this:

 [{
    Year: 2013,
    Month: 12,
    Count: 3
 },
 {
    Year: 2013,
    Month: 11,
    Count: 10
 }]

Solution

  • After some digging I found that Dynamic aggregation will do the job. I've added field month, because anonymous object didn't work.

    Map = transactions => from transaction in transactions
    select new
        {
            Value = transaction.Value,
            Description = new object[] { transaction.Description, transaction.Items.Select(i => i.Name) },
            Account_UserName = transaction.Account.UserName,
            Time = transaction.Time,
            Month = new DateTime(transaction.Time.Year, transaction.Time.Month, 1) // new field
        };
    

    And then extended query by .AggregateBy(x => x.Month).CountOn(x => x.Month);

    var result = _session.Query<Transaction, Transaction_Search>()
        .AggregateBy(x => x.Month)
        .CountOn(x => x.Month);
    

    This produces, after some transformation, desired result.