You are currently browsing legacy 4.0 version of documentation. Click here to switch to the newest 5.1 version.

We can help you with migration to the latest RavenDB

Contact Us Now
see on GitHub

Indexes: Indexing Hierarchical Data

One of the greatest advantages of a document database is that we have very few limits on how we structure our data. One very common scenario is the usage of hierarchical data structures. The most trivial of them is the comment thread:

class BlogPost {
    constructor(title, author, text, comments) {
        this.title = title; = author;
        this.text = text;
        this.comments = comments;

class BlogPostComment {
    constructor(author, text, comments) { = author;
        this.text = text;
        this.comments = comments;

While it is very easy to work with such a structure in all respects, it does bring up an interesting question, namely how can we search for all blog posts that were commented by specified author?

The answer to that is that RavenDB contains built-in support for indexing hierarchies, and you can take advantage of the Recurse method to define an index using the following syntax:

class BlogPosts_ByCommentAuthor extends AbstractIndexCreationTask {
    constructor() {
        super(); = "docs.BlogPosts.Select(post => new { " +
            "    authors = this.Recurse(post, x => x.comments).Select(x0 => " +
const indexDefinition = new IndexDefinition(); = "BlogPosts/ByCommentAuthor";
indexDefinition.maps = new Set([
        "from post in docs.Posts" +
        "  from comment in Recurse(post, (Func<dynamic, dynamic>)(x => x.comments)) " +
        "  select new " +
        "  { " +
        "      author = " +
        "  }"

await store.maintenance.send(new PutIndexesOperation(indexDefinition));

This will index all the comments in the thread, regardless of their location in the hierarchy.

const results = session
    .query({ indexName: "BlogPosts/ByCommentAuthor" })
    .whereEquals("authors", "Ayende Rahien")