JSCODE Logo
프로그래밍 과외블로그후기멘토진
회사명 : JSCODE대표 : 박재성사업자 등록번호 : 244-22-01557통신판매업 : 제 2023-인천미추홀-0381 호
학원 명칭 : 제이에스코드(JSCODE)원격학원학원설립ㆍ운영 등록번호 : 제6063호

서울특별시 구로구 경인로 20가길 11(오류동, 아델리아)

Copyright ⓒ 2025 JSCODE - 최상위 현업 개발자들의 프로그래밍 교육 All rights reserved.

이용약관개인정보처리방침
← 블로그 목록으로 돌아가기

[실습] Spring Boot에서 인덱스에 맞게 Document 정의하기

JSCODE 박재성
JSCODE 박재성
2025-12-06
author
JSCODE 박재성
category
Elasticsearch
createdAt
Dec 6, 2025
series
실전에서 바로 써먹는 Elasticsearch 입문 (검색 최적화편)
slug
final-query-and-strategy
type
post
updatedAt
Dec 6, 2025 04:48 AM

✅ Spring Boot에서 인덱스에 맞게 Document 정의하기

Spring Data JPA에서 DB의 테이블에 맞게 Entity를 작성하는 것처럼, Spring Data Elasticsearch에서 인덱스에 맞게 Document를 작성해야 한다.
 
  1. Elasticsearch 의존성 설치
    1. build.gradle
      ... dependencies { implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'org.springframework.boot:spring-boot-starter-data-elasticsearch' developmentOnly 'org.springframework.boot:spring-boot-devtools' runtimeOnly 'com.mysql:mysql-connector-j' testImplementation 'org.springframework.boot:spring-boot-starter-test' testRuntimeOnly 'org.junit.platform:junit-platform-launcher' } ...
      notion image
       
  1. application.yml에 Elasticsearch 연결을 위한 정보 작성하기
    1. application.yml
      spring: datasource: url: jdbc:mysql://localhost:3306/coupang username: root password: password123 driver-class-name: com.mysql.cj.jdbc.Driver jpa: hibernate: ddl-auto: update show-sql: true elasticsearch: uris: http://localhost:9200 logging: level: org.elasticsearch.client: TRACE
       
  1. Document 생성하기
    1. Document 객체에 products 인덱스의 매핑(mapping) 정보를 반영해보자.
      ProductDocument
      @Document(indexName = "products") // products 인덱스 생성 @Setting(settingPath = "/elasticsearch/product-settings.json") public class ProductDocument { @Id private String id; @MultiField(mainField = @Field(type = FieldType.Text, analyzer = "products_name_analyzer"), otherFields = { @InnerField(suffix = "auto_complete", type = FieldType.Search_As_You_Type, analyzer = "nori") } ) private String name; @Field(type = FieldType.Text, analyzer = "products_description_analyzer") private String description; @Field(type = FieldType.Integer) private Integer price; @Field(type = FieldType.Double) private Double rating; @MultiField(mainField = @Field(type = FieldType.Text, analyzer = "products_category_analyzer"), otherFields = { @InnerField(suffix = "raw", type = FieldType.Keyword) } ) private String category; public ProductDocument(Long id, String name, String description, Integer price, Double rating, String category) { this.id = id; this.name = name; this.description = description; this.price = price; this.rating = rating; this.category = category; } // getter, setter 메서드 public String getName() { return name; } public void setName(String name) { this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Integer getPrice() { return price; } public void setPrice(Integer price) { this.price = price; } public Double getRating() { return rating; } public void setRating(Double rating) { this.rating = rating; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } }
       
  1. settings 파일 만들어주기
    1. json 형식의 파일로 만들어야 하기 때문에 주석을 전부 지운 채로 작성해야 한다. 그리고 앞쪽에 “settings” 필드 안의 값만 작성해야 한다. “mappings”에 대한 정보조차 적지 않는다. (”mappings" 정보는 Document 객체에 기입하기 때문에 적을 필요가 없다.)
      src/main/resources/elasticsearch/product-settings.json
      { "analysis": { "filter": { "product_synonyms": { "type": "synonym", "synonyms": [ "samsung, 삼성", "apple, 애플", "노트북, 랩탑, 컴퓨터, computer, laptop, notebook", "전화기, 휴대폰, 핸드폰, 스마트폰, 휴대전화, phone, smartphone, mobile phone, cell phone", "아이폰, iphone", "맥북, 맥, macbook, mac" ] } }, "analyzer": { "products_name_analyzer": { "char_filter": [], "tokenizer": "nori_tokenizer", "filter": [ "nori_part_of_speech", "nori_readingform", "lowercase", "product_synonyms" ] }, "products_description_analyzer": { "char_filter": ["html_strip"], "tokenizer": "nori_tokenizer", "filter": [ "nori_part_of_speech", "nori_readingform", "lowercase" ] }, "products_category_analyzer": { "char_filter": [], "tokenizer": "nori_tokenizer", "filter": [ "nori_part_of_speech", "nori_readingform", "lowercase" ] } } } }
 
  1. Elasticsearch Repository 생성하기
    1. ProductDocumentRepository
      public interface ProductDocumentRepository extends ElasticsearchRepository<ProductDocument, String> { }
      참고) 최소 1개 이상의 ElasticsearchRepository가 존재해야, Spring Boot를 실행시킬 때 Elasticsearch와 연결을 시도한다.
 
  1. 기존에 생성해둔 products 인덱스 삭제하기
    1. Kibana에서 아래 명령어를 실행시켜 인덱스를 삭제하자.
      DELETE /products // 인덱스 삭제 GET /products // 잘 삭제됐는 지 확인
       
  1. Spring Boot 프로젝트 실행시키기
    1. notion image
      위 로그가 찍혀있다면 Document 객체에 정의한 내용대로 index가 잘 생성됐다는 걸 알 수 있다.
       
  1. index 잘 생성됐는 지 kibana로 확인하기
    1. GET /products
       
author
JSCODE 박재성
category
Elasticsearch
createdAt
Dec 6, 2025
series
실전에서 바로 써먹는 Elasticsearch 입문 (검색 최적화편)
slug
type
series-footer
updatedAt
Dec 6, 2025 05:12 AM
📎
이 글은 실전에서 바로 써먹는 Elasticsearch 입문 (검색 최적화편) 강의의 수업 자료 중 일부입니다.