我有一个稍微复杂的索引,我需要一个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' to '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)
};
现在没有抛出错误,但是它也没有给出结果。
应该是这样:
PricingDate = price.Max(p => (DateTimeOffset)price.Key.PricingDate)
但是你想要的并不需要map reduce索引。你可以使用:
session.Query<PriceDocument>()
.Where(x=>x.ProduceId == prodId)
.OrderByDescending(x=>x.PriceDate)
.FirstOrDefault();
你的Map/Reduce索引不起作用的原因是你有不同的Map &减少功能。
尝试从
更改索引的Reduce部分中的这一行PricingDate = price.Max(p => price.Key.PricingDate)
PricingDate = price.Max(p => (int)price.Key.PricingDate)