我正在使用elasticsearch客户端使用constant_score和aggregations进行一些搜索查询,但它抛出异常:
[parsing_exception] [constant_score] malformed query, expected [END_OBJECT] but found [FIELD_NAME]
这是我创建查询并调用搜索功能的地方:
fetchData: function fetchFn(req, res, next) {
var model = new urlModel();
util.log('Fetching data from ES::');
var query = buildAggregateUrl(req.reqData);
// if (req.reqData['domain']) {
// var termFilter = { "term": { "domain": req.reqData.domain } };
// query.constant_score.filter.bool.must.push(termFilter);
// }
model.search({ query }, function (er, re) {
if (re) {
req.sendResult = re;
}
next(er);
});
function buildAggregateUrl(opts) {
var query = {
constant_score: {
filter: {
bool: {
must: [{
"range": {
"timestamp": {
"gte": opts.startTime,
"lte": opts.endTime
}
}
}]
}
}
},
aggs: {
success: {
scripted_metric: {
init_script: "params._agg.succ=0;",
map_script: "if(doc.status.value=='success'){params._agg.succ+=1}",
combine_script: "return params._agg.succ",
reduce_script: "int sum=0;for (a in params._aggs){sum+=a}return sum"
}
},
failure: {
scripted_metric: {
init_script: "params._agg.fail=0;",
map_script: "if(doc.status.value=='failure'){params._agg.fail+=1}",
combine_script: "return params._agg.fail",
reduce_script: "int sum=0;for (a in params._aggs){sum+=a}return sum"
}
}
}
};
return query;
}
}
And this is what the search function looks like:
es_model.prototype.search = function (opts, cb) {
var query = {
index: this.esConfig.index,
type: this.esConfig.type,
body: {query:opts.query}
};
console.log('Query ===> ',query);
this.client.search(query, cb);
}
我无法弄清楚语法问题在哪里。我尝试用withtin查询包装constant_score键但它似乎不起作用。
答案 0 :(得分:2)
您只是错过了顶层的query
元素:
{
query: {
constant_score: {
filter: {
bool: {
must: [{
"range": {
"timestamp": {
"gte": opts.startTime,
"lte": opts.endTime
}
}
}]
}
}
}
},
aggs: {
success: {
scripted_metric: {
init_script: "params._agg.succ=0;",
map_script: "if(doc.status.value=='success'){params._agg.succ+=1}",
combine_script: "return params._agg.succ",
reduce_script: "int sum=0;for (a in params._aggs){sum+=a}return sum"
}
},
failure: {
scripted_metric: {
init_script: "params._agg.fail=0;",
map_script: "if(doc.status.value=='failure'){params._agg.fail+=1}",
combine_script: "return params._agg.fail",
reduce_script: "int sum=0;for (a in params._aggs){sum+=a}return sum"
}
}
}
}
另请注意,您的客户端代码应如下所示:
es_model.prototype.search = function (opts, cb) {
var query = {
index: this.esConfig.index,
type: this.esConfig.type,
body: opts.query
};
this.client.search(query, cb);
}