在ElasticSearch中的嵌套键上过滤脚本

时间:2018-06-26 07:48:41

标签: elasticsearch

我有这些文件:

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 }  ] }
'

其中键discount是嵌套键。

我需要编写一个脚本,通过输入group_id(例如5)将百分比应用于价格并与计算出的价格进行比较。

我有这个主意:

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"
                     }
                }
            }
        }
    }
}

结果应仅为product_id => 1。 因为已将百分比(50%)应用于价格,并且该百分比小于200。

如果执行此脚本,则会出现此异常:

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

我正在尝试_source.pricectx._source.price,但由于相同的异常而失败。

0 个答案:

没有答案