Awesome Indexing with RavenDB
Join the DZone community and get the full member experience.
Join For Freei am currently teaching a course in ravendb, and as usual during a course, we keep doing a lot of work that pushes what we do with ravendb. usually because we try to come up with new scenarios on the fly and adapting to the questions from the students.
in this case, we were going over the map/reduce stack and we kept coming more and more complex example and how to handle them, and then we got to this scenario.
given the following class structure:
1: public class animal { public string name { get; set; } public string species { get; set; } public string breed { get; set; } }
give me the count of all the species and all the breeds. that is pretty easy to do, right? in sql, you would write it like this:
select species, breed, count(*) from animals group by species, breed
and that is nice, but it still means that you have to do some work on the client side to merge things up to get the final result, since we want something like this:
-
dogs: 6
- german shepherd: 3
- labrador: 1
- mixed: 2
-
cats: 3
- street: 2
- long haired: 1
in ravendb, we can express the whole thing in a simple succinct index:
public class animals_stats : abstractindexcreationtask<animal, animals_stats.reduceresult> { public class reduceresult { public string species { get; set; } public int count { get; set; } public breedstats[] breeds { get; set; } public class breedstats { public string breed { get; set; } public int count { get; set; } } } public animals_stats() { map = animals => from animal in animals select new { animal.species, count = 1, breeds = new [] {new {animal.breed, count = 1}} }; reduce = animals => from r in animals group r by r.species into g select new { species = g.key, count = g.sum(x => x.count), breeds = from breed in g.selectmany(x => x.breeds) group breed by breed.breed into gb select new {breed = gb.key, count = gb.sum(x => x.count)} }; } }
and the result of this beauty?
and that is quite pretty, even if i say so myself.
Published at DZone with permission of Oren Eini, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments