My goal is to retrieve sample data from a running local ElasticSearch Server inside my NG2-webapp, and then display those results.
So far, I have created a component test-es-types using the NPM Elasticsearch Typescript package.
This is the .ts code:
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 is running on localhost:9200 and returns the queried data as expected (according to console). However, when trying to put this data into an array (allTitles), I get the following console error:
Uncaught TypeError: Cannot read property 'firstname' of undefined
console.log tells me that allTitles is empty (length 0), so that obviously doesn't work. Seems like I do not yet understand the intricacies of transforming objects into arrays?