Currently working on a small search application that utilizes Elasticsearch and AngularJS. I have made progress in implementing autocomplete functionality using the AngularJS Bootstrap typeahead feature. However, I am encountering difficulties in displaying the actual suggestions returned by Elasticsearch.
I have a function that retrieves results from Elasticsearch as a promise:
this.getSuggestions = function(query) {
var deferred = $q.defer();
esClient.search({
index: 'autocomplete',
body: {
"query": {
"match_phrase_prefix": {
"autocomplete_field": {
"query": query,
"max_expansions": 10
}
}
},
"size": 5,
"from": 0,
"_source": ["autocomplete_field"]
}
}).then(function(es_return) {
deferred.resolve(es_return);
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
};
Below is the HTML code utilizing AngularJS UI Bootstrap:
<input type="text" name="q" ng-model="searchTerms" placeholder="Search" class="form-control input-lg" uib-typeahead="query for query in getSuggestions($viewValue)" typeahead-on-select="search($item)" typeahead-popup-template-url="customPopupTemplate.html" auto-focus>
The corresponding getSuggestions function in the controller looks like this:
//get suggestions
$scope.getSuggestions = function(query) {
$scope.isSearching = true;
return searchService.getSuggestions(query).then(function(es_return){
var phrases = es_return.hits.hits;
console.log(phrases);
if (phrases) {
return $scope.autocomplete.suggestions = phrases;
};
$scope.isSearching = false;
});
};
When testing, I'm seeing 5 suggestions displayed in the dropdown menu but they all appear as [object Object]. This seems to be related to the line:
var phrases = es_return.hits.hits;
The console output shows:
[Object, Object, Object, Object, Object]
I need assistance in properly accessing the value of "autocomplete_field" within the _source object of the Elasticsearch results.
UPDATE The template used for the dropdown menu is:
<ul class="dropdown-menu" role="listbox">
<li ng-repeat="match in matches track by $index" ng-class="{active: isActive($index) }"
ng-mouseenter="selectActive($index)" ng-click="selectMatch($index)" role="option" id="{{::match.id}}">
<div uib-typeahead-match index="$index" match="match" query="query" template-url="templateUrl"></div>
</li>
</ul>
UPDATE 2 Here's an example JSON response:
{
"took": 5,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"failed": 0
},
"hits": {
"total": 3,
"max_score": 2.5897822,
"hits": [
{
"_index": "autocomplete",
"_type": "suggestions",
"_id": "229",
"_score": 2.5897822,
"_source": {
"autocomplete_field": "fast and furious"
}
},
{
"_index": "autocomplete",
"_type": "suggestions",
"_id": "230",
"_score": 2.5897822,
"_source": {
"autocomplete_field": "die hard"
}
},
{
"_index": "autocomplete",
"_type": "suggestions",
"_id": "107",
"_score": 1.7686365,
"_source": {
"autocomplete_field": "the bourne identity"
}
}
}
}