elasticsearch上的autocomplete / typeahead angularjs bootstrap

时间:2014-10-20 08:38:19

标签: angularjs twitter-bootstrap autocomplete elasticsearch

我一直在寻找一种有效的解决方案,以便在elasticsearch服务器上使用angularjs& bootstrap获得自动完成/预先输入。

1 个答案:

答案 0 :(得分:5)

这是一个有效的解决方案,不是问题,但我想分享它希望它会有所帮助:

调用自动完成功能的html代码:

 <input required type="text"
   popover-trigger="focus"
   placeholder="recherche globale"
   class="form-control"
   ng-model="simplequeryInput"
   ng-model-onblur focus-on="focusMe"
   ng-click="searchSimple=true" ng-keyup="$event.keyCode == 13 ? submitSimple() : null"
   typeahead="item for item in autocomplete($viewValue) | limitTo:15 "
   typeahead-on-select="simplequeryInput=$model"
 />
  • 包含elasticsearch(v2.4.0)脚本 可用here

  • 我的弹性搜索服务

    interfaceApp.service('elasticQuery', function ($rootScope,esFactory) {
      return esFactory({ host: $rootScope.elastic_host}); //'localhost:9200'
    });
    
  • angularjs code查询elasticsearch:

    'use strict';
    var searchModules = angular.module('searchModules', ['ngRoute','ngDialog']);
    searchModules.controller('searchCtrl', function (ngDialog,$scope, $http,$rootScope, elasticQuery) {
      ...
      $scope.autocomplete = function(val) {
        var keywords = [];
        keywords.push(val);
        // THIS RETURN IS VERY IMPORTANT 
        return elasticQuery.search({
          index: 'YOUR_INDEX_NAME',
          size: 15,
          body: {
            "fields" : ["T_FAMILY","T_GENUS","T_SCIENTIFICNAME"], // the fields you need
            "query" : {
            "bool" : {
              "must" : [
                {
                  "query_string" : {
                    "query" : "T_FAMILY:"+val // i want only source where FAMILY == val
                  }
                }
              ]
            }
            }
          }
        }).then(function (response) {
          for (var i in response.hits.hits) {
            var fields = (response.hits.hits[i]).fields;
            var tmpObject = fields["T_FAMILY"] +" " + fields["T_GENUS"] + " ( "+fields["T_SCIENTIFICNAME"] + " )";
            keywords.push(tmpObject);
          }
        return keywords;
        });
      }
    });
    

希望有所帮助