多地图/减少工作在RavenDb

本文关键字:工作 RavenDb 地图 | 更新日期: 2023-09-27 18:18:42

我读了Ayende关于RavenDB多地图特性的博文,并尝试实现它。我没法把它搞定。我所拥有的与博客文章中的示例基本相同:

class RootDocument {
    public string Id { get; set; }
    public string Foo { get; set; }
    public string Bar { get; set; }
}
public class ChildDocument {
    public string Id { get; set; }
    public string RootId { get; set; }
    public int Value { get; set; }
}
class RootsByIdIndex: AbstractMultiMapIndexCreationTask<RootsByIdIndex.Result> {
    public class Result {
        public string Id { get; set; }
        public string Foo { get; set; }
        public string Bar { get; set; }
        public int Value { get; set; }
    }
    public RootsByIdIndex() {
        AddMap<ChildDocument>(children => from child in children
                                          select new {
                                              Id = child.RootId,
                                              Foo = (string)null,
                                              Bar = (string)null,
                                              Value = child.Value
                                          });
        AddMap<RootDocument>(roots => from root in roots
                                      select new {
                                          Id = root.Id,
                                          Foo = root.Foo,
                                          Bar = root.Bar,
                                          Value = 0
                                      });
        Reduce = results => from result in results
                            group result by result.Id into g
                            select new {
                                Id = g.Key,
                                Foo = g.Select(x => x.Foo).Where(x => x != null).First(),
                                Bar = g.Select(x => x.Bar).Where(x => x != null).First(),
                                Value = g.Sum(x => x.Value)
                            };
    }
}

查询索引总是给我value属性的值0。对索引稍加改动,就会使ChildDocument的映射看起来从未检索到任何文档。

这应该在当前稳定的RavenDB构建(1.0.573)中工作吗?还是我做错了?

多地图/减少工作在RavenDb

索引的reduce部分在Foo和Bar字段中是错误的。

在第一个Map函数中,您将Foo和Boo设置为null,因为所有Map函数的输出结构在MultiMap Index中必须完全相同。你必须用FirstOrDefault()而不是First()

Foo = g.Select(x => x.Foo).Where(x => x != null).FirstOrDefault(),
Bar = g.Select(x => x.Bar).Where(x => x != null).FirstOrDefault(),