带有map的RavenDB索引减少了不同

时间:2011-08-31 14:10:08

标签: mapreduce ravendb

我在RavenDB文档中需要一个稍微复杂的索引

给出了这样的文档定义:

public class PriceDocument
{
    public string Id { get; set; }
    public Guid PriceId { get; set; }
    public decimal Price { get; set; }
    public DateTime? PricingDate { get; set; }
    public string Source { get; set; }
    public int Version { get; set; }    
}

我需要获取给定productId的所有产品(我可以在查询时执行此操作) PricingDate(最新)和Source

是唯一的

所以给出以下数据:

var priceDocument = new PriceDocument  {
    Price = 1m,
    Id = productId + "/1",
    PricingDate = new DateTime(2011, 4, 1, 8, 0, 0),
    PriceId = productId,
    Source = "Bloomberg",
    Version = 1   
};

var priceDocument1 = new PriceDocument {
    Price = 1m,
    Id = productId + "/2",
    PricingDate = new DateTime(2011, 4, 1,9,0,0),
    PriceId = productId,
    Source = "Bloomberg", 
    Version = 1
};

我应该得到priceDocument1,因为它是最新的。

到目前为止,我有一个像这样定义的索引:

Map = docs => 
    from priceDocument in docs
    select new {
        PricingDate = priceDocument.PricingDate, 
        PricingSource = priceDocument.Source,
        Price = priceDocument.Price,
        PriceId = priceDocument.PriceId
    };

Reduce = results => 
    from result in results
    group result by new { result.PricingDate, result.Source } into price
    select new {
        PricingDate = price.Max(p => price.Key.PricingDate),
        PricingSource = price.Key.Source,
    };

但它在运行时不起作用,我得到AbstractIndexingExecuter||8||Failed to index documents for index (my index name)

我在一个单独的项目中重新创建了这个示例,我可以在Raven Studio的统计数据中看到我收到错误:

  

无法将类型'System.DateTimeOffset'隐式转换为'int'DateTime?更改为DateTime

没有运气。

我从使用日期切换到使用我可以依赖它递增所以现在索引看起来像这样:

Map = docs => 
    from priceDocument in docs
    select new {
        PricingDate = priceDocument.PricingDate,
        PricingSource = priceDocument.Source,
        ProductId = priceDocument.ProductId,
        ProductVersion = priceDocument.Version
    };

Reduce = results => 
    from result in results
    group result by new {
        result.PriceId,
        result.PricingDate,
        result.Source,
        result.Version
    } into price
    select new {
        PricingDate = price.Key.PricingDate,
        PricingSource = price.Key,
        ProductVersion = price.Max(p=> price.Key.Version)
    };

现在不抛出任何错误,但它也没有产生任何结果。

2 个答案:

答案 0 :(得分:5)

应该是这样的:

   PricingDate = price.Max(p => (DateTimeOffset)price.Key.PricingDate)

但你想要的不需要地图缩小索引。你可以通过使用:

来实现
session.Query<PriceDocument>()
       .Where(x=>x.ProduceId == prodId)
       .OrderByDescending(x=>x.PriceDate)
       .FirstOrDefault();

你的Map / Reduce索引不起作用的原因是你有不同的地图和输出输出。减少功能。

答案 1 :(得分:3)

尝试从

的Reduce部分更改此行
PricingDate = price.Max(p => price.Key.PricingDate)

PricingDate = price.Max(p => (int)price.Key.PricingDate)