[ElasticSearch]. 한국어 형태소 분석기 nori_analyzer 사용하기

jongmin-oh·2023년 5월 1일
0

엘라스틱 서치에서 사용하는 토크나이저를 파이썬 클라이언트로 연동해서 사용할 수 있다.
굳이 엘라스틱서치에서 작동되는걸 파이썬으로 가져와서 연동해야할 필요가 있을까 하지만
검색 결과로 나오는 BM25 score 말고 분리된 형태소 간 유사도를 파악하기 위해 사용했다.
*(0~1)로 치환되는 값이 필요함.

index Mapping 정보

"analysis": {
    "analyzer": {
        "nori_token_analyzer": {
            "type": "custom",
            "tokenizer": "nori_base_tokenizer"
        }
    },
    "tokenizer": {
        "nori_base_tokenizer": {
            "type": "nori_tokenizer",
            "decompound_mode": "mixed",
            "discard_punctuation": false
        }
    }
}

파이썬 클라이언트 연동

from elasticsearch import Elasticsearch
from config import ELASTIC_HOST

class ElasticSearch:
    def __init__(self):
        self.client = None

    def connect(self):
        self.client = Elasticsearch(hosts=ELASTIC_HOST)

    def close(self):
        self.client.close()


elastic = ElasticSearch()

형태소 분석기 함수 정의

def analyzer(question):
    if elastic.client == None:
        elastic.connect()
    res = elastic.client.indices.analyze(
        index=INDEX_NAME,
        analyzer="nori_token_analyzer",
        text=question,
        attributes=["leftPOS"],
        explain=True,
    )
    pos_tag = [
        (i["token"], i["leftPOS"])
        for i in res["detail"]["tokenizer"]["tokens"]
        if i["leftPOS"] != "SP(Space)"
    ]
    return pos_tag

테스트

print(analyzer("오늘 저녁 뭐먹을까 추천해줘~~"))

[('오늘', 'MAG(General Adverb)'),
('저녁', 'NNG(General Noun)'),
('뭐', 'IC(Interjection)'),
('먹', 'VV(Verb)'),
('을까', 'E(Verbal endings)'),
('추천', 'NNG(General Noun)'),
('해', 'XSV(Verb Suffix)'),
('줘', 'VX(Auxiliary Verb or Adjective)'),
('~~', 'SY(Other symbol)')]

profile
스타트업에서 자연어처리 챗봇을 연구하는 머신러닝 개발자입니다.

0개의 댓글