【发布时间】:2016-07-06 03:49:19
【问题描述】:
使用 Elasticsearch 和 AngularJS 构建一个小型搜索应用程序,使用 AngularJS Bootstrap 预输入几乎可以自动完成,但我无法显示 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" 的值?
UPDATE下拉菜单的模板是
<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,这里是一个示例 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"
}
}
}
}
【问题讨论】:
-
你的模板是什么样的?
-
可能应该是
uib-typeahead="query as query.title for query in getSuggestions($viewValue)"(title应该是显示属性,但是由于您没有提供 JSON,所以我只能猜测正确的属性名称) -
@MikeRobinson 抱歉耽搁了,请看上面的更新,有下拉模板
-
@AlonEitan 抱歉耽搁了,在上面的 UPDATE 2 中添加了 JSON,谢谢
-
@user3125823 试试
uib-typeahead="query as query._source.autocomplete_field for query in getSuggestions($viewValue)"
标签: javascript angularjs twitter-bootstrap