SpringBoot + ElasticSearch 연동 및 간단 API 호출해보기

반응형
728x90
반응형

ElasticSearch 설치

Docker + Elasticsearch 설정하는 이전 포스팅을 참고하자.

devfunny.tistory.com/365

 

Docker Centos7에 ElasticSearch + Kibana 설치하여 외부 로컬에서 접속하기 (with Docker Hub)

들어가기전 docker에 centos7을 설치 후, 해당 컨테이너를 실행하고 그 안에 Elasticsearch와 Kibana를 설치하여 localhost:5601로 kibana를 띄어볼 것이다. 이를 위한 순서는 아래와 같다. 1) Centos 설치 2) JDK..

devfunny.tistory.com

 

 

설정파일 생성

  • 1) build.gradle Import
/* elasticsearch */
compile 'org.springframework.boot:spring-boot-starter-data-elasticsearch'
compile 'org.elasticsearch.client:elasticsearch-rest-high-level-client:7.9.1'
compile 'org.elasticsearch.client:elasticsearch-rest-client:7.9.3'
compile 'org.elasticsearch:elasticsearch:7.9.3'

 

  • 2) application.yml 파일에 elasticsearch 설정 추가하기
elasticsearch:
  host: 127.0.0.1
  port: 9200

 

  • 3) ElkConfig.java 파일 생성하기
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.RestClients;
import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;

@Configuration
@Slf4j
public class ElkConfig extends AbstractElasticsearchConfiguration {

    @Value("${elasticsearch.host}")
    private String host;

    @Value("${elasticsearch.port}")
    private int port;

    @Override
    @Bean
    public RestHighLevelClient elasticsearchClient() {
        final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
                .connectedTo(host + ":" + port)
                .build();

        return RestClients.create(clientConfiguration).rest();
    }

    @Bean
    public ElasticsearchOperations elasticsearchOperations() {
        return new ElasticsearchRestTemplate(elasticsearchClient());
    }

}

 

 

  • 4) ReservationIndex.java 생성하기
import lombok.Builder;
import lombok.Data;
import org.elasticsearch.common.geo.GeoPoint;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.*;

@Data
@Document(indexName = "reservation")
@Setting(settingPath = "elastic-setting.json")
public class ReservationIndex {
    /* id */
    @Id
    @Field(type = FieldType.Long)
    private int reservationId;

    /* 서비스구분 */
    @Field(type = FieldType.Keyword)
    private String type;

    /* 서비스ID */
    @Field(type = FieldType.Keyword)
    private String serviceId;

    /* 장소 X 좌표, Y 좌 */
    @GeoPointField
    private GeoPoint location; // X, Y

    /* 서비스개시시작일시 */
    @Field(type = FieldType.Date)
    private String startDate;
}

 

이 파일에서 @Setting(settingPath = "elastic-setting.json") 이 부분은 프로젝트 resource/** 경로의 파일을 찾는다. 해당 파일에 사용할 분석기, 필터 등을 설정하면 인덱스 생성시에 적용된다.

 

 

Elasticsearch API 호출

아래 메서드들을 호출할 파일에 클래스를 주입한다.

@RequiredArgsConstructor
public class ElkService {
    private final ElasticsearchOperations elasticsearchOperations;
    private final ElasticSearchClient elasticSearchClient;
    
    ...
}

 

  • 1) 인덱스 생성
/**
* create Index (reservation)
* @return
*/
public String createIndex() {
  	IndexCoordinates indexCoordinates = elasticsearchOperations.getIndexCoordinatesFor(ReservationIndex.class);
  	IndexQuery indexQuery = new IndexQueryBuilder()
                              .withId(UUID.randomUUID().toString())
                              .withObject(new ReservationIndex())
                              .build();

	return elasticsearchOperations.index(indexQuery, indexCoordinates);
}

 

  • 2) Document insert
/**
* insert 문서
* @param reservationIndexList
* @return
*/
public List<ReservationIndex> insertDocument(List<ReservationIndex> reservationIndexList) {
	return (List<ReservationIndex>) elasticsearchOperations.save(reservationIndexList);
}

 

 

반응형

Designed by JB FACTORY