在RavenDb中多地图/减少工作?

时间:2011-12-22 22:05:42

标签: c# mapreduce ravendb

我已经阅读了Ayende的blog post on the multi map feature 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)?或者我做错了吗?

1 个答案:

答案 0 :(得分:4)

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

在第一个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(),