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:- Access the document's metadata from your index;
- Query the indexes, using the metadata property as if it were a normal property.
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:- add that property to an index in rebuild the index - not recommended on production;
- 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
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
- A simple introduction to RavenDB
- Installing and Running RavenDB on Windows and Linux
- An in-depth review of the RavenDB Cloud
- Patching RavenDB Metadata
- Creating ASP.NET Core websites with Docker
- Send emails from ASP.NET Core websites using SendGrid and Azure
For more RavenDB posts on this blog, please click here.