QueryExpander

QueryExpander

QueryExpander는 LLM을 사용해 의미적으로 유사한 쿼리를 생성해 RAG 시스템의 검색 재현율(recall)을 높이는 컴포넌트예요.

출처: 문서

본문

항목 내용
파이프라인에서 가장 흔한 위치 MultiQueryTextRetriever 또는 MultiQueryEmbeddingRetriever처럼 여러 쿼리를 받는 Retriever 컴포넌트 앞
필수 run 변수 query: 확장할 쿼리 문자열
출력 변수 queries: 확장된 쿼리 목록
API reference Query
GitHub 링크 query_expander.py
패키지 이름 haystack-ai

개요

QueryExpander는 사용자 쿼리를 받아 의미적으로 유사한 여러 변형을 생성해요. 이 기법은 원래 쿼리 문구와는 정확히 일치하지 않지만 여전히 관련 있는 문서를 검색 시스템이 찾을 수 있게 해서 재현율을 높여 주죠.

이 컴포넌트는 채팅 기반 LLM을 사용해 확장된 쿼리를 생성해요. 기본적으로 OpenAI의 gpt-4.1-mini 모델을 사용하지만, 선호하는 어떤 Chat Generator 컴포넌트(AnthropicChatGenerator나 AzureOpenAIChatGenerator 같은)든 chat_generator 파라미터로 전달할 수 있어요.

아래 예제는 anthropic-haystack 패키지에 있는 AnthropicChatGenerator를 사용해요:

pip install anthropic-haystack
from haystack.components.query import QueryExpander
from haystack_integrations.components.generators.anthropic import AnthropicChatGenerator

expander = QueryExpander(
    chat_generator=AnthropicChatGenerator(model="claude-sonnet-4-20250514"),
    n_expansions=3,
)

생성되는 쿼리는 이렇습니다:

  • 핵심 의미는 유지하면서 다른 단어와 표현을 사용해요
  • 동의어와 관련 용어를 포함해요
  • 원래 쿼리의 언어를 보존해요
  • 키워드 기반 검색과 시맨틱 검색(임베딩 같은) 모두에서 잘 동작하도록 설계됐어요

확장 개수는 n_expansions 파라미터로, 원래 쿼리를 출력에 포함할지 여부는 include_original_query 파라미터로 제어할 수 있어요.

커스텀 프롬프트 템플릿

쿼리가 어떻게 확장되는지 제어하려면 커스텀 프롬프트 템플릿을 제공할 수 있어요:

from haystack.components.query import QueryExpander

custom_template = """You are a search query expansion assistant.
Generate {{ n_expansions }} alternative search queries for: "{{ query }}"
Return a JSON object with a "queries" array containing the expanded queries.
Focus on technical terminology and domain-specific variations."""

expander = QueryExpander(prompt_template=custom_template, n_expansions=4)
result = expander.run(query="machine learning optimization")

사용법

QueryExpander는 멀티 쿼리 Retriever와 함께 동작하도록 설계되었어요. 완전한 파이프라인 예제는 다음을 참고하세요:

더 알아보기 (Learn more)