RavenDB custom sorting and when not to use it
RavenDB has the notion of Custom Sorters, basically, we allow you to inject your own logic into the sorting process. That allows you to run any complex logic you have around sorting. There are rarely good reasons to want to use that. A good use case for that is when you need to sort by an external value that mutates outside of your control. Let’s say that you have invoices in multiple currencies. You want to sort them by their value in USD. The catch, you need them sorted on the current exchange rate. For that reason, you can use the custom sorter that would use the current value of the currency as the sorting mechanism.
I should point out that from a business perspective, you’ll typically want to use the value that you had for the order at the time the order was made, but that is not related the the custom sorting feature.
Let’s take another example, however. Consider the following Enum:
We want to sort by the education level of our candidates, but by default, we’ll be sorting using the textual value of the field. That isn’t what we want. We can define a custom sorter for that, but there is a far better option, just tell us what the order should be in the index.
Here is a good example:
What we are doing here is simple, we translate the textual value to a numeric one. When we query the index, we can filter by the textual value and sort by the sort value, giving us what we want. This is far simpler and more robust. If you need to add additional values down the line, it is obvious where they need to go. A custom sorter, on the other hand, is far more capable, but also more complex to operate.
Comments
Out of curiosity, why are you working with strings values for the enum? Enum.ToString() results in string allocation, is Reflection based, and is generally not recommended for hot-path code... Knowing your performance views, I'm amazed to don't provide some caching mechanism for enums built-in...
Itay,
It's a bit complex. This is code that is running server side, so the Enum value doesn't actually exist. The client side serialized that to a string, and the
ToString()
call is a noop, basically.Comment preview