使用Elasticsearch和AngularJS构建一个小型搜索应用程序,几乎可以使用AngularJS Bootstrap typeahead进行自动完成工作,但是我无法显示ES返回的实际建议。
我有这个从ES
返回结果的承诺 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;
};
这是带有AngularJS UI Bootstrap东西的HTML
<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>
这是控制器中的getSuggestions函数
//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;
});
};
我在下拉列表中收到5条建议,但我没有获得实际价值......我得到的是这个,重复5次
[object Object]
我很确定它与此行有关
var phrases = es_return.hits.hits;
我的console.log输出此
[Object, Object, Object, Object, Object]
我不太确定如何在ES结果的_source
对象中访问“autocomplete_field”的值?
更新下拉菜单的模板为
<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>
更新2 ,此处为json响应示例
{
"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"
}
}
}
}
答案 0 :(得分:0)
在看到JSON的结构后,我可以告诉您需要将uib-typeahead
属性更改为:
uib-typeahead="query as query._source.autocomplete_field for query in getSuggestions($viewValue)"