【问题标题】:Elasticsearch.js AngularJS autocompleteElasticsearch.js AngularJS 自动完成
【发布时间】:2016-05-03 17:47:42
【问题描述】:

我正在尝试使用 Elasticsearch、angularJS 和 bootstrap 实现自动完成功能。

我受到了这个解决方案的启发: autocomplete/typeahead angularjs bootstrap on elasticsearch

这是我的 Angular 代码:

angular.module('cineAngularApp')
     .service('client', function (esFactory) {
        return esFactory({
            host: 'localhost:9200',
            apiVersion: '2.2',
            log: 'trace'
        });
     });

 angular.module('cineAngularApp')
 .controller('AutocompleteCtrl', function ($scope,client) {

    $scope.getResult = function(val){

        return client.search({
            index: 'autocomplete_test',
            fields: 'city', 
            q: 'city:'+val
        }).then(function (resp) {
            var keywords = [];
            for(var i in resp.hits.hits){
                var fields = (resp.hits.hits[i]).fields["city"];
                keywords.push(fields);
            }
            return keywords;
        }, function (err) {
            console.trace(err.message);
        });
    };
 });

这是我的问题

当我使用简单查询时,上面的代码可以正常工作,但是一旦我通过添加 body 更改查询,它就不起作用了。

 angular.module('cineAngularApp')
 .controller('AutocompleteCtrl', function ($scope,client) {

    $scope.getResult = function(val){

        return client.search({
            index: 'autocomplete_test',
            fields: 'city', 
            body: {
                query: {
                    match: {
                        city: val
                    }
                }
            }
        }).then(function (resp) {
            var keywords = [];
            for(var i in resp.hits.hits){
                var fields = (resp.hits.hits[i]).fields["city"];
                keywords.push(fields);
            }
            return keywords;
        }, function (err) {
            console.trace(err.message);
        });
    };
 });

我不知道它是否有帮助,但我在调试时也注意到它不再是 POST 请求,而是一个 OPTION 请求。

提前感谢您的帮助。

【问题讨论】:

  • 在您的代码中,"query": "title:"+var 中有一个 sintax 错误。我不知道这是问题所在。你把它改成"query": "title"+val 试试看。
  • OPTIONS 请求是您的预检 CORS 请求。如果失败,您需要使用适当的 CORS 标头响应这些请求

标签: angularjs elasticsearch autocomplete elasticsearch.js


【解决方案1】:

试试这个:

return client.search({
    index: 'movies',
    "fields": [ "title" ], 
    "body": { // Use body field on elasticsearch client library
        "query": {
            "query_string": {
               "fields": ["title"],
               "query": "title:"+val
            }
        }
    }
}).then(function (resp) {
    // ....
})

【讨论】:

  • 我试过你的代码,但没有用。当我添加身体时,我根本没有结果。唯一适合我的查询是:return client.search({ index: 'movies', fields: 'title', q: 'title:'+val}).then(function (resp) { // .... })
猜你喜欢
  • 2014-07-04
  • 2014-08-20
  • 1970-01-01
  • 2017-09-10
  • 1970-01-01
  • 1970-01-01
  • 2013-08-29
  • 2015-02-26
  • 1970-01-01
相关资源
最近更新 更多