i am looking for a possibility to find the nearest price / number with the help of elasticsearch. the problem is that i do not have a range. what i want to achieve is that the results are sorted by nearest distance. according to the example search query my index contains 3 documents with the following prices (numbers): 45, 27, 32
the "distance" from my search value 29 for the given numbers are 45 - 29 = 16 | 27 - 29 = -2 | 32 - 29 = 3 so what i would expect is that the search results are scored by the "distance" the number is away from the given price.
search query example:
GET myawesomeindex/_search
{
"query": {
"bool": {
"should": [
{
"match": {
"description": "this is the text i want to find"
}
},
{
"match": {
"price": 29
}
}
]
}
}
}
i think my question is related to this similar question: Elasticsearch scoring based on how close a number is to a query
There you go:
"sort": {
"_script": {
"type": "number",
"script": "return doc['price'].value-distance",
"params": {
"distance": 29
},
"lang": "groovy",
"order": "desc"
}
}
And you need to enable dynamic scripting.
You can, also, do it like this
"query": {
"function_score": {
"query": {
"bool": {
"should": [
{
"match": {
"description": "this is the text i want to find"
}
},
{
"match": {
"price": 29
}
}
]
}
},
"functions": [
{
"exp": {
"price": {
"origin": "29",
"scale": "1",
"decay": 0.999
}
}
}
]
}
}
But this will alter the score
itself. If you want pure sorting by the distance (and nothing else) then I believe the first option is the best.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With