David Nordvall
David Nordvall

Reputation: 13302

Does multi map/reduce work in RavenDb?

I've read Ayende's blog post on the multi map feature of RavenDB and have tried to implement it. I cannot get it to work through. What I have is basically the same as the example in the blog post:

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)
                            };
    }
}

Querying on the index always gives me the value 0 for the Value attribute. A little fiddling with the index makes it seem that the map for ChildDocument never retrieves any documents.

Should this work in the current stable RavenDB build (1.0.573)? Or am I doing it wrong?

Upvotes: 4

Views: 446

Answers (1)

Carlos Mendes
Carlos Mendes

Reputation: 2010

The reduce part of your index is wrong in the fields Foo and Bar.

In the first Map function you're setting Foo and Boo to null as the structure for the output of all Map functions has to be the exactly the same in a MultiMap Index. You have to use FirstOrDefault() instead of First()

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

Upvotes: 4

Related Questions