averageravendbreduceravendb-studio

Syntax question on reduce part of RavenDB index, average calculation


I am struggling with the correct syntax for an averaging column. What I have - from RavenDB Studio editor:

Map:

from area in docs.Level5_AdministrativeAreas
select new 
{
     area.NAME_4,
     totalPrice = area.pricePerSquareMetre,
     areaCount = 1,
     priceAverage = 0
}

Reduce:

from result in results
group result by new { result.NAME_4 } into g
select new 
{
   NAME_4 = g.Key.NAME_4,
   totalPrice = g.Sum(x => x.totalPrice),
   areaCount = g.Sum(x => x.areaCount),
   priceAverage = totalPrice / areaCount
}

Count and total price are being calculated correctly, but I don't know how to reference totalPrice and areaCount.

Is an extra select block required ? I tried "g.totalPrice" & "g.priceAverage", but it's not recognised.

Thank you for your help !


Solution

  • The Reduce part needs to be like this :

    Reduce:

    from result in results
    group result by new { result.NAME_4 } into g
    let theCount = g.Sum(x => x.areaCount)
    let theTotal = g.Sum(x => x.totalPrice)
    select new 
    {
       NAME_4 = g.Key.NAME_4,
       totalPrice = theTotal,
       areaCount = theCount ,
       priceAverage = theTotal / theCount 
    }
    

    => Read section Common Pitfalls with MapReduce Indexes