<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">
  <channel>
    <title><![CDATA[쿼리 언어 - Elasticsearch Labs]]></title>
    <description><![CDATA[Articles and tutorials from the Search team at Elastic]]></description>
    <copyright><![CDATA[© 2026. Elasticsearch B.V. All Rights Reserved]]></copyright>
    <image>
      <title><![CDATA[쿼리 언어 - Elasticsearch Labs]]></title>
      <url>https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt1121c0bf0e8a6e65/6a88da6340a1841030ef456f/search-labs-thumbnail.png</url>
      <link>https://www.elastic.co/kr/search-labs/blog/category/query-languages</link>
    </image>
    <link>https://www.elastic.co/kr/search-labs/blog/category/query-languages</link>
    <atom:link href="https://www.elastic.co/kr/search-labs/rss/category/query-languages.xml" rel="self" type="application/rss+xml"/>
    <language><![CDATA[kr]]></language>
    <lastBuildDate>Tue, 29 Sep 2026 09:34:11 GMT</lastBuildDate>
  <item>
    <title><![CDATA[Elasticsearch를 사용한 어휘 및 시맨틱 검색]]></title>
    <description><![CDATA[이 블로그에서는 어휘 및 시맨틱 검색을 중심으로 Elasticsearch를 사용해 정보를 검색하는 다양한 접근 방식을 살펴보겠습니다.]]></description>
    <content:encoded><![CDATA[<p>검색은 검색어 또는 복합 검색어를 기반으로 가장 관련성이 높은 정보를 찾는 과정이며, 관련 검색 결과는 이러한 검색어와 가장 잘 일치하는 문서입니다. 검색과 관련된 여러 가지 과제와 방법이 있지만, <strong>질문에 대한 최상의 답변을 찾는다는</strong> 궁극적인 목표는 동일합니다.</p><p>이 목표를 고려하여 이 블로그 게시물에서는 텍스트 검색에 특히 초점을 맞춘 <strong>어휘 검색과 의미론적 검색을</strong>중심으로 Elasticsearch를 사용하여 정보를 검색하는 다양한 접근 방식을 살펴보겠습니다.</p><h2>필수 구성 요소</h2><p>이를 위해 이커머스 상품 정보를 시뮬레이션하기 위해 생성된 <a href="https://github.com/elastic/elasticsearch-labs/blob/main/supporting-blog-content/lexical-and-semantic-search-with-elasticsearch/products-ecommerce.json">데이터 세트에</a> 대한 다양한 검색 시나리오를 보여주는 Python 예제를 제공합니다.</p><p>이 데이터 세트에는 각각 설명이 포함된 2,500개 이상의 제품이 포함되어 있습니다. 이러한 제품은 아래와 같이 76개의 개별 제품 카테고리로 분류되며, 각 카테고리에는 다양한 수의 제품이 포함되어 있습니다:</p><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt34415151c00ced2b/6a17d8710b0bed6c9bdd342c/4104466050f3024b6bcaf382da2a702650f62227-1440x708.png" alt="" /><p><em>트리맵 시각화 - category.keyword(제품 카테고리)의 상위 22개 값</em></p><p>설정에는 다음이 필요합니다:</p><ul><li><p>Python 3.6 이상</p></li><li><p><a href="https://www.elastic.co/guide/en/elasticsearch/client/python-api/current/index.html">Elastic Python 클라이언트</a></p></li><li><p>Elastic 8.8 이상 배포, 8GB 메모리 머신 러닝 노드 사용</p></li><li><p>Elastic에 사전 로드되어 배포에 설치 및 시작되는 <a href="https://www.elastic.co/guide/en/machine-learning/8.9/ml-nlp-elser.html">Elastic 학습된 Sparse EncodeR</a> 모델</p></li></ul><p>저희는 Elastic Cloud를 사용할 예정이며, <a href="https://cloud.elastic.co/registration?onboarding_token=vectorsearch&amp;cta=cloud-registration&amp;tech=trial&amp;plcmt=article%20content&amp;pg=search-labs">무료 체험판을 사용할 수</a> 있습니다.</p><p>이 블로그 게시물에 제공된 검색어 외에도 <a href="https://github.com/elastic/elasticsearch-labs/blob/main/supporting-blog-content/lexical-and-semantic-search-with-elasticsearch/ecommerce_dense_sparse_project.ipynb">Python 노트북에서</a> 다음 프로세스를 안내해 드립니다:</p><ul><li><p>Python 클라이언트를 사용하여 Elastic 배포에 연결 설정하기</p></li><li><p>텍스트 임베딩 모델을 Elasticsearch 클러스터에 로드합니다.</p></li><li><p>피처 벡터와 고밀도 벡터를 인덱싱하기 위한 매핑으로 인덱스를 생성합니다.</p></li><li><p>텍스트 삽입 및 텍스트 확장을 위한 추론 프로세서가 포함된 수집 파이프라인 만들기</p></li></ul><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt0e95406ece8f08d9/6a17d8731d1b83d32e93e2f4/54a9a490a3b0cf1b9c2228bee8eddd3f566bd435-1418x1102.png" alt="" /><h2>어휘 검색 - 희소 검색</h2><p>텍스트 쿼리를 기반으로 Elasticsearch에서 문서의 관련성 순위를 매기는 고전적인 방식은 <strong>어휘 검색을 위한</strong> 희소 모델 <a href="https://en.wikipedia.org/wiki/Okapi_BM25">인 BM25 모델의</a> Lucene 구현을 사용합니다. 이 방법은 텍스트 검색의 전통적인 접근 방식을 따르며, 정확한 용어 일치 항목을 찾습니다.</p><p>이 검색을 가능하게 하기 위해 Elasticsearch는 텍스트 분석을 수행하여 <strong>텍스트 필드</strong> 데이터를 검색 가능한 형식으로 변환합니다.</p><p><strong>텍스트 분석</strong> 은 검색을 위해 관련 토큰을 추출하는 프로세스를 관리하는 일련의 규칙인<a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/analyzer-anatomy.html"> 분석기에</a> 의해 수행됩니다. 분석기에는<a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-tokenizers.html"> 토큰라이저가</a> 정확히 하나만 있어야 합니다. 토큰화 도구는 아래 예시와 같이 문자 스트림을 수신하여 개별 토큰(일반적으로 개별 단어)으로 분할합니다:</p><h3>어휘 검색을 위한 문자열 토큰화</h3>#Performs text analysis on a string and returns the resulting tokens.

# Define the text to be analyzed
text = "Comfortable furniture for a large balcony"

# Define the analyze request
request_body = {
  "analyzer": "standard",
  "text": text
}

# Perform the analyze request
response = client.indices.analyze(analyzer=request_body["analyzer"], text=request_body["text"])

# Extract and display the analyzed tokens
tokens = [token["token"] for token in response["tokens"]]
print("Analyzed Tokens:", tokens)
<p>출력</p>Analyzed Tokens: ['comfortable', 'furniture', 'for', 'a', 'large', 'balcony']
<p>이 예에서는 영어 문법 기반 토큰화를 제공하기 때문에 대부분의 사용 사례에서 잘 작동하는 기본 분석기인 <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-standard-analyzer.html">표준</a> 분석기를 사용하고 있습니다. 토큰화를 통해 개별 조건에 따른 매칭이 가능하지만, 각 토큰은 여전히 문자 그대로 매칭됩니다.</p><p>검색 환경을 맞춤 설정하고 싶다면 다른<a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-analyzers.html"> 기본 제공 분석기를</a> 선택할 수 있습니다. 예를 들어, <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-stop-analyzer.html">중지 분석기를</a> 사용하도록 코드를 업데이트하면 중지 단어 제거를 지원하여 문자가 아닌 모든 문자에서 텍스트를 토큰으로 분리할 수 있습니다.</p>...
# Define the analyze request
request_body = {
  "analyzer": "stop",
  "text": text
}
...
<p>출력</p>Analyzed Tokens: ['comfortable', 'furniture', 'large', 'balcony']
<p><a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-custom-analyzer.html">기본</a> <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-charfilters.html">제공</a> 분석기가 사용자의 요구 사항을 충족하지 못하는 경우, 0개 이상의 문자 필터,<a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-tokenizers.html">토큰화</a> 도구 및 0개 이상의 <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-tokenfilters.html">토큰 필터를 적절히 조합하여 사용자 지정</a> 분석기를 만들 수 있습니다.</p>"analyzer":  {

  "my_analyzer": {

    "type": "custom", #For custom analyzers, use a type of custom or omit the type parameter.

    "tokenizer": "standard", #Built-in or customized tokenizer

    "filter": ["lowercase", "synonym"] #Built-in or customized token filters
  }
}
<p>토큰화기와 토큰 필터를 결합한 위의 예에서 텍스트는 <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-synonym-tokenfilter.html#:~:text=Elasticsearch%20will%20use%20the%20token,applied%20to%20the%20synonym%20entries.">동의어 토큰</a> <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-lowercase-tokenfilter.html">필터에</a> 의해 처리되기 전에 소문자 필터에 의해 소문자로 처리됩니다.</p><h2>어휘 일치</h2><p><a href="https://www.elastic.co/blog/practical-bm25-part-2-the-bm25-algorithm-and-its-variables">BM25는</a> 용어의 빈도와 중요도에 따라 주어진 검색 쿼리에 대한 문서의 관련성을 측정합니다.</p><p>아래 코드는 <em>"전자상거래 검색"</em> 인덱스의 "설명" 필드 값과 검색 쿼리를 고려하여 최대 2개의 문서를 <em>검색하는</em> <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-match-query.html">일치</a> 쿼리를 수행합니다.<strong>"</strong><em><strong>넓은 발코니를 위한 편안한 가구 ".</strong></em></p><p>이 쿼리와 일치하는 문서로 간주되는 기준을 세분화하면 정확도를 높일 수 있습니다. 그러나 보다 구체적인 결과를 얻으려면 변형에 대한 허용 오차가 낮아지는 대가가 따릅니다.</p># BM25

response = client.search(size=2,
index="ecommerce-search",
query= {
  "match": {
    "description" : {  
      "query": "Comfortable furniture for a large balcony",
      "analyzer": "stop"
    }
  }
}
)

hits = response['hits']['hits']

if not hits:
  print("No matches found")

else:
  for hit in hits:
    score = hit['_score']
    product = hit['_source']['product']
    category = hit['_source']['category']
    description = hit['_source']['description']
    print(f"\nScore: {score}\nProduct: {product}\nCategory: {category}\nDescription: {description}\n")
<p>출력</p>Score: 15.607948
Product: Barbie Dreamhouse
Category: Toys
Description: is a classic Barbie playset with multiple rooms, furniture, a large balcony, a pool, and accessories. It allows kids to create their dream Barbie world.

Score: 9.137739
Product: Comfortable Rocking Chair
Category: Indoor Furniture
Description: enjoy relaxing moments with this comfortable rocking chair. Its smooth motion and cushioned seat make it an ideal piece of furniture for unwinding.
<p>결과물을 분석한 결과, 가장 연관성이 높은 결과는 "<em>장난감 " 카테고리의</em>" 바비 드림하우스 " 제품이며,<em>설명에 "</em><em>가구</em>", " 대형" 및 <em>"발코니</em>" 라는 용어가 포함되어 있어 연관성이 높으며, 이 제품은 설명에 검색어와 일치하는 3개의 용어가 포함된 유일한 제품이며, 설명에 <em>"발코니"</em> 라는 용어가 포함된 유일한 제품이기도 합니다.</p><p>두 번째로 관련성이 높은 제품은 "<em>실내 가구</em>" 로 분류된<em>" 편안한 흔들</em>의자 " 이며 설명에 "<em>편안한</em>" 및 "<em>가구 " 라는</em>용어가 포함되어 있습니다. 데이터 세트에서 이 검색 쿼리의 2개 이상의 용어와 일치하는 제품은 3개뿐이며, 이 제품은 그 중 하나입니다.</p><p><em>"105개 제품의 설명에는 '</em> 편안함" '이, 4개 카테고리의 4개 제품 설명에는 ' <em>"가구"</em> '가 표시됩니다: <em>장난감</em>, <em>실내 가구, 실외 가구 및 '개 및 고양이 용품 &amp; 장난감'.</em></p><p>보시다시피, 검색어와 가장 연관성이 높은 제품은 장난감이고 두 번째로 연관성이 높은 제품은 실내 가구입니다. 이러한 문서가 일치하는 이유를 알 수 있도록 점수 계산에 대한 자세한 정보를 원한다면 <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-explain.html"><em>explain</em></a> __query 매개 변수를 true로 설정하면 됩니다.</p><p>두 결과 모두 가장 관련성이 높은 결과이지만, 이 데이터 세트의 문서 수와 용어 발생을 모두 고려할 때 "<em>넓은 발코니에 어울리는 편안한 가구</em>" 쿼리의 의도는 장난감과 실내 가구를 제외한 실제 넓은 발코니에 어울리는 가구를 검색하는 것입니다.</p><p>어휘 검색은 비교적 <strong>간단하고 빠르지만</strong>, 사용자의 의도와 쿼리를 알지 못하면 가능한 모든 용어와 동의어를 알 수 없기 때문에 한계가 있습니다. 자연어 사용에서 흔히 볼 수 있는 현상은 <strong>어휘 불일치입니다</strong>. <a href="https://dl.acm.org/doi/abs/10.1145/32206.32212">연구에</a> 따르면, 같은 분야의 전문가들이 같은 사물의 이름을 다르게 지을 확률은 평균적으로 <strong>80% %에</strong> 달한다고 합니다.</p><p>이러한 한계로 인해 의미론적 지식을 통합하는 다른 채점 모델을 찾게 되었습니다. 자연어처럼 순차적인 입력 토큰을 처리하는 데 탁월한 트랜스포머 기반 모델은 문서와 쿼리의 수학적 표현을 모두 고려하여 검색의 기본 의미를 포착합니다. 이를 통해 문맥을 인식하는 조밀한 텍스트 벡터 표현이 가능해져 관련 콘텐츠를 찾는 정교한 방법인 <strong>시맨틱 검색을</strong> 강화할 수 있습니다.</p><h2>시맨틱 검색 - 고밀도 검색</h2><p>이러한 맥락에서 데이터를 의미 있는 벡터 값으로 변환한 후, 데이터 집합에서 쿼리 벡터와 가장 유사한 벡터 표현을 찾기 위해 <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/knn-search.html">k-최근접 이웃(kNN)</a> 검색 알고리즘을 사용합니다. Elasticsearch는 kNN 검색을 위해 두 가지 방법, 즉 <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/knn-search.html#exact-knn">정확한 무차별 kNN과</a> ANN이라고도 하는 <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/knn-search.html#approximate-knn">대략적인 kNN을</a> 지원합니다.</p><p>무차별 대입 방식은 정확한 결과를 보장하지만 대규모 데이터 세트에는 잘 확장되지 않습니다. 근사 kNN은 성능 향상을 위해 정확도를 일부 희생하여 가장 가까운 이웃을 효율적으로 찾습니다.</p><p>kNN 검색과 고밀도 벡터 인덱스에 대한 Lucene의 지원을 통해 Elasticsearch는 다양한 <a href="http://ann-benchmarks.com/">앤 벤치마크 데이터 세트에서</a> 강력한 검색 성능을 보여주는 계층적 탐색 가능한 작은 세계(HNSW) 알고리즘을 활용할 수 있습니다. 아래 예제 코드를 사용하여 Python에서 대략적인 kNN 검색을 수행할 수 있습니다.</p><h3>대략적인 kNN을 사용한 시맨틱 검색</h3># KNN - approximate kNN

response = client.search(index='ecommerce-search', size=2,
knn={
  "field": "description_vector.predicted_value",
  "k": 50, # Number of nearest neighbors to return as top hits.
#The optimal value of k is dependent on the data. It can vary in different scenarios.

  "num_candidates": 500, # Number of nearest neighbor candidates to consider per shard.

#Increasing num_candidates tends to improve the accuracy of the final k results.

  "query_vector_builder": { # Object indicating how to build a query_vector. kNN search enables you to perform semantic search by using a previously deployed text embedding model, the steps for this process are demonstrated in the Python notebook.
    "text_embedding": { 
      "model_id": "sentence-transformers__all-mpnet-base-v2", # Text embedding model id
      "model_text": "Comfortable furniture for a large balcony" # Query
    }
  }
}
)

for hit in response['hits']['hits']:
        
  score = hit['_score']
  product = hit['_source']['product']
  category = hit['_source']['category']
  description = hit['_source']['description']
  print(f"\nScore: {score}\nProduct: {product}\nCategory: {category}\nDescription: {description}\n")
<p>이 코드 블록은 제품 데이터 세트의 " description" 필드가 포함된 것을 고려하여<em>Elasticsearch의 kNN을</em><em>사용하여 " 큰 발코니를 위한 편안한 가구 "</em> 의 벡터화된 쿼리(query_vector_build)와 유사한 설명을 가진 최대 두 개의 제품을 반환합니다.</p><p>제품 임베딩은 이전에 추론 프로세서가 포함된 수집 파이프라인에서 생성되었습니다. <em>"</em><a href="https://huggingface.co/sentence-transformers/all-mpnet-base-v2"><em>all-mpnet-base-v2</em></a><em>"</em> 텍스트 임베딩 모델을 포함하는 추론 프로세서를 사용하여 파이프라인에서 수집되는 데이터에 대해 추론하는 방식으로 생성되었습니다.</p><p>이 모델은 다음을 사용하여 사전 학습된 모델의 평가를 기반으로 선택되었습니다. <em>"</em><a href="https://github.com/UKPLab/sentence-transformers/blob/master/docs/package_reference/sentence_transformer/evaluation.md"><em>sentence_transformers.evaluation</em></a><em>"</em> 훈련 중 모델을 평가하는 데 다양한 클래스가 사용됩니다. "all-mpnet-base-v2" 모델은 <a href="https://www.sbert.net/docs/pretrained_models.html">문장-변환 순위에서</a> 가장 우수한 평균 성능을 보였으며, <a href="https://huggingface.co/spaces/mteb/leaderboard">대용량 텍스트 임베딩 벤치마크(MTEB)</a> 리더보드에서도 유리한 위치를 확보했습니다. 이 모델은<a href="https://huggingface.co/microsoft/mpnet-base"> Microsoft/MPnet-Base</a> 모델을 사전 학습하고 1B 문장 쌍 데이터 세트에서 미세 조정하여 문장을 768차원의 고밀도 벡터 공간에 매핑합니다.</p><p>또는 도메인별 데이터에 맞게 세밀하게 조정된 다른 모델을 사용할 수도 있습니다.</p><p>출력</p>Score: 0.79207325
Product: Patio Sofa Set with Ottoman
Category: Outdoor Furniture
Description: is a versatile and comfortable patio sofa set, including a sofa, ottoman, and coffee table, great for outdoor lounging.

Score: 0.7836937
Product: Patio Sofa Set with Canopy
Category: Outdoor Furniture
Description: is a luxurious and comfortable patio sofa set with a canopy, providing shade and style for outdoor lounging.
<p><em>출력은 선택한 모델,</em> <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/knn-search.html#knn-search-filter-example"><em>필터</em></a> <em>및</em> <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/knn-search.html#tune-approximate-knn-for-speed-accuracy"><em>대략적인 kNN 튜닝에</em></a>따라 달라질 수 있습니다<em>.</em></p><p><em>검색어에 " outdoor</em>" 라는 단어가 명시적으로 언급되지 않았음에도 불구하고 kNN 검색 결과는 모두 "<em>아웃도어</em>가구 " 카테고리에 속하며, 이는 문맥에서 의미 이해의 중요성을 강조합니다.</p><p>고밀도 벡터 검색은 몇 가지 장점이 있습니다:</p><ul><li><p>시맨틱 검색 활성화</p></li><li><p>대규모 데이터 세트를 처리할 수 있는 확장성</p></li><li><p>다양한 데이터 유형을 처리할 수 있는 유연성</p></li></ul><p>하지만 <strong>밀도 높은 벡터 검색에는 고유한 문제도</strong> 있습니다:</p><ul><li><p>사용 사례에 적합한 임베딩 모델 선택하기</p></li><li><p>모델을 선택한 후에는 도메인별 데이터 세트에서 성능을 최적화하기 위해 모델을 미세 조정해야 할 수 있으며, 이 과정에는 도메인 전문가의 참여가 필요합니다.</p></li><li><p>또한 고차원 벡터를 인덱싱하는 데는 계산 비용이 많이 들 수 있습니다.</p></li></ul><h2>시맨틱 검색 - 학습된 희소 검색</h2><p>시맨틱 검색을 수행하는 또 다른 방법인 학습된 희소 검색에 대해 알아보겠습니다.</p><p>스파스 모델로서, 수십 년에 걸친 최적화의 혜택을 누리고 있는 Elasticsearch의 Lucene 기반 반전 인덱스를 활용합니다. 그러나 이 접근 방식은 단순히 BM25와 같은 어휘 채점 기능을 사용하여 동의어를 추가하는 것 이상의 의미를 갖습니다. 대신, 더 심층적인 언어 규모 지식을 사용하여 학습된 연관성을 통합하여 관련성을 최적화합니다.</p><p>검색 쿼리를 확장하여 원래 쿼리에 없는 관련 용어를 포함시킴으로써, 아래 예에서 볼 수 있듯이 <a href="https://www.elastic.co/guide/en/machine-learning/current/ml-nlp-elser.html">Elastic 학습형 스파스 인코더는</a> <strong>스파스 벡터 임베딩을 개선합니다</strong>.</p><h3>Elastic 학습형 스파스 인코더를 사용한 스파스 벡터 검색</h3># Elastic Learned Sparse Encoder

response = client.search(index='ecommerce-search', size=2,
query={
  "text_expansion": {
    "ml.tokens": {
      "model_id":"elser_model",
      "model_text":"Comfortable furniture for a large balcony"                
    }
  }
}
)

for hit in response['hits']['hits']:

  score = hit['_score']
  product = hit['_source']['product']
  category = hit['_source']['category']
  description = hit['_source']['description']
  print(f"\nScore: {score}\nProduct: {product}\nCategory: {category}\nDescription: {description}\n")
<p>출력</p>Score: 14.405318
Product: Garden Lounge Set with Side Table
Category: Garden Furniture
Description: is a comfortable and stylish garden lounge set, including a sofa, chairs, and a side table for outdoor relaxation.

Score: 14.281318
Product: Rattan Patio Conversation Set
Category: Outdoor Furniture
Description: is a stylish and comfortable outdoor furniture set, including a sofa, two chairs, and a coffee table, all made of durable rattan material.
<p>이 경우 결과에는 "<em>야외 가구</em>" 와 매우 유사한 제품을 제공하는 "<em>정원 가구 " 카테고리가 포함됩니다.</em></p><p>분석하여 "ml.tokens", 학습된 희소 검색이 생성한 토큰이 포함된 "rank_features" 필드를 보면, 생성된 다양한 토큰 중 검색 쿼리의 일부가 아니지만 "<em>relax</em>" (편안한), "<em>sofa</em>" (가구), "<em>outdoor</em>" (발코니)와 같이 의미상 여전히 연관성이 있는 용어가 있다는 것을 알 수 있습니다.</p><p>아래 이미지는 용어 확장이 있는 경우와 없는 경우 모두 쿼리와 함께 이러한 용어 중 일부를 강조 표시합니다.</p><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt7e869985347b19a7/6a17d875e31791dc2c2d56a1/dd86607fce6137d843a3ec002390eaa988b432f9-1440x502.png" alt="" /><p>이 모델은 문맥 인식 검색을 제공하고 어휘 불일치 문제를 완화하는 동시에 해석 가능한 결과를 제공하는 데 도움이 됩니다. 도메인별 재학습이 적용되지 않은 경우에도 고밀도 벡터 모델을 능가하는 성능을 발휘할 수 있습니다.</p><h2>하이브리드 검색: 어휘 검색과 시맨틱 검색을 결합하여 관련성 높은 결과 제공</h2><p>검색에 관한 한 만능 솔루션은 존재하지 않습니다. 이러한 검색 방법에는 각각 장점도 있지만 문제점도 있습니다. 사용 사례에 따라 가장 적합한 옵션이 변경될 수 있습니다. 종종 검색 방법 간에 상호 보완적으로 최상의 결과를 얻을 수 있습니다. 따라서 관련성을 높이기 위해 각 방법의 강점을 결합하는 방법을 살펴볼 것입니다.</p><p><strong>하이브리드 검색을</strong> 구현하는 방법에는 선형 조합, 각 점수에 가중치를 부여하는 방법, 가중치를 지정할 필요가 없는 상호 순위 융합(RRF) 등 여러 가지가 있습니다.</p><h3>Elasticsearch: 어휘 검색과 시맨틱 검색의 두 가지 장점을 모두 갖춘 최고의 솔루션</h3># BM25 + Elastic Learned Sparse Encoder (Linear Combination)

response = client.search(index='ecommerce-search', size=2,

query= {
  "bool": {
    "should": [
    {
      "match": {
        "description" : {  
          "query": "A dining table and comfortable chairs for a large balcony",
          "boost": 1
        }
      }
    },                   
    {
      "text_expansion": {
        "ml.tokens": {
          "model_id": "elser_model",
          "model_text": "A dining table and comfortable chairs for a large balcony",
          "boost": 1
        }
      }
     }
    ]
  }
}
)

# The boost value is 1 for the text expansion and match query. This means that the relevance score of the results of these queries are not boosted. You can specify a boost value to give a weight to each score in the sum. The scores will be calculated as: score = boost value * match_score + boost value * text_expansion_score

for hit in response['hits']['hits']:

  score = hit['_score']
  product = hit['_source']['product']
  category = hit['_source']['category']
  description = hit['_source']['description']
  print(f"\nScore: {score}\nProduct: {product}\nCategory: {category}\nDescription: {description}\n")
<p>이 코드에서는 "<em>큰 발코니를 위한 식탁과 편안한 의자</em>" 라는 값을 갖는 두 개의 쿼리를 사용하여 하이브리드 검색을 수행했습니다. "<em>가구</em>" 을 검색어로 사용하는 대신 찾고 있는 내용을 지정하고 있으며, 두 검색 모두 동일한 필드 값인 "설명" 을 고려하고 있습니다. 순위는 BM25와 ELSER 점수에 동일한 가중치를 부여한 선형 조합으로 결정됩니다.</p><p>출력</p>Score: 31.628141
Product: Garden Dining Set with Swivel Rockers
Category: Garden Furniture
Description: is a functional and comfortable garden dining set, including a table and chairs with swivel rockers for easy movement.

Score: 31.334227
Product: Garden Dining Set with Swivel Chairs
Category: Garden Furniture
Description: is a functional and comfortable garden dining set, including a table and chairs with swivel seats for convenience.
<p>아래 코드에서는 쿼리에 동일한 값을 사용하되, 상호 순위 융합 방법을 사용하여 BM25(쿼리 파라미터)와 kNN(knn 파라미터)의 점수를 결합하여 문서를 결합하고 순위를 매깁니다.</p># BM25 + KNN (RRF)

response = client.search(index='ecommerce-search', size=2,
query={
  "bool": {
    "should": [
    {
      "match": {
        "description": {
        "query": "A dining table and comfortable chairs for a large balcony"
        }
      }
    }
    ]
  }
},
knn={
  "field": "description_vector.predicted_value",
  "k": 50,
  "num_candidates": 500,
  "query_vector_builder": {
    "text_embedding": {
      "model_id": "sentence-transformers__all-mpnet-base-v2",
      "model_text": "A dining table and comfortable chairs for a large balcony"
    }
  }
},
rank={
  "rrf": { # Reciprocal rank fusion
    "window_size": 50, # This value determines the size of the individual result sets per query.
    "rank_constant": 20 # This value determines how much influence documents in individual result sets per query have over the final ranked result set.
  }
}
)

for hit in response['hits']['hits']:
        
  rank = hit['_rank']
  category = hit['_source']['category']
  product = hit['_source']['product']
  description = hit['_source']['description']
  print(f"\nRank: {rank}\nProduct: {product}\nCategory: {category}\nDescription: {description}\n")
<p><em>RRF 기능은 기술 미리보기 중입니다. 구문은 GA 이전에 변경될 가능성이 높습니다.</em></p><p>출력</p>Rank: 1
Product: Patio Dining Set with Bench
Category: Outdoor Furniture
Description: is a spacious and functional patio dining set, including a dining table, chairs, and a bench for additional seating.

Rank: 2
Product: Garden Dining Set with Swivel Chairs
Category: Garden Furniture
Description: is a functional and comfortable garden dining set, including a table and chairs with swivel seats for convenience.
<p>여기에서도 다양한 필드와 값을 사용할 수 있으며, 이러한 예제 중 일부는 <a href="https://github.com/elastic/elasticsearch-labs/blob/main/supporting-blog-content/lexical-and-semantic-search-with-elasticsearch/ecommerce_dense_sparse_project.ipynb">Python 노트북에서</a> 사용할 수 있습니다.</p><p>보시다시피, Elasticsearch를 사용하면 기존의 어휘 검색과 벡터 검색(희소 또는 고밀도)의 두 가지 장점을 모두 활용하여 목표에 <strong>도달하고 질문에 대한 최상의 답을 찾을</strong>수 있습니다 .</p><p>여기에 언급된 접근 방식에 대해 계속 알아보고 싶다면 다음 블로그가 유용할 수 있습니다:</p><ul><li><p><a href="https://www.elastic.co/blog/improving-information-retrieval-elastic-stack-hybrid">Elastic Stack에서 정보 검색 개선: 하이브리드 검색</a></p></li><li><p><a href="https://www.elastic.co/blog/vector-search-elasticsearch-rationale">Elasticsearch의 벡터 검색: 설계의 근거</a></p></li><li><p><a href="https://www.elastic.co/blog/lexical-ai-powered-search-elastic-vector-database">Elastic의 벡터 데이터베이스로 어휘 및 AI 기반 검색을 최대한 활용하는 방법</a></p></li><li><p><a href="https://www.elastic.co/blog/may-2023-launch-sparse-encoder-ai-model">Elastic 학습형 스파스 인코더를 소개합니다: 시맨틱 검색을 위한 Elastic의 AI 모델</a></p></li><li><p><a href="https://www.elastic.co/blog/may-2023-launch-information-retrieval-elasticsearch-ai-model">Elastic Stack에서 정보 검색 개선: 새로운 검색 모델인 Elastic 학습형 스파스 인코더를 소개합니다.</a></p></li></ul><p>Elasticsearch는 벡터 검색을 구축하는 데 필요한 모든 도구와 함께 벡터 데이터베이스를 제공합니다:</p><ul><li><p>Elasticsearch <a href="https://www.elastic.co/elasticsearch/vector-database">벡터 데이터베이스</a></p></li><li><p>Elastic의 <a href="https://www.elastic.co/enterprise-search/vector-search">벡터 검색</a> 사용 사례</p></li></ul><h2>결론</h2><p>이 블로그 게시물에서는 특히 텍스트, 어휘 및 의미 검색에 초점을 맞춰 Elasticsearch를 사용해 정보를 검색하는 다양한 접근 방식을 살펴봤습니다. 이를 보여드리기 위해 이커머스 제품 정보가 포함된 데이터 세트를 사용하여 다양한 검색 시나리오를 보여주는 Python 예제를 제공했습니다.</p><p>BM25로 기존 어휘 검색을 검토하고 어휘 불일치 등의 장점과 문제점에 대해 논의했습니다. 우리는 이 문제를 극복하기 위해 시맨틱 지식을 통합하는 것이 중요하다고 강조했습니다. 또한 시맨틱 검색을 가능하게 하는 고밀도 벡터 검색에 대해 논의하고, 고차원 벡터를 색인화할 때의 계산 비용 등 이 검색 방법과 관련된 문제점에 대해서도 다뤘습니다.</p><p>반면에 스파스 벡터는 압축률이 매우 높다고 언급했습니다. 따라서 원래 쿼리에 없는 관련 용어를 포함하도록 검색 쿼리를 확장하는 Elastic의 학습된 스파스 인코더에 대해 설명했습니다.</p><p>검색에 있어 만능 솔루션은 존재하지 않습니다. 각 검색 방법에는 장단점이 있습니다. 따라서 하이브리드 검색의 개념에 대해서도 논의했습니다.</p><p>보시다시피, Elasticsearch를 사용하면 기존의 어휘 검색과 벡터 검색이라는 두 가지 장점을 모두 누릴 수 있습니다!</p><p>시작할 준비가 되셨나요? 사용 가능한 <a href="https://github.com/elastic/elasticsearch-labs/blob/main/supporting-blog-content/lexical-and-semantic-search-with-elasticsearch/ecommerce_dense_sparse_project.ipynb">Python 노트북을</a> 확인하고 <a href="https://cloud.elastic.co/registration?onboarding_token=vectorsearch&amp;cta=cloud-registration&amp;tech=trial&amp;plcmt=article%20content&amp;pg=search-labs">Elastic Cloud 무료 체험판을</a> 시작하세요.</p>]]></content:encoded>
    <link>https://www.elastic.co/search-labs/blog/lexical-and-semantic-search-with-elasticsearch</link>
    <guid isPermaLink="true">https://www.elastic.co/search-labs/blog/lexical-and-semantic-search-with-elasticsearch</guid>
    <category><![CDATA[벡터 데이터베이스]]></category>
    <category><![CDATA[Python]]></category>
    <category><![CDATA[쿼리 언어]]></category>
    <dc:creator><![CDATA[Priscilla Parodi]]></dc:creator>
    <enclosure url="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/bltbd7e961f594005e7/6a17d80f033c8d981f6bb009/d240bfef29e9d432069059b312dd044eb76eec6c-1440x840.png" length="0" type="image/png"/>
    <pubDate>Tue, 03 Oct 2023 00:00:00 GMT</pubDate>
  </item>
  </channel>
</rss>