How to store money in elasticsearch

I created an elasticsearch index, and my current mapping stores the dollar amount of an element as a string. This is difficult because I cannot correctly find / filter this value.

GET catalog/product/_search { "filter": { "range": { "price": { "from": 230.0, "to": 300.0 } } } } 

Where the price is displayed as a string. I used the string because, going from the python decimal value, I had problems when that value suddenly gets the values ​​at about 17.98999999999999999999998789. This happens sometimes, but I don’t want to go into the issue of switching from decimal decimal code to java double / float (so I'm just a str () thing).

Any thoughts on a better approach? Should I bite a bullet and match the price with double or floating?

+7
python elasticsearch
source share
2 answers

This is because ElasticSearch does not have a built-in type for decimals or currencies, so your value is most likely converted to float and suffers from floating point problems.

You can get around this by simply storing the value as long (for example, the number of cents, not dollars) and converting them from the decimal application side.

Since you will only do this conversion for the values ​​you are already listing, the performance impact should be negligible.

+7
source share

In the new version (tested on 5.0), probably the best option is to use scaled_float with scaling_factor = 100 , as in their example:

 PUT my_index { "mappings": { "my_type": { "properties": { "number_of_bytes": { "type": "integer" }, "time_in_seconds": { "type": "float" }, "price": { "type": "scaled_float", "scaling_factor": 100 } } } } } 

Here you can find the doc .

+6
source share

All Articles