I have an index in ES that has, in addition to other fields, revenue_amount and revenue_currency fields. The revenue is stored in different currencies. At run time, all currencies are converted to USD and rendered.
Now, I would like to support sorting on the revenue_amount field. The problem is ES sorts results in terms of revenue prior to converting to USD, and so a revenue returned at the top might not be the highest revenue after converting to USD.
I was wondering, if its possible that before sorting, ES calls a user-defined function that changes a field value, and then apply sort afterwards? Something like this:
revenue_converted = convertToUSD(revenue)
And so the sorting will be applied to revenue_converted, rather than revenue.
I know I can convert the currencies at index time, but that will require refreshing the index every time the rates are updated, and so I would like to avoid it, if possible.
You have two ways of achieving this: one is by using script-based sorting as keety mentioned:
The
usd_conversion_rate
factor is the conversion rate to USD. So for instance, if 1 USD is worth 2.34 units of another currency, theusd_conversion_rate
factor would be1 / 2.34
(or0.4273
). When multiplied withrevenue_amount
it'll give you the amount in the USD reference currency.Script-based sorting is not very performant, though, and the recommendation is to use a
function_score
so results can be sorted by score instead. That leads us to the second way of achieving what you need and it goes like this. One way is by using ascript_score
function, but that involves scripting again.Since our above script was very simple (i.e. multiply a field by some factor), the simplest way would involve using
field_value_factor
and it goes like this:UPDATE
According to your latest comment, it seems that the right option for you is to use
script_score
after all. The idea here would be to input all your currency rates available in your lookup table as parameters of yourscript_score
script and then use the proper one according to the value of therevenue_currency
field.