Hiro Protagonist
Hiro Protagonist

Reputation: 483

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 !

Upvotes: 2

Views: 60

Answers (2)

Danielle
Danielle

Reputation: 3839

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

Upvotes: 5

Hiro Protagonist
Hiro Protagonist

Reputation: 483

Probably not ideal, but this works (talk about not seeing the forest for the trees...)

priceAverage = g.Sum(x => x.totalPrice) / g.Sum(x => x.areaCount)

Upvotes: 2

Related Questions