DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Data Engineering
  3. Databases
  4. Leaving the Relational Mindset- RavenDB's Trees

Leaving the Relational Mindset- RavenDB's Trees

Oren Eini user avatar by
Oren Eini
·
Apr. 04, 11 · News
Like (0)
Save
Tweet
Share
3.17K Views

Join the DZone community and get the full member experience.

Join For Free

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.

Database Relational database

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

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • DevOps Roadmap for 2022
  • PostgreSQL: Bulk Loading Data With Node.js and Sequelize
  • Three SQL Keywords in QuestDB for Finding Missing Data
  • Data Mesh vs. Data Fabric: A Tale of Two New Data Paradigms

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: