Friday, August 10, 2012

Self “joins” in RavenDB

Self “joins” in RavenDB:
A customer had an interesting problem in the mailing list. He had the following model:

public class Case
{
public string Id { get; set; }
public string[] CasesCitedByThisCase { get; set; }
public string Name { get; set; }
// other interesting properties
}



And he needed to be able to query and sort by the case’s properties, but also by its importance. A case important is determined by how many other cases are citing it.
This seems hard to do, because you cannot access other documents during standard indexing, so you have to use map reduce to make this work. The problem is that it is really hard to just map/reduce to make this work, you need two disparate sets of information from the documents.
This is why we have multi map, and we can create the appropriate index like this:

public class Cases_Search : AbstractMultiMapIndexCreationTask<Cases_Search.Result>
{
public class Result
{
public string Id { get; set; }
public int TimesCited { get; set; }
public string Name { get; set; }
}

public Cases_Search()
{
AddMap<Case>(cases =>
from c in cases
select new
{
c.Id,
c.Name,
TimesCited = 0
}
);

AddMap<Case>(cases =>
from c in cases
from cited in c.CasesCitedByThisCase
select new
{
Id = cited,
Name = (string)null,
TimesCited = 1
}
);

Reduce = results =>
from result in results
group result by result.Id
into g
select new
{
Id = g.Key,
Name = g.Select(x => x.Name).FirstOrDefault(x => x != null),
TimesCited = g.Sum(x => x.TimesCited)
};
}
}



We are basically doing two passes on the cases, one to get the actual case information, the next to get the information about the cases it cite. We then take all of that information together and reduce it together, resulting in the output that we wanted.
The really nice thing about this? This being a RavenDB index, all of the work is done once, and queries on this are going to be really cheap.


DIGITAL JUICE

No comments:

Post a Comment

Thank's!