3

好的,给定这样的文档集合:

{ 
  "Name": "A",
  "Price": 1.50
}

如何对列表中的价格进行简单聚合?我不想执行任何分组,只是一个简单的标量结果。

IE。总和,平均等

我尝试了以下两种方法均未成功:

仅地图

for doc in docs
select new { sumPrices = Sum(d => d.Price) }

地图

for doc in docs
select new { price = d.Price }

减少

for result in results
select new { sumPrices = Sum(result) }
4

2 回答 2

3

这应该可以解决问题。

地图:

from doc in docs.Products
select new { Name = "Total", Total = doc.Price }

减少:

select new
{
    Name = g.Key,
    Total = g.Sum(x => (double)x.Total)
}

每个文档都经过 Map,聚合发生在 Reduce。但是从 Map 出来的模式仍然需要与您的结果相匹配。每个文档的“总计”就是它的价格。然后这些都在reduce中求和。

Name 属性有点没用,它只是为了给 reduce 一些东西来分组每个文档。

于 2011-10-08T12:35:01.903 回答
0

这就是我想出的。

地图:

from doc in docs 
where doc["@metadata"]["Raven-Entity-Name"] == "Books" 
select new { Name = "Total", Price = doc.Price };

减少:

from result in results 
group result by result.Name 
into g 
select new { Name = g.Key, Price = g.Sum(x => x.Price) }

但是,如果我将价格更改为整数,我只能让它工作。所以我的两个文档看起来像这样:

{
    "Name":"B",
    "Price":4
}
{
    "Name":"A",
    "Price":10
}

我的 JSON 输出如下所示:

{"Results":[{"Name":"Total","Price":"14","Price_Range":"14"}],"IsStale":false,"TotalResults":1}

显然,将价格更改为整数并不是解决方案。这可能是 RavenDB 中的一个错误,但我自己对它很陌生,所以我希望这只是我做我Sum()的方式或数据在文档中表示的方式。

于 2010-08-03T22:02:27.097 回答