Over a million developers have joined DZone.

Leaving the Relational Mindset- RavenDB's Trees

DZone's Guide to

Leaving the Relational Mindset- RavenDB's Trees

· Database Zone
Free Resource

Learn how to create flexible schemas in a relational database using SQL for JSON.

One of the common problems with people coming over to RavenDB is that they still think in relational terms, implicitly accepting relational limitations. Here's an issue from a recent client meeting.  The client was getting an error when rendering a page similar to this one: 

The error is one of RavenDB’s Safe-By-Default, and is triggered when you are making too many calls. This is usually something that you want to catch early, and fail fast rather than add an additional load to the system. But the problem that the customer was dealing with is that they needed to display different icons for each level of the tree, depending on whether the item was a container or a leaf.

Inside Raven, categories were modeled as:

{ // categories/1
"ParentId": null,
"Name": "Welcome ..."

{ // categories/2
"ParentId": "categories/1",
"Name": "Chapter 2..."

They had a few more properties, but none that really interests us for this post. The original code was pretty naïve, and did something like this:

public IEnumerable<TreeNode> GetNodesForLevel(string level)
var categories = from cat in session.Query<Category>()
where cat.ParentId == level
select cat;

foreach(var category in categories)
var childrenQuery = from cat in session.Query<Category>()
where cat.ParentId == category.Id
select cat;

yield return new TreeNode
Name = category.Name,
HasChildren = childrenQuery.Count() > 0


As you can imagine, this has caused some issues, because we have a classic Select N+1 here.

Now, if we were using SQL, we could have done something like:

select *, (select count(*) from Categories child where child.ParentId = parent.Id)
from Categories parent
where parent.ParentId = @val


The problem there is that this is a correlated subquery, and that can get expensive quite easily. Other options include denormalizing the count into the Category directly, but we will ignore that.

What we did in Raven is define a map/reduce index to do all of the work for us. It is elegant, but it requires somewhat of a shift in thinking, so let me introduce that one part at a time:


from cat in docs.Categories 
let ids = new []
new { cat.Id, Count = 0, cat.ParentId },
new { Id = cat.ParentId, Count = 1, ParentId = (string)null }
from id in ids
select id


We are doing something quite strange, we need to project two items for every category. The syntax for that is awkward, I’ll admit, but it is pretty clear what is going on in here.

Using the categories shown above, we get the following output:

    { "Id": "categories/1", "Count" = 0, ParentId: null }
{ "Id": null, "Count" = 1, ParentId: null }

{ "Id": "categories/2", "Count" = 0, ParentId: "categories/1" }
{ "Id": "categories/1", "Count" = 1, ParentId: null }


The reason that we are doing this is that we need to be able to aggregate across all categories, whether they are in a parent child relationship or not. In order to do that, we project one record for ourselves, with count set to zero (because we don’t know that we are anyone’s parents) and one for our parent. Note that in the parent case, we don’t know what his parent is, so we set it to null.

The next step is to write the reduce part, which runs over the results of the map query:

    from result in results
group result by result.Id into g
let parent = g.FirstOrDefault(x=>x.ParentId != null)
select new
Id = g.Key,
Count = g.Sum(x=>x.Count),
ParentId = parent == null ? null : parent.ParentId


Here you can see something quite interesting, we are actually group only on the Id of the results. So given our current map results, we will have three groups:

  • Id is null
  • Id is “categories/1”
  • Id  is “categories/2”

Note that in the projection part, we are trying to find the parent for the current grouping, we do that by looking for the first record that was emitted, the one where we actually include the ParentId from the record. We then use count to check how many children a category have. Again, because we are emitting a record with Count equal to zero for the each category, they will be included even if they don’t have any children.

The result of all of that is that we will have the following items indexed:

{ "Id": null, "Count": 1, "ParentId": null }
{ "Id": "categories/1", "Count": 1, "ParentId": null }
{ "Id": "categories/2", "Count": 0, "ParentId": "categories/1" }


We can now query this index very efficiently to find who are the children of a specific category, and what is the count of their children.

How does this solution compare to writing the correlated sub query in SQL? Well, there are two major advantages:

  • You are querying on top of the pre-computed index, that means that you don’t need to worry about things like row locks, number of queries, etc. Your queries are going to be blazing fast, because there is no computation involved in generating a reply.
  • If you are using the HTTP mode, you get caching by default. Yep, that is right you don’t need to do anything, and you don’t need to worry about managing the cache, or deciding when to expire things, you can just take advantage on the native RavenDB caching system, which will handle all of that for you.

Admittedly, this is a fairly simple example, but using similar means, we can create very powerful solutions. It all depends on how we are thinking on our data.

Create flexible schemas using dynamic columns for semi-structured data. Learn how.


Published at DZone with permission of Oren Eini, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}