刚刚升级到 v2,这不再有效;如果我尝试使用 Count(),我会收到类似的错误
public class Deck_Ratings : AbstractIndexCreationTask<DeckRating, Deck_Ratings.ReduceResult>
{
public class ReduceResult
{
public string DeckId { get; set; }
public int Rating { get; set; }
}
public Deck_Ratings()
{
Map = deckRatings => deckRatings.Select(deckRating => new
{
deckRating.DeckId,
deckRating.Rating
});
Reduce = reduceResults => reduceResults
.GroupBy(reduceResult => reduceResult.DeckId)
.Select(grouping => new
{
DeckId = grouping.Key,
Rating = grouping.Average(reduceResult => reduceResult.Rating)
});
}
}
最佳答案
禁止可能受缩减批次大小影响的聚合(例如 Count 和 Average),因为它们会产生错误的结果。您可能已经能够在 1.0 以下使用它,但是您的平均值可能是错误的,除非您的项目太少以至于它们都在一个缩减批次中完成。要了解有关减少批次的更多信息,请阅读 Map / Reduce - A Visual Explanation
您必须通过为每个项目求和 1 来计算项目。您必须通过将值的总和作为总数,将 1 的总和作为计数,然后将它们相除来平均项目。
public class Deck_Ratings : AbstractIndexCreationTask<DeckRating, Deck_Ratings.ReduceResult>
{
public class ReduceResult
{
public string DeckId { get; set; }
public int TotalRating { get; set; }
public int CountRating { get; set; }
public double AverageRating { get; set; }
}
public Deck_Ratings()
{
Map = deckRatings => deckRatings.Select(deckRating => new
{
deckRating.DeckId,
TotalRating = deckRating.Rating,
CountRating = 1,
AverageRating = 0
});
Reduce = reduceResults => reduceResults
.GroupBy(reduceResult => reduceResult.DeckId)
.Select(grouping => new
{
DeckId = grouping.Key,
TotalRating = grouping.Sum(reduceResult => reduceResult.TotalRating)
CountRating = grouping.Sum(reduceResult => reduceResult.CountRating)
})
.Select(x => new
{
x.DeckId,
x.TotalRating,
x.CountRating,
AverageRating = x.TotalRating / x.CountRating
});
}
}
关于c# - Reduce 不能在分组中包含 Average() 方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14233875/