Samaung Notebook이라는 상품이 있다고 가정하자. 사람들은 검색할 때notebook이라고 정확하게 검색할 수도 있지만,노트북,랩탑,휴대용 컴퓨터,laptop과 같이 동의어로 검색할 수도 있다. 그리고samsung이라고 검색할 수도 있지만삼성이라고 검색할 수도 있다. 이렇게 동의어로 검색하더라도Samsung notebook이 나오게 하려면 어떻게 셋팅해야 하는 지 알아보자.
// 기존 인덱스 삭제 DELETE /products // 인덱스 생성 + 매핑 정의 + Custom Analyzer 적용 PUT /products { "settings": { "analysis": { "filter": { "products_synonym_filter": { "type": "synonym", "synonyms": [ "notebook, 노트북, 랩탑, 휴대용 컴퓨터, laptop", "samsung, 삼성" ] } }, "analyzer": { "products_name_analyzer": { "char_filter": [], "tokenizer": "standard", "filter": [ "lowercase", "products_synonym_filter" ] } } } }, "mappings": { "properties": { "name": { "type": "text", "analyzer": "products_name_analyzer" } } } } // 잘 생성됐는 지 확인 GET /products
POST /products/_doc { "name": "Samsung Notebook" }
GET /products/_search { "query": { "match": { "name": "노트북" } } } GET /products/_search { "query": { "match": { "name": "랩탑" } } } GET /products/_search { "query": { "match": { "name": "휴대용 컴퓨터" } } } GET /products/_search { "query": { "match": { "name": "laptop" } } } GET /products/_search { "query": { "match": { "name": "삼성" } } }
synonym 설정 덕분에 위 쿼리로 검색해보면 데이터가 잘 조회된다. 왜 잘 조회가 된 건지 Analyze API를 활용해 디버깅해보자. GET /products/_analyze { "field": "name", "text": "Samsung Notebook" }
{ "tokens": [ { "token": "samsung", "start_offset": 0, "end_offset": 7, "type": "<ALPHANUM>", "position": 0 }, { "token": "삼성", "start_offset": 0, "end_offset": 7, "type": "SYNONYM", "position": 0 }, { "token": "notebook", "start_offset": 8, "end_offset": 16, "type": "<ALPHANUM>", "position": 1 }, { "token": "노트북", "start_offset": 8, "end_offset": 16, "type": "SYNONYM", "position": 1 }, { "token": "랩탑", "start_offset": 8, "end_offset": 16, "type": "SYNONYM", "position": 1 }, { "token": "휴대용", "start_offset": 8, "end_offset": 16, "type": "SYNONYM", "position": 1 }, { "token": "laptop", "start_offset": 8, "end_offset": 16, "type": "SYNONYM", "position": 1 }, { "token": "컴퓨터", "start_offset": 8, "end_offset": 16, "type": "SYNONYM", "position": 2 } ] }
synonym을 활용하면 된다.