Monday, July 16, 2018

Querying RavenDB Metadata

Need to query your RavenDB metadata? Read to understand.
We've been discussing RavenDB on this blog. On this post, I want to address a feature that's commonly asked: how to query metadata in RavenDB.
There are two ways to do this:
  • using an pre-defined index: adding metadata to an index and querying it;
  • using a dynamic: using dynamic indexes in the studio.

Querying Metadata in RavenDB using an Index

This should be your standard approach, basically resumed in:
  1. Access the document's metadata from your index;
  2. Query the indexes, using the metadata property as if it were a normal property.
 Here's what you should do to access a document's metadata from your index:

Once that set, here's how you would query it:

Simple enough, isn't it? This is the best option as your data will be always searched using the index causing minimum stress to your database.

Querying Metadata in RavenDB dynamically using the Studio

But sometimes is unavoidable: users will come to you and ask you to run some queries. What if you don't have that property indexed? You have to options:
  1. add that property to an index in rebuild the index - not recommended on production;
  2. run a query against the dynamic index in RavenDB. The dynamic index allows you to write your queries against the collection and RavenDB will, behind the scenes, create the index for you. Note that we shouldn't be doing this frequently because it adds some stress to the server as it will build an index to process that query but
In order to query for the metadata in the studio, here's how you should do it:

So, using the below Lucene query allows you to query a document's metadata using RavenDb. Just remember to select the dynamic index. In this case, I'm using the dynamic/Users index.

@metadata.Raven-Clr-Type:"HildenCo.User, HildenCo.Domain"

Querying metadata using Lucene in C#

If I wanted, we can also use the client api to query RavenDB Lucene from my C# application. The following example shows us how to do it:

Conclusion

On this post I tried to show a few ways to query metadata. Hope it helps.

See Also

About the Author

Bruno Hildenbrand      
Principal Architect, HildenCo Solutions.