---
title: "Indexing Hierarchical Data"
url: "https://docs.ravendb.net/6.2/indexes/indexing-hierarchical-data"
version: "6.2"
language: "csharp"
---

# Indexing Hierarchical Data

> Client language: C#. Also available for [Java](https://docs.ravendb.net/6.2/indexes/indexing-hierarchical-data.java.md), [Python](https://docs.ravendb.net/6.2/indexes/indexing-hierarchical-data.python.md), [PHP](https://docs.ravendb.net/6.2/indexes/indexing-hierarchical-data.php.md), [Node.js](https://docs.ravendb.net/6.2/indexes/indexing-hierarchical-data.nodejs.md).
>
> RavenDB publishes an official agent skill for coding assistants at https://docs.ravendb.net/skills/ravendb/SKILL.md (also installable with `npx skills add ravendb/skills`). The skill describes itself as: "Read this before writing any RavenDB query, client call or /databases/ request. Covers server setup, document modelling, the Node.js, .NET and Python clients, RQL, indexes, vector search and AI agents. Code written from recall tends to run and return the wrong rows, because RQL resembles SQL and the clients take field names as plain strings."

> **Note**
>
> - Use the `Recurse` method to traverse the layers of a hierarchical document and index its fields.
>
> - In this Page:
>   - [Hierarchical data](#hierarchical-data)
>   - [Index hierarchical data](#index-hierarchical-data)
>   - [Query the index](#query-the-index)

## Hierarchical data

One significant advantage of document databases is their tendency not to impose limits on data structuring.
**Hierarchical data structures** exemplify this quality well; for example, consider the commonly used comment thread, implemented using objects such as:

```csharp
public class BlogPost
{
  public string Author { get; set; }
  public string Title { get; set; }
  public string Text { get; set; }

  // Blog post readers can leave comments
  public List<BlogPostComment> Comments { get; set; }
}

public class BlogPostComment
{
  public string Author { get; set; }
  public string Text { get; set; }

  // Allow nested comments, enabling replies to existing comments
  public List<BlogPostComment> Comments { get; set; }
}
```

Readers of a post created using the above `BlogPost` structure can add `BlogPostComment` entries to the post's *Comments* field,
and readers of these comments can reply with comments of their own, creating a recursive hierarchical structure.

For example, the following document, `BlogPosts/1-A`, represents a blog post by John that contains multiple layers of comments from various authors.

`BlogPosts/1-A`:

```json
{
  "Author": "John",
  "Title": "Post title..",
  "Text": "Post text..",
  "Comments": [
      {
          "Author": "Moon",
          "Text": "Comment text..", 
          "Comments": [
              {
                  "Author": "Bob",
                  "Text": "Comment text.."
              },
              {
                  "Author": "Adel",
                  "Text": "Comment text..", 
                  "Comments": {
                      "Author": "Moon",
                      "Text": "Comment text.."
                  }
              }
          ]
      }
  ],
  "@metadata": {
      "@collection": "BlogPosts"
  }
}
```

## Index hierarchical data

To index the elements of a hierarchical structure like the one above, use RavenDB's `Recurse` method.

The sample index below shows how to use `Recurse` to traverse the comments in the post thread and index them by their authors.
We can then [query the index](#query-the-index) for all blog posts that contain comments by specific authors.

### Index

```csharp
public class BlogPosts_ByCommentAuthor : 
  AbstractIndexCreationTask<BlogPost, BlogPosts_ByCommentAuthor.IndexEntry>
{
  public class IndexEntry
  {
      public IEnumerable<string> Authors { get; set; }
  }

  public BlogPosts_ByCommentAuthor()
  {
      Map = blogposts => 
          from blogpost in blogposts
          let authors = Recurse(blogpost, x => x.Comments)
          select new IndexEntry
          {
              Authors = authors.Select(x => x.Author)
          };
  }
}
```

### JavaScript\_index

```csharp
public class BlogPosts_ByCommentAuthor_JS : AbstractJavaScriptIndexCreationTask
{
  public class Result
  {
      public string[] Authors { get; set; }
  }

  public BlogPosts_ByCommentAuthor_JS()
  {
      Maps = new HashSet<string>
      {
          @"map('BlogPosts', function (blogpost) {

                var authors =
                     recurse(blogpost.Comments, function(x) {
                         return x.Comments;
                     })
                    .filter(function(comment) { 
                         return comment.Author != null;
                     })
                    .map(function(comment) { 
                        return comment.Author;
                     });

                return {
                   Authors: authors
                };
          });"
      };
  }
}
```

### Put\_indexes\_operation

```csharp
store.Maintenance.Send(new PutIndexesOperation(
  new IndexDefinition
  {
      Name = "BlogPosts/ByCommentAuthor",
      Maps =
      {
          @"from blogpost in docs.BlogPosts
            let authors = Recurse(blogpost, (Func<dynamic, dynamic>)(x => x.Comments))
            let authorNames = authors.Select(x => x.Author)
            select new
            {
                Authors = authorNames
            }"
      }
  }));
```

## Query the index

The index can be queried for all blog posts that contain comments made by specific authors.

**Query the index using code**:

### Query

```csharp
List<BlogPost> results = session
  .Query<BlogPosts_ByCommentAuthor.IndexEntry, BlogPosts_ByCommentAuthor>()
   // Query for all blog posts that contain comments by 'Moon':
  .Where(x => x.Authors.Any(a => a == "Moon"))
  .OfType<BlogPost>()
  .ToList();
```

### Query\_async

```csharp
List<BlogPost> results = await asyncSession
  .Query<BlogPosts_ByCommentAuthor.IndexEntry, BlogPosts_ByCommentAuthor>()
   // Query for all blog posts that contain comments by 'Moon':
  .Where(x => x.Authors.Any(a => a == "Moon"))
  .OfType<BlogPost>()
  .ToListAsync();
```

### DocumentQuery

```csharp
List<BlogPost> results = session
  .Advanced
  .DocumentQuery<BlogPost, BlogPosts_ByCommentAuthor>()
   // Query for all blog posts that contain comments by 'Moon':
  .WhereEquals("Authors", "Moon")
  .ToList();
```

### RQL

```sql
from index "BlogPosts/ByCommentAuthor"
where Authors == "Moon"
```

**Query the index using Studio**:

- Query the index from the Studio's [List of Indexes](https://docs.ravendb.net/6.2/studio/database/indexes/indexes-list-view.md#indexes-list-view) view:

  !["List of Indexes view"](https://docs.ravendb.net/assets/images/list-of-indexes-view-0264fd76eb532b875ff987b54ac8b1a5.png)

- View the query results in the [Query](https://docs.ravendb.net/6.2/studio/database/queries/query-view.md) view:

  !["Query View"](https://docs.ravendb.net/assets/images/query-view-3bf9519c65639130153355e9601b0bfc.png)

- View the list of terms indexed by the `Recurse` method:

  !["Click to View Index Terms"](https://docs.ravendb.net/assets/images/click-to-view-terms-b3e9856139362596d1c7cc1bd99c5c34.png)

  !["Index Terms"](https://docs.ravendb.net/assets/images/index-terms-59dbac19292c26ef6b64fc4cb5c60512.png)

## See also

- [Indexing Basics](https://docs.ravendb.net/6.2/indexes/indexing-basics.md)
- [Indexing Related Documents](https://docs.ravendb.net/6.2/indexes/indexing-related-documents.md)
- [Indexing Spatial Data](https://docs.ravendb.net/6.2/indexes/indexing-spatial-data.md)
- [Indexing Polymorphic Data](https://docs.ravendb.net/6.2/indexes/indexing-polymorphic-data.md)
- [Basics](https://docs.ravendb.net/6.2/indexes/querying/query-index.md)
- [Query Overview](https://docs.ravendb.net/6.2/client-api/session/querying/how-to-query.md)
