PgvectorKeywordRetriever
PgvectorKeywordRetriever
Pgvector Document Store에서 쿼리와 일치하는 문서를 가져오는 키워드 기반 Retriever예요.
출처: 문서
본문
| 항목 | 내용 |
|---|---|
| 파이프라인에서 가장 흔한 위치 | 1. RAG 파이프라인에서 PromptBuilder 앞 2. 시맨틱 검색 파이프라인의 마지막 컴포넌트 3. 추출형 QA 파이프라인에서 TransformersExtractiveReader 앞 |
| 필수 init 변수 | document_store: PgvectorDocumentStore 인스턴스 |
| 필수 run 변수 | query: 문자열 |
| 출력 변수 | documents: 쿼리와 일치하는 문서 목록 |
| API reference | Pgvector |
| GitHub 링크 | pgvector 통합 |
| 패키지 이름 | pgvector-haystack |
개요
PgvectorKeywordRetriever는 PgvectorDocumentStore와 호환되는 키워드 기반 Retriever예요.
이 컴포넌트는 문서 순위를 매기기 위해 PostgreSQL의 ts_rank_cd 함수를 사용해요. 쿼리 용어가 문서에 얼마나 자주 나타나는지, 문서 안에서 용어들이 서로 얼마나 가까이 있는지, 그리고 그 용어들이 나타나는 문서 부분이 얼마나 중요한지(가중치)를 고려하죠. 자세한 내용은 Postgres 문서를 참고하세요.
ElasticsearchBM25Retriever 같은 유사 컴포넌트와 달리, 이 Retriever는 기본적으로 퍼지 검색(fuzzy search)을 적용하지 않는다는 점을 기억하세요. 그래서 결과가 0개가 나오지 않도록 쿼리를 신중하게 구성하는 것이 중요해요.
query 외에도 PgvectorKeywordRetriever는 top_k(가져올 최대 문서 수)와 filters(검색 공간을 좁히기) 같은 선택적 파라미터를 받아요.
설치
pgvector가 있는 PostgreSQL 데이터베이스를 빠르게 구성하려면 Docker를 사용할 수 있어요:
docker run -d -p 5432:5432 -e POSTGRES_USER=postgres -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=postgres pgvector/pgvector:pg17
pgvector 설치 방법에 대한 자세한 내용은 pgvector GitHub 저장소를 방문하세요.
pgvector-haystack 통합 패키지를 설치하세요:
pip install pgvector-haystack
사용법
단독으로 사용하기
이 Retriever는 동작하려면 PgvectorDocumentStore와 인덱싱된 문서가 필요해요.
PostgreSQL 데이터베이스에 대한 연결 문자열로 PG_CONN_STR 환경 변수를 설정하세요.
from haystack_integrations.document_stores.pgvector import PgvectorDocumentStore
from haystack_integrations.components.retrievers.pgvector import (
PgvectorKeywordRetriever,
)
document_store = PgvectorDocumentStore()
retriever = PgvectorKeywordRetriever(document_store=document_store)
retriever.run(query="my nice query")
RAG 파이프라인에서 사용하기
이 코드를 실행하기 위한 전제 조건은 다음과 같아요:
OPENAI_API_KEY환경 변수에 OpenAI API 키 설정PG_CONN_STR환경 변수에 PostgreSQL 데이터베이스 연결 문자열 설정
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
from haystack_integrations.document_stores.pgvector import PgvectorDocumentStore
from haystack_integrations.components.retrievers.pgvector import (
PgvectorKeywordRetriever,
)
# 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 = PgvectorDocumentStore(
language="english", # this parameter influences text parsing for keyword retrieval
recreate_table=True,
)
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 = PgvectorKeywordRetriever(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 = "languages spoken around the world today"
result = rag_pipeline.run(
{
"retriever": {"query": question},
"prompt_builder": {"question": question},
"answer_builder": {"query": question},
},
)
print(result["answer_builder"])