由于插入性能,我有一个想批量存储小文档的场景。但我当然希望能够搜索单个项目。
public class Batch
{
public Guid Id { get; set; }
public Item[] Items { get; set; }
}
public class Item
{
public int Id { get; set; }
public string Description { get; set; }
}
假设我想按描述搜索并且我希望返回 ID。我创建了以下非常简单的 map/reduce 索引,我希望这样做:
Map = batches =>
from batch in batches
from item in batch.Items
select new Result
{
Description = item.Description,
ItemIds = new[] {item.Id}
};
Reduce = results =>
from result in results
group result by result.Description into g
select new Result
{
Description = g.Key,
ItemIds = g.SelectMany(x => x.ItemIds).ToArray()
};
使用此索引的查询不会失败,只是不会返回任何结果。
如果只对索引进行一点修改,使用 string.Join 而不是 SelectMany 来获取 ID,一切正常。
Map = batches =>
from batch in batches
from item in batch.Items
select new Result
{
Description = item.Description,
ItemIdsAsString = item.Id.ToString(),
};
Reduce = results =>
from result in results
group result by result.Description into g
select new Result
{
Description = g.Key,
ItemIdsAsString = string.Join("|", g.Select(x => x.ItemIdsAsString)),
};
行为完全相同,只是 ID 现在存储为“2|5|7”而不是这些整数的数组。但是这一次,索引产生了正确的结果。
SelectMany 在 Reduce 表达式中不起作用的原因是什么?