gpt4 book ai didi

javascript - AngularJs 自动完成几乎可以工作

转载 作者:行者123 更新时间:2023-11-28 05:49:48 25 4
gpt4 key购买 nike

使用 Elasticsearch 和 AngularJS 构建一个小型搜索应用程序,几乎可以使用 AngularJS 进行自动完成工作。 Bootstrap typeahead,但我无法显示 ES 返回的实际建议。

我有一个从 ES 返回结果的 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;
};

这是带有 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>

这是 Controller 中的 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"
}
}
}
}

最佳答案

查看 JSON 的结构后,我可以看出您需要将 uib-typeahead 属性更改为:

uib-typeahead="query as query._source.autocomplete_field for query in getSuggestions($viewValue)"

关于javascript - AngularJs 自动完成几乎可以工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38165032/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com