I have the following query, which is using painless script to create a script_score, which is used for sorting.
Following are my creation scripts -
PUT /listings/_doc/1
{
"prod_id" : 1,
"currency" : "USD",
"price" : 1
}
PUT /listings/_doc/2
{
"prod_id" : 2,
"currency" : "INR",
"price" : 60
}
PUT /listings/_doc/3
{
"prod_id" : 3,
"currency" : "EUR",
"price" : 2
}
PUT /listings/_doc/4
{
"prod_id" : 5,
"currency" : "MYR",
"price" : 1
}
The data looks like this -
{
"took" : 0,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 4,
"relation" : "eq"
},
"max_score" : 1.0,
"hits" : [
{
"_index" : "products",
"_type" : "_doc",
"_id" : "1",
"_score" : 1.0,
"_source" : {
"prod_id" : 1,
"currency" : "USD",
"price" : 1
}
},
{
"_index" : "products",
"_type" : "_doc",
"_id" : "2",
"_score" : 1.0,
"_source" : {
"prod_id" : 2,
"currency" : "INR",
"price" : 60
}
},
{
"_index" : "products",
"_type" : "_doc",
"_id" : "3",
"_score" : 1.0,
"_source" : {
"prod_id" : 3,
"currency" : "EUR",
"price" : 2
}
},
{
"_index" : "products",
"_type" : "_doc",
"_id" : "5",
"_score" : 1.0,
"_source" : {
"prod_id" : 5,
"currency" : "MYR",
"price" : 1
}
}
]
}
}
The query that I'm trying to run -
GET products/_search
{
"query": {
"function_score": {
"query": {
"match_all": {}
},
"functions": [{
"script_score": {
"script": {
"params": {
"usd": 1,
"isCheckOutUsd" : true,
"sgdBuy": 0.72,
"sgdSpot": 0.72,
"myrBuy": 0.24,
"myrSpot": 0.24,
"inrBuy": 0.014,
"inrSpot": 0.014,
"eurBuy": 1.12,
"eurSpot": 1.12
},
"source": """
double valueForComparision = 0;
if(doc.currency.value == 'usd'){
valueForComparision = doc.price.value;
}
else{
if(params.isCheckOutUsd){
String temp = doc.currency.value + "Buy";
valueForComparision = doc.price.value / params[temp];
}
else{
String temp = doc.currency.value + "Spot";
valueForComparision = doc.price.value / params[temp];
}
}
return valueForComparision;
"""
}
}
}]
}
},
"sort": [
{
"_score": {
"order": "desc"
}
}
]
}
I'm following this doc as a reference - https://www.elastic.co/guide/en/elasticsearch/painless/master/painless-walkthrough.html
Your if condition needs to be a boolean
Change this
if('isCheckOutUsd')
To this:
if(params.isCheckOutUsd)