SolrBM25Retriever
SolrBM25Retriever
SolrBM25Retriever 는 Solr Document Store에서 질의와 일치하는 문서를 가져오는 키워드 기반 리트리버예요. BM25 알고리즘으로 문서와 질의 사이의 유사도를 계산해 관련 문서를 찾아줘요.
출처: 문서
본문
개요 (Overview)
SolrBM25Retriever 는 SolrDocumentStore에서 질의와 일치하는 문서를 가져오는 키워드 기반 리트리버예요. 문서와 질의 사이의 유사도를 BM25 알고리즘으로 계산하는데, 이 알고리즘은 두 문자열의 **가중 단어 겹침(weighted word overlap)**을 구해요.
SolrBM25Retriever 는 단어 겹침 기반으로 문자열을 매칭하므로, 사람이나 제품 이름, ID, 잘 정의된 오류 메시지의 정확한 일치를 찾는 데 자주 쓰여요. BM25 알고리즘은 매우 가볍고 단순해요. 도메인 밖 데이터에서 더 복잡한 임베딩 기반 접근보다 이를 능가하기 어려울 때도 많아요.
질의와 문서의 의미적 매칭이 필요하다면, 임베딩 모델이 만든 벡터로 관련 정보를 검색하는 SolrEmbeddingRetriever나 두 접근을 결합한 SolrHybridRetriever를 사용하세요.
파라미터 (Parameters)
query 외에도 SolrBM25Retriever 는 다른 옵션 파라미터를 받아요. top_k(가져올 최대 문서 수), 검색 범위를 좁히는 filters 등이 있죠. fuzziness 를 0보다 크게 설정하면 해당 편집 거리(edit distance)로 용어별 퍼지 매칭이 켜지고, all_terms_must_match=True 로 설정하면 질의의 모든 용어가 일치해야 해요. scale_score=True 를 주면 BM25 점수가 (0, 1) 범위로 스케일링돼요.
리트리버는 Document Store의 async 클라이언트를 사용하는 run_async 메서드도 제공해요.
사용법 (Usage)
설치 (Installation)
Solr를 Haystack에서 쓰려면 패키지를 설치하세요:
pip install solr-haystack
단독으로 쓰기
이 리트리버는 SolrDocumentStore 인스턴스와 인덱싱된 문서가 있어야 동작해요.
from haystack_integrations.document_stores.solr import SolrDocumentStore
from haystack_integrations.components.retrievers.solr import SolrBM25Retriever
document_store = SolrDocumentStore(url="http://localhost:8983/solr", core="haystack")
retriever = SolrBM25Retriever(document_store=document_store)
retriever.run(query="How to make a pizza", top_k=3)
파이프라인에서 쓰기
from haystack import Document, Pipeline
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
from haystack_integrations.components.retrievers.solr import SolrBM25Retriever
from haystack_integrations.document_stores.solr import SolrDocumentStore
# 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 = SolrDocumentStore(url="http://localhost:8983/solr", core="haystack")
# 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 is optional, but useful to run the script multiple times without throwing errors
document_store.write_documents(documents=documents, policy=DuplicatePolicy.SKIP)
rag_pipeline = Pipeline()
rag_pipeline.add_component(
"retriever", SolrBM25Retriever(document_store=document_store)
)
rag_pipeline.add_component(
"prompt_builder",
ChatPromptBuilder(template=prompt_template, required_variables="*"),
)
rag_pipeline.add_component("llm", OpenAIChatGenerator())
rag_pipeline.connect("retriever", "prompt_builder.documents")
rag_pipeline.connect("prompt_builder", "llm.messages")
question = "How many languages are spoken around the world today?"
result = rag_pipeline.run(
{
"retriever": {"query": question},
"prompt_builder": {"question": question},
}
)
더 알아보기 (Learn more)
- SolrDocumentStore — Solr 기반 문서 저장소
- SolrEmbeddingRetriever — 임베딩 기반 의미 검색 리트리버
- SolrHybridRetriever — BM25와 임베딩을 결합한 하이브리드 리트리버
- ChatPromptBuilder, TransformersExtractiveReader
- Solr API 참조
- GitHub 저장소