SupabaseGroongaBM25Retriever

SupabaseGroongaBM25Retriever

SupabaseGroongaBM25Retriever 는 PGroonga 검색으로 SupabaseGroongaDocumentStore 에서 문서를 가져오는 전문(full-text) 리트리버예요. 임베딩 없이 일반 텍스트 쿼리로 동작해서, 다국어 문서 검색에 특히 유용해요.

출처: 문서

본문

개요 (Overview)

SupabaseGroongaBM25Retriever 는 빠른 다국어 전문 검색을 위한 PostgreSQL 확장인 PGroonga를 사용해 SupabaseGroongaDocumentStore 에서 문서를 검색해요.

임베딩 기반 리트리버와 달리 이 리트리버는 일반 텍스트 쿼리로 동작하고 임베딩이 필요 없어요. PGroonga의 다국어 인덱싱 기능 덕분에 기본적으로 다양한 언어를 지원해요.

이 리트리버는 SupabasePgvectorEmbeddingRetriever 및 DocumentJoiner와 결합해, 키워드 검색과 의미 검색을 모두 활용하는 하이브리드 검색 파이프라인을 만들 수 있어요. RAG 파이프라인에서 두 리트리버의 결과를 합치고 싶다면 Smart Pipeline Connections를 이용해 DocumentJoiner 를 생략할 수도 있어요.

query 외에도 이 리트리버는 top_k(가져올 최대 문서 수)와 검색 범위를 좁히는 filters 같은 선택 파라미터를 받아요.

사전 조건 (Prerequisites)

Supabase 프로젝트에서 PGroonga를 활성화해야 해요. Supabase SQL 편집기에서 다음 SQL을 실행하세요:

CREATE EXTENSION IF NOT EXISTS pgroonga;

또한 PGroonga가 검색에 쓰는 SQL 함수를 만들어야 해요. 필요한 함수 정의는 통합 README에서 확인할 수 있어요.

설치 (Installation)

pip install supabase-haystack

사용법 (Usage)

단독으로 쓰기

이 리트리버는 SupabaseGroongaDocumentStore 와 인덱싱된 문서가 있어야 동작해요. Supabase 프로젝트의 SUPABASE_URL 과 SUPABASE_SERVICE_KEY 환경 변수를 설정하세요.

from haystack_integrations.document_stores.supabase import SupabaseGroongaDocumentStore
from haystack_integrations.components.retrievers.supabase import (
    SupabaseGroongaBM25Retriever,
)
from haystack.utils import Secret

document_store = SupabaseGroongaDocumentStore(
    supabase_url="https://.supabase.co",
    supabase_key=Secret.from_env_var("SUPABASE_SERVICE_KEY"),
    table_name="haystack_groonga_documents",
)
retriever = SupabaseGroongaBM25Retriever(document_store=document_store)
retriever.run(query="my nice query")

RAG 파이프라인에서 쓰기

이 코드를 실행하기 위한 사전 조건은 다음과 같아요:

  • OPENAI_API_KEY 환경 변수에 OpenAI API 키를 설정하세요.
  • SUPABASE_SERVICE_KEY 환경 변수에 Supabase 서비스 역할 키를 설정하세요.
from haystack import Document, 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.utils import Secret
from haystack_integrations.document_stores.supabase import SupabaseGroongaDocumentStore
from haystack_integrations.components.retrievers.supabase import (
    SupabaseGroongaBM25Retriever,
)

document_store = SupabaseGroongaDocumentStore(
    supabase_url="https://.supabase.co",
    supabase_key=Secret.from_env_var("SUPABASE_SERVICE_KEY"),
    table_name="haystack_groonga_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.",
    ),
]
document_store.write_documents(documents=documents, policy=DuplicatePolicy.SKIP)

prompt_template = [
    ChatMessage.from_user(
        "Given these documents, answer the question.\nDocuments:\n"
        "{% for doc in documents %}{{ doc.content }}{% endfor %}\n"
        "Question: {{question}}\nAnswer:"
    ),
]

retriever = SupabaseGroongaBM25Retriever(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={"question", "documents"},
    ),
    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"])

더 알아보기 (Learn more)