Set Based Operations in RavenDB

In a relational database you work most of the time with a set of rows. This fundamental concept gives SQL its power and flexibility. You use this in every SELECT and when you have to update or delete many rows at once. To delete all orders with an id less than 100 you can write this command:

This feature of SQL is not possible with most of the NoSQL databases. One exception to this rule is RavenDB. Here you can use set based operations as you do in a relational database – only the syntax is a bit different.

This post is part of the RavenDB series. You can find the other parts here:

 

Bulk Deletes

To delete multiple documents at once you can use the DeleteByIndex() method. As the name suggests it will use a specific index to query the database. Once more we will need to use the Lucene-syntax and not LINQ. To delete all orders shipped to Sweden you would use this command:

You can use all the fields in the index to filter the documents. To delete by the document id or a shipping date you therefore have to use an appropriate index or create one with those fields on your own.

This DeleteByIndex() method checks for an up-to-date index and will stop the execution if the index is stale. There is an overload to change this behaviour but you should use allowStale: true with caution. Most likely you use a bulk operation to get all documents matching your criteria and this is not guaranteed when the index is stale.

 

Bulk Updates

Updating multiple documents is a little bit more complex than the batch delete operation. Not only do we need to use an index but also a patch command. This is the same as I explained for the HTTP API, but this time in C# code.

For the update we use the same index and combine two patch requests in the same command. The first PatchRequest() creates a new field “Tags” with the value “Overnight” while the second request will rename the field “Freight” to “Freightcosts”:

The resulting document looks like this:

Raven Set Operations

So far I only showed how you can update or delete a subset of your documents. While this is the most likely usage scenario you can also patch all your documents. All you need to change is the query to match every country:

 

Next

You can now update multiple documents at once without fetching them one by one. In the next post we will look on relations and how the can be represented in RavenDB.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.