Finding results by related documents
These are not the droids you are looking for! – Obi-Wan Kenobi
Sometimes you need to find a set of documents not because of their own properties, but based on a related document. A good example may be needing to find all employees that blue Nissan car. Here is the actual model:
In SQL, we’ll want a query that goes like this:
This is something that you cannot express directly in RavenDB or RQL. Luckily, you aren’t going to be stuck, RavenDB has a couple of options for this. The first, and the most closely related to the SQL option is to use a graph query. That is how you will typically query over relationships in RavenDB. Here is what this looks like:
Of course, if you have a lot of matches here, you will probably want to do things in a more efficient manner. RavenDB allows you to do so using indexes. Here is what the index looks like:
The advantage here is that you can now query on the index in a very simple manner:
RavenDB will ensure that you get the right results, and changing the Car’s color will automatically update the index’s value.
The choice between these two comes down to frequency of change and how large the work is expected to be. The index favors more upfront work for faster query times while the graph query option is more flexible but requires RavenDB to do more on each query.
Woah, already finished? 🤯
If you found the article interesting, don’t miss a chance to try our database solution – totally for free!