这是我的代码:
const convertCurrency = async (currrencyType) => {
try{
const res = await got("https://api.exchangerate-api.com/v4/latest/USD");
return (JSON.parse(res.body)['rates'][currrencyType]);
}
catch(err){
console.log(err);
}
}
async function search(){
try{
client.search({
index : '03776182',
body: {
aggs : {
price_ranges : {
range : {
field : "price",
script : {source : "convertCurrency(/EUR/) * _value"},
ranges : [
{ "from" : 10, "to" : 20 },
]
}
}
}
}
},(err,resp,status)=>{
err ? console.log(err): console.log(JSON.stringify(resp));
});
}
catch(err){console.log(err);}
}
我正在尝试在源字段中插入自定义脚本。但是它给出了以下错误。
response: `{"error":{"root_cause":[{"type":"script_exception","reason":"compile error","script_stack":["convertCurrency(/EUR/) * _value"," ^---- HERE"],"script":"convertCurrency(/EUR/) * _value","lang":"painless"}],"type":"search_phase_execution_exception","reason":"all shards failed","phase":"query","grouped":true,"failed_shards":[{"shard":0,"index":"03776182","node":"C4p_ha96QhK2uB47jV9pxg","reason":{"type":"script_exception","reason":"compile error","script_stack":["convertCurrency(/EUR/) * _value"," ^---- HERE"],"script":"convertCurrency(/EUR/) * _value","lang":"painless","caused_by":{"type":"illegal_state_exception","reason":"Regexes are disabled. Set [script.painless.regex.enabled] to [true] in elasticsearch.yaml to allow them. Be careful though, regexes break out of Painless's protection against deep recursion and long loops."}}}]},"status":500}`,
toString: [Function],
同时正常表达效果很好。
最佳答案
您不能从ES脚本调用JS回调,这没有意义,因为它们不在同一上下文中执行。
您应该做的是首先在Node.js代码中检索欧元汇率,然后将以该汇率作为参数的查询发送到脚本。
在伪代码中,它看起来像这样:
// 1. retrieve EUR/USD exchange rate
const EUR_USD = convertCurrency('EUR');
// 2. send your query
client.search({
index : '03776182',
body: {
aggs : {
price_ranges : {
range : {
field : "price",
script : {
source : "params.rate * _value"
params: {
rate: EUR_USD
}
},
ranges : [
{ "from" : 10, "to" : 20 },
]
}
}
}
}
关于javascript - 如何在带有Node.js的Elasticsearch中的聚合中使用自定义脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59193412/