我的目标是从NG2-webapp中正在运行的本地 ElasticSearch Server 中检索样本数据,然后显示这些结果。
到目前为止,我已使用NPM Elasticsearch Typescript package创建了一个组件test-es-types
。
这是.ts
代码:
import { Component, OnInit } from '@angular/core';
import * as elasticsearch from 'elasticsearch';
@Component({
selector: 'app-test-es-types',
templateUrl: './test-es-types.component.html',
styleUrls: ['./test-es-types.component.scss']
})
export class TestEsTypesComponent implements OnInit {
constructor() { }
ngOnInit() {
// Setting up Elasticsearch Client
var client = new elasticsearch.Client({
host: 'http://localhost:9200',
log: 'trace'
});
console.log("Client:", client);
// Elasticsearch Server Ping
client.ping({
// ping usually has a 3000ms timeout
requestTimeout: 1000
}, function (error) {
if (error) {
console.trace('elasticsearch cluster is down!');
} else {
console.log('All is well');
}
});
// first we do a search, and specify a scroll timeout
var allTitles: string[] = [];
console.log("Erzeuge allTitles Array...");
client.search({
index: 'bank',
// Set to 30 seconds because we are calling right back
scroll: '30s',
searchType: 'query_then_fetch',
docvalueFields: [''],
q: 'Avenue'
}, function getMoreUntilDone(error, response) {
// collect the first name from each response
console.log("allTitles gefüllt: ", allTitles);
response.hits.hits.forEach(function (hit) {
allTitles.push(hit.fields.firstname);
});
if (response.hits.total !== allTitles.length) {
// now we can call scroll over and over
client.scroll({
scrollId: response._scroll_id,
scroll: '30s'
}, getMoreUntilDone);
} else {
console.log('every "test" title', allTitles);
}
});
}
}
ES-server在localhost:9200上运行,并按预期返回查询的数据(根据控制台)。但是,当尝试将此数据放入数组(allTitles)时,我收到以下控制台错误:
Uncaught TypeError: Cannot read property 'firstname' of undefined
console.log告诉我allTitles是空的(长度为0),所以显然不起作用。好像我还不了解将对象转换为数组的复杂性?
答案 0 :(得分:1)
强烈建议不要直接从浏览器环境中使用弹性API。
https://github.com/elastic/elasticsearch-js/issues/905#issuecomment-582932779
答案 1 :(得分:0)
一个可能的问题是您没有正确访问响应。尝试像
这样的东西var data = [5,4,3,2,1];
for(var i = 0; i < data.length;) {
if(data[i]>data[i+1]) {
var temp = data[i];
data[i] = data[i+1];
data[i+1] = temp;
i = 0;
}else{
i++;
}
console.log(data);
}
以下是quickstart guide以获取更多信息。