본문 바로가기

IT/AngularJS

AngularJS + ElasticSearch with elasticsearch.js

AngularJS 기반으로 ElasticSearch 서비스 호출하기.

ElasticSearch는 AngularJS, jQuery 기반의 javascript 라이브러리를 제공한다.


ElasticSearch 홈페이지 내 js 라이브러리 다운 페이지

https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/browser-builds.html


elasticsearch.angular.js를 활용한 셋업 관련 공식 예제코드

https://github.com/spalger/elasticsearch-angular-example/blob/master/index.html


ElasticSearch 홈페이지 내 Quick Start 가이드 페이지

https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/quick-start.html#quick-start



다음은 간략하게 구현한 AngularJS + ElasticSearch 코드


angular.module('SearchApp', ['elasticsearch'])
.service('client', function(esFactory) {
	return esFactory({
		host: 'localhost:9200',
		log: 'warning'
	});
})
.controller('SearchController', function($scope, client, esFactory) {
	
	$scope.documents = undefined;
	
	/*
	 * sending search request to elasticsearch
	 */
	$scope.procSearch = function() {
		if ( $scope.query === undefined || $scope.query.length <= 0 ) { return; }
		
		var result = client.search({
			index: 'test',
			size: 30,
			q: $scope.query
		})
		.then(function(result) {
			console.log(result.hits.hits.length + ' documents searched.');
			$scope.documents = result.hits.hits;
		}, function(error) {
			console.error(error);
			$scope.error = error;
		});
	};
})


그 외 ElasticSearch를 화면단에서 호출하다보니 CORS 관련하여 Access-Control-Allow-Origin 에러가 발생하는데,

이와 관련해서는 다음 포스트를 참고할 것: