ElasticsearchBM25Retriever
ElasticsearchBM25Retriever
Elasticsearch Document Store에서 쿼리와 일치하는 문서를 가져오는 키워드 기반 리트리버예요.
출처: 문서
본문
- 파이프라인에서의 일반적인 위치: 1. RAG 파이프라인에서
PromptBuilder앞. 2. 시맨틱 검색 파이프라인의 마지막 컴포넌트. 3. 추출형 QA 파이프라인에서TransformersExtractiveReader앞. - 필수 초기화 변수:
document_store(ElasticsearchDocumentStore 인스턴스) - 필수 실행 변수:
query(문자열) - 출력 변수:
documents(쿼리와 일치하는 문서 리스트)
개요 (Overview)
ElasticsearchBM25Retriever는 ElasticsearchDocumentStore에서 쿼리와 일치하는 문서를 가져오는 키워드 기반 리트리버예요. 문서와 쿼리 사이의 유사도를 BM25 알고리즘에 기반해 계산하는데, 이 알고리즘은 두 문자열 사이의 가중 단어 겹침(weighted word overlap)을 계산해요.
ElasticsearchBM25Retriever는 단어 겹침에 기반해 문자열을 매칭하므로, 사람 이름이나 제품 이름, ID, 또는 명확히 정의된 오류 메시지의 정확한 일치를 찾는 데 자주 사용돼요. BM25 알고리즘은 매우 가볍고 단순해요. 그럼에도 도메인 밖(out-of-domain) 데이터에서는 더 복잡한 임베딩 기반 접근법으로도 이기기 어려울 수 있어요.
ElasticsearchBM25Retriever는 query 외에도 top_k(검색할 최대 문서 수)와 filters(검색 공간을 좁히는 용도) 같은 다른 선택적 파라미터를 받아요. 리트리버를 초기화할 때 fuzziness 파라미터로 비정확한 퍼지 매칭(fuzzy matching)이 수행되는 방식을 조정할 수도 있어요.
쿼리와 문서 사이의 의미적 매칭을 원한다면, 임베딩 모델이 만든 벡터로 관련 정보를 검색하는 ElasticsearchEmbeddingRetriever를 사용할 수 있어요.
설치 (Installation)
Elasticsearch를 설치한 뒤 인스턴스를 시작하세요. Haystack은 Elasticsearch 8을 지원해요.
Docker가 설정되어 있다면 Docker 이미지를 받아 실행하는 것을 권장해요.
docker pull docker.elastic.co/elasticsearch/elasticsearch:8.19.7
docker run -p 9200:9200 -e "discovery.type=single-node" -e "ES_JAVA_OPTS=-Xms1024m -Xmx1024m" -e "xpack.security.enabled=false" elasticsearch:8.19.7
대안으로 Elasticsearch 통합 GitHub에서 제공하는 docker-compose.yml을 사용해 Elasticsearch를 실행하는 Docker 컨테이너를 시작할 수 있어요.
docker compose up
실행 중인 Elasticsearch 인스턴스가 있으면 elasticsearch-haystack 통합을 설치하세요.
pip install elasticsearch-haystack
사용법 (Usage)
단독 사용 (On its own)
from haystack import Document
from haystack_integrations.components.retrievers.elasticsearch import (
ElasticsearchBM25Retriever,
)
from haystack_integrations.document_stores.elasticsearch import (
ElasticsearchDocumentStore,
)
from elasticsearch import Elasticsearch
document_store = ElasticsearchDocumentStore(hosts="http://localhost:9200/")
documents = [
Document(content="There are over 7,000 languages spoken around the world today."),
Document(
content="Elephants have been observed to behave in a way that indicates a high level of self-awareness, such as recognizing themselves in mirrors.",
),
Document(
content="In certain parts of the world, like the Maldives, Puerto Rico, and San Diego, you can witness the phenomenon of bioluminescent waves.",
),
]
document_store.write_documents(documents=documents)
retriever = ElasticsearchBM25Retriever(document_store=document_store)
retriever.run(query="How many languages are spoken around the world today?")
RAG 파이프라인에서 사용 (In a RAG pipeline)
OPENAI_API_KEY를 환경 변수로 설정한 뒤 다음 코드를 실행하세요.
from haystack_integrations.components.retrievers.elasticsearch import (
ElasticsearchBM25Retriever,
)
from haystack_integrations.document_stores.elasticsearch import (
ElasticsearchDocumentStore,
)
from elasticsearch import Elasticsearch
from haystack import Document
from haystack import Pipeline
from haystack.components.builders.answer_builder import AnswerBuilder
from haystack.components.builders import ChatPromptBuilder
from haystack.components.generators.chat import OpenAIChatGenerator
from haystack.dataclasses import ChatMessage
from haystack.document_stores.types import DuplicatePolicy
# OpenAIChatGenerator reads the OPENAI_API_KEY environment variable by default.
# Create a RAG query pipeline
prompt_template = [
ChatMessage.from_user(
"""
Given these documents, answer the question.\nDocuments:
{% for doc in documents %}
{{ doc.content }}
{% endfor %}
\nQuestion: {{question}}
\nAnswer:
""",
),
]
document_store = ElasticsearchDocumentStore(hosts="http://localhost:9200/")
# Add Documents
documents = [
Document(content="There are over 7,000 languages spoken around the world today."),
Document(
content="Elephants have been observed to behave in a way that indicates a high level of self-awareness, such as recognizing themselves in mirrors.",
),
Document(
content="In certain parts of the world, like the Maldives, Puerto Rico, and San Diego, you can witness the phenomenon of bioluminescent waves.",
),
]
# DuplicatePolicy.SKIP param is optional, but useful to run the script multiple times without throwing errors
document_store.write_documents(documents=documents, policy=DuplicatePolicy.SKIP)
retriever = ElasticsearchBM25Retriever(document_store=document_store)
rag_pipeline = Pipeline()
rag_pipeline.add_component(name="retriever", instance=retriever)
rag_pipeline.add_component(
instance=ChatPromptBuilder(template=prompt_template, required_variables="*"),
name="prompt_builder",
)
rag_pipeline.add_component(instance=OpenAIChatGenerator(), name="llm")
rag_pipeline.add_component(instance=AnswerBuilder(), name="answer_builder")
rag_pipeline.connect("retriever", "prompt_builder.documents")
rag_pipeline.connect("prompt_builder.prompt", "llm.messages")
rag_pipeline.connect("llm.replies", "answer_builder.replies")
rag_pipeline.connect("retriever", "answer_builder.documents")
question = "How many languages are spoken around the world today?"
result = rag_pipeline.run(
{
"retriever": {"query": question},
"prompt_builder": {"question": question},
"answer_builder": {"query": question},
},
)
print(result["answer_builder"]["answers"][0].data)
얻을 수 있는 예시 출력은 다음과 같아요.
"Over 7,000 languages are spoken around the world today"