Javascript函数返回Elasticsearch结果 [英] Javascript function to return Elasticsearch results
问题描述
我正在尝试编写一个JavaScript函数,该函数返回Elasticsearch v5查询的结果.我不知道在哪里以及如何在此代码中包括返回".使用以下命令,segmentSearch(id)返回一个Promise对象, {_ 45:0,_81:0,_65:null,_54:null}
._65包含正确匹配的数组,但是我不知道如何解析它.console.log(hits)产生相同的数组,但是如何从函数中返回它呢?
I'm trying to write a JavaScript function that returns results of an Elasticsearch v5 query. I can't figure out where and how to include 'return' in this code. With the following, segmentSearch(id) returns a Promise object,{_45: 0, _81: 0, _65: null, _54: null}
.
_65 holds an array of the correct hits, but I can't figure out how to parse it. The console.log(hits) produces that same array, but how can I return it from the function?
var elasticsearch = require('elasticsearch');
var client = new elasticsearch.Client({
host: 'localhost:9200',
log: 'trace'
});
segmentSearch = function(id){
var searchParams = {
index: 'myIndex',
type: 'segment',
body: {
query: {
nested : {
path : "properties",
query : {
match : {"properties.source" : id }
},
inner_hits : {}
}
}
}
}
return client.search(searchParams).then(function (resp) {
var hits = resp.hits.hits;
console.log('hits: ',hits)
return hits;
}, function (err) {
console.trace(err.message);
});
}
推荐答案
我将在client.search函数之外在全局范围和array中实例化一个新数组.按"hits",然后访问新填充的数组.>
I would instanitate a new array outside of your client.search function in global scope and array.push your 'hits' Then access your newly filled array.
let newArr = [];
client.search(searchParams).then(function (resp) {
for(let i = 0; i < resp.hits.hits.length; i++){
newArr.push(resp.hits.hits[i]);
}
console.log('hits: ',newArr)
return newArr;
}, function (err) {
console.trace(err.message);
});
这篇关于Javascript函数返回Elasticsearch结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!