Angular2 + Elasticsearch:从 Elasticsearch 服务器计算检索到的 JSON 数据时出现“未定义属性”错误
2017-07-18
515
我的目标是从 NG2-webapp 内正在运行的本地 ElasticSearch 服务器 检索示例数据,然后显示这些结果。
到目前为止,我已经使用
NPM Elasticsearch Typescript 包
创建了一个组件
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),因此这显然不起作用。看来我还不了解将对象转换为数组的复杂性?
2个回答
强烈建议不要直接从浏览器环境中使用 elastic API。
https://github.com/elastic/elasticsearch-js/issues/905#issuecomment-582932779
Ali
2020-02-10
一个可能的问题是您没有正确访问响应。请尝试类似
client.search({......
.............
.............
}).then(function(resp){
console.log("allTitles gefüllt: ", allTitles);
response.hits.hits.forEach(function(hit){
allTitles.push(hit.fields.firstname);
});
}, function(err){
console.log(err);
});
有关更多信息,请参阅 快速入门指南 。
ndon
2017-07-18