Filter script on nested key in ElasticSearch


(Roman šlancar) #1

I have these documents:

curl -XPOST -H 'Content-Type: application/json' "http://localhost:9200/test/_bulk?pretty" -d'
{"index":{"_index":"test","_type":"product"}},
{"product_id": 1, "price": 260, "discount": [ { "group_id": 5, "percent": 50 }, { "group_id": 7, "percent": 10 } ] },
{"index":{"_index":"test","_type":"product"}},
{"product_id": 2, "price": 250, "discount": [ { "group_id": 4, "percent": 10 }, { "group_id": 2, "percent": 17 }, { "group_id": 3, "percent": 15 }  ] }
'

Where key discount is nested key.

I need to write a script which, by input group_id e.g., 5, applies percentages to the price and compares with this calculated price.

I have this idea:

curl -XGET -H "Content-Type: application/json" "http://localhost:9200/test/product/_search?pretty" -d'
{
    "query": {
        "bool" : {
            "must" : {
                "script" : {
                    "script" : {
                        "source": """
                            int percent = 0; 
                            int price = doc['price']; 

                            for (int i = 0; i < doc['discount'].length; ++i) { 
                                if(doc['discount'][i]['group_id'] == 5) { 
                                    percent = doc['discount'][i]['percent']; 
                                    break; 
                                }
                          } 
                          
                          if(percent > 0) { 
                              price = price - (percent * price / 100); 
                          } 
                          
                          return (price < 200);"
                        """,  
                        "lang": "painless"
                     }
                }
            }
        }
    }
}

The result should be only product_id => 1.
Because the percentage (50%) has been applied to the price and it is less than 200.

If I execute this script I'll get this exception:

  "lang" : "painless",
  "caused_by" : {
    "type" : "illegal_argument_exception",
    "reason" : "Variable [price] is not defined."
  }

I'm trying _source.price or ctx._source.price but unsuccessfully with the same exception.


(system) #2

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.