SentenceWindowRetriever
SentenceWindowRetriever
SentenceWindowRetriever 는 검색 결과로 나온 관련 문장의 주변 문장들까지 함께 끌어와서 전체 맥락을 얻을 수 있게 해 주는 컴포넌트예요. 짧은 문장 단위로 쪼개 검색하다 보면 문맥이 잘리기 쉬운데, 이 컴포넌트가 그 문제를 보완해 줘요.
출처: 문서
본문
개요 (Overview)
"문장 창(sentence window)"은 관련 문장 주변의 맥락까지 함께 검색하는 기법이에요. 인덱싱할 때 문서를 작은 덩어리나 문장으로 쪼개서 저장하고, 검색할 때는 질의와 유사도가 가장 높은 문장들을 찾아요. 관련 문장을 찾고 나면 그 주변의 이웃 문장들을 가져와 전체 맥락을 만들죠. 이웃 문장의 개수는 관련 문장 앞뒤로 고정된 개수로 정해요.
이 컴포넌트는 InMemoryEmbeddingRetriever 같은 다른 Retriever와 함께 쓰도록 설계되었어요. 그러한 Retriever가 질의를 인덱싱된 문장과 비교해 관련 문장을 찾고, SentenceWindowRetriever 가 Document 객체에 저장된 메타데이터를 활용해 관련 문장 주변의 이웃 문장들을 가져오는 구조예요.
사용법 (Usage)
단독으로 쓰기
splitter = DocumentSplitter(split_length=10, split_overlap=5, split_by="word")
text = (
"This is a text with some words. There is a second sentence. And there is also a third sentence. "
"It also contains a fourth sentence. And a fifth sentence. And a sixth sentence. And a seventh sentence"
)
doc = Document(content=text)
docs = splitter.run([doc])
doc_store = InMemoryDocumentStore()
doc_store.write_documents(docs["documents"])
retriever = SentenceWindowRetriever(document_store=doc_store, window_size=3)
파이프라인에서 쓰기
from haystack import Document, Pipeline
from haystack.components.retrievers.in_memory import InMemoryBM25Retriever
from haystack.components.retrievers import SentenceWindowRetriever
from haystack.components.preprocessors import DocumentSplitter
from haystack.document_stores.in_memory import InMemoryDocumentStore
splitter = DocumentSplitter(split_length=10, split_overlap=5, split_by="word")
text = (
"This is a text with some words. There is a second sentence. And there is also a third sentence. "
"It also contains a fourth sentence. And a fifth sentence. And a sixth sentence. And a seventh sentence"
)
doc = Document(content=text)
docs = splitter.run([doc])
doc_store = InMemoryDocumentStore()
doc_store.write_documents(docs["documents"])
rag = Pipeline()
rag.add_component("bm25_retriever", InMemoryBM25Retriever(doc_store, top_k=1))
rag.add_component(
"sentence_window_retriever",
SentenceWindowRetriever(document_store=doc_store, window_size=3),
)
rag.connect("bm25_retriever", "sentence_window_retriever")
rag.run({"bm25_retriever": {"query": "third"}})
추가 자료 (Additional References)
📓 튜토리얼: 문장 주변의 컨텍스트 창 검색하기