본문 바로가기
WIKI 기술 지식 베이스

Query Planning tool

원문 보기 위키 갱신

출처: 문서

본문

쿼리 계획 도구

3.3에 도입됨 {: .label .label-purple }

QueryPlanningTool은 자연어 질문으로부터 OpenSearch 쿼리 도메인 특화 언어(DSL) 쿼리를 생성해요. 이는 에이전트 기반 워크플로를 통해 자연어 쿼리 처리를 가능하게 하는 에이전틱 검색의 핵심 구성 요소예요.

QueryPlanningTool은 자연어 질문에서 DSL 쿼리를 생성하기 위해 두 가지 접근 방식을 지원해요.

  • LLM 지식만 사용 (기본값): 대규모 언어 모델(LLM)이 학습 지식과 사용자가 제공한 시스템/사용자 프롬프트만을 사용하여 쿼리를 생성해요. 이 접근 방식은 전적으로 DSL 구문에 대한 모델의 이해와 특정 프롬프팅 지침에 의존해요.
  • 검색 템플릿 사용: LLM이 쿼리를 생성할 때 추가 컨텍스트로 미리 정의된 검색 템플릿을 사용해요. 설명이 포함된 검색 템플릿 모음을 제공하면 LLM이 이를 예시와 지침으로 사용하여 더 정확한 쿼리를 생성해요. LLM이 제공된 템플릿 중 사용자 질문에 적합한 것이 없다고 판단하면 독립적으로 쿼리를 생성하려고 시도해요.

검색 템플릿을 사용하는 것은 특정 사용 사례나 도메인에 대해 확립된 쿼리 패턴이 있을 때 특히 유용해요. LLM이 선호하는 구조를 따르고 인덱스 매핑에서 적절한 필드 이름을 사용하는 쿼리를 생성하는 데 도움을 줘요.

1단계: 인덱스 생성 및 샘플 데이터 수집

먼저, iris 데이터셋에 대한 인덱스를 생성하세요.

PUT /iris-index
{
  "mappings": {
    "properties": {
      "petal_length_in_cm": {
        "type": "float"
      },
      "petal_width_in_cm": {
        "type": "float"
      },
      "sepal_length_in_cm": {
        "type": "float"
      },
      "sepal_width_in_cm": {
        "type": "float"
      },
      "species": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword",
            "ignore_above": 256
          }
        }
      }
    }
  }
}

{% include copy-curl.html %}

다음으로, 인덱스에 샘플 문서를 수집하세요.

POST _bulk
{ "index": { "_index": "iris-index", "_id": "1" } }
{ "petal_length_in_cm": 1.4, "petal_width_in_cm": 0.2, "sepal_length_in_cm": 5.1, "sepal_width_in_cm": 3.5, "species": "setosa" }
{ "index": { "_index": "iris-index", "_id": "2" } }
{ "petal_length_in_cm": 4.5, "petal_width_in_cm": 1.5, "sepal_length_in_cm": 6.4, "sepal_width_in_cm": 2.9, "species": "versicolor" }
{ "index": { "_index": "iris-index", "_id": "3" } }
{ "petal_length_in_cm": 6.0, "petal_width_in_cm": 2.5, "sepal_length_in_cm": 5.9, "sepal_width_in_cm": 3.0, "species": "virginica" }

{% include copy-curl.html %}

2단계: 모델 등록 및 배포

다음 요청은 Amazon Bedrock에서 원격 모델을 등록하고 클러스터에 배포해요. API 호출은 커넥터와 모델을 한 단계로 생성해요. region, access_key, secret_key, session_token을 자신의 값으로 바꾸세요. converse API를 지원하는 모든 모델(예: Anthropic Claude 4 또는 GPT 5)을 사용할 수 있어요. 이 모델에 대한 커넥터를 생성하여 다른 모델 제공자를 사용할 수도 있어요(커넥터 청사진 참조).

중요: QueryPlanningTool에 대한 커넥터를 생성할 때 요청 본문에 system_prompt 및 user_prompt 매개변수가 포함되어야 해요. 이 매개변수는 도구가 시스템 및 사용자 프롬프트를 모델 요청에 제대로 주입하는 데 필요해요.

다음 예제는 Anthropic Claude 4 모델을 등록하고 배포해요.

POST /_plugins/_ml/models/_register?deploy=true
{
  "name": "Claude 4 Sonnet Query Planner Tool Model",
  "function_name": "remote",
  "description": "Claude 4 sonnet for Query Planning",
  "connector": {
    "name": "Bedrock Claude 4 Sonnet Connector",
    "description": "Amazon Bedrock connector for Claude 4 Sonnet",
    "version": 1,
    "protocol": "aws_sigv4",
    "parameters": {
      "region": "us-east-1",
      "service_name": "bedrock",
      "model": "us.anthropic.claude-sonnet-4-20250514-v1:0"
    },
    "credential": {
      "access_key": "your-aws-access-key",
      "secret_key": "your-aws-secret-key",
      "session_token": "your-aws-session-token"
    },
    "actions": [
      {
        "action_type": "predict",
        "method": "POST",
        "url": "https://bedrock-runtime.${parameters.region}.amazonaws.com/model/${parameters.model}/converse",
        "headers": {
          "content-type": "application/json"
        },
        "request_body": "{ \"system\": [{\"text\": \"${parameters.system_prompt}\"}], \"messages\": [${parameters._chat_history:-}{\"role\":\"user\",\"content\":[{\"text\":\"${parameters.user_prompt}\"}]}${parameters._interactions:-}]${parameters.tool_configs:-} }"
      }
    ]
  }
}

{% include copy-curl.html %}

다음 예제는 OpenAI GPT 5 모델을 등록하고 배포해요.

POST /_plugins/_ml/models/_register
{
    "name": "My OpenAI model: gpt-5",
    "function_name": "remote",
    "description": "test model",
    "connector": {
        "name": "My openai connector: gpt-5",
        "description": "The connector to openai chat model",
        "version": 1,
        "protocol": "http",
        "parameters": {
            "model": "gpt-5"
        },
        "credential": {
            "openAI_key": "your-openai-api-key"
        },
        "actions": [
            {
                "action_type": "predict",
                "method": "POST",
                "url": "https://api.openai.com/v1/chat/completions",
                "headers": {
                    "Authorization": "Bearer ${credential.openAI_key}"
                },
                "request_body": "{ \"model\": \"${parameters.model}\", \"messages\": [{\"role\":\"developer\",\"content\":\"${parameters.system_prompt}\"},${parameters._chat_history:-}{\"role\":\"user\",\"content\":\"${parameters.user_prompt}\"}${parameters._interactions:-}], \"reasoning_effort\":\"low\"${parameters.tool_configs:-}}"
            }
        ]
    }
}

{% include copy-curl.html %}

OpenSearch는 모델 ID로 응답해요.

{
  "task_id": "_9iSxJgBOh0h20Y9XYTH",
  "status": "CREATED",
  "model_id": "ANiSxJgBOh0h20Y9XYXl"
}

3단계: 에이전트 등록

QueryPlanningTool을 실행하려면 모든 OpenSearch 에이전트 유형을 사용할 수 있어요. 다음 예제는 flow 에이전트를 사용하며, 이 에이전트는 도구를 순서대로 실행하고 마지막 도구의 출력을 반환해요.

LLM 지식만 사용

프롬프트만 사용하려면 generation_type을 지정하지 않으면 기본값은 llmGenerated예요.

POST /_plugins/_ml/agents/_register
{
  "name": "Agentic Search with Claude 4",
  "type": "flow",
  "description": "A test agent for query planning.",
  "tools": [
    {
      "type": "QueryPlanningTool",
      "parameters": {
        "model_id": "ANiSxJgBOh0h20Y9XYXl"
      }
    }
  ]
}

{% include copy-curl.html %}

에이전트를 등록할 때 모델 등록 중에 지정한 매개변수(예: system_prompt 및 user_prompt)를 재정의할 수 있어요.

검색 템플릿 사용

OpenSearch DSL 생성을 지원하기 위해 검색 템플릿을 추가 컨텍스트로 추가할 수 있어요.

먼저, 검색 템플릿을 생성하세요.

POST /_scripts/flower_species_search_template
{
  "script": {
    "lang": "mustache",
    "source": {
      "from": "{% raw %} {{from}}{{^from}}0{{/from}} {% endraw %} ",
      "size": "{% raw %} {{size}}{{^size}}10{{/size}} {% endraw %} ",
      "query": {
        "match": {
          "species": "{% raw %} {{species}} {% endraw %} "
        }
      }
    }
  }
}

{% include copy-curl.html %}

POST /_scripts/flower_petal_length_range_template
{
  "script": {
    "lang": "mustache",
    "source": {
      "from": "{% raw %} {{from}}{{^from}}0{{/from}} {% endraw %} ",
      "size": "{% raw %} {{size}}{{^size}}10{{/size}} {% endraw %} ",
      "query": {
        "range": {
          "petal_length_in_cm": {
            "gte": "{% raw %} {{min_length}} {% endraw %} ",
            "lte": "{% raw %} {{max_length}} {% endraw %} "
          }
        }
      }
    }
  }
}

{% include copy-curl.html %}

다음으로, generation_type을 user_templates로 설정하고 search_templates 매개변수에 각 템플릿의 template_id와 template_description을 제공하여 에이전트를 등록하세요.

POST /_plugins/_ml/agents/_register
{
  "name": "Agentic Search with Claude 4",
  "type": "flow",
  "description": "A test agent for query planning.",
  "tools": [
    {
      "type": "QueryPlanningTool",
      "description": "A general tool to answer any question",
      "parameters": {
        "model_id": "ANiSxJgBOh0h20Y9XYXl",
        "generation_type": "user_templates",
        "search_templates": [
          {
            "template_id": "flower_species_search_template",
            "template_description": "This template searches for flowers that match the given species using a match query."
          },
          {
            "template_id": "flower_petal_length_range_template",
            "template_description": "This template searches for flowers within a specific petal length range using a range query."
          }
        ]
      }
    }
  ]
}

{% include copy-curl.html %}

LLM은 template_description을 유일한 컨텍스트로 사용하여 사용자가 제공한 question을 기반으로 OpenSearch DSL 쿼리를 생성할 때 사용할 최상의 템플릿을 선택해요. LLM이 적절한 선택을 할 수 있도록 템플릿에 대한 좋은 설명을 제공해야 해요. LLM은 템플릿 변수를 직접 채우거나 템플릿을 렌더링하지 않는다는 점에 유의하세요. 대신 템플릿의 쿼리 구조를 분석하고 이를 가이드로 사용하여 새롭고 상황에 맞는 OpenSearch DSL 쿼리를 생성해요.

매개변수 설명은 등록 매개변수를 참조하세요.

OpenSearch는 에이전트 ID로 응답해요.

{
  "agent_id": "RNjQi5gBOh0h20Y9-RX1"
}

4단계: 에이전트 실행

다음 요청을 전송하여 에이전트를 실행하세요.

POST /_plugins/_ml/agents/RNjQi5gBOh0h20Y9-RX1/_execute
{
  "parameters": {
    "question": "How many iris flowers of type setosa are there?",
    "index_name": "iris-index"
  }
}

{% include copy-curl.html %}

OpenSearch는 생성된 쿼리 DSL을 포함한 추론 결과를 반환해요.

{
  "inference_results": [
    {
      "output": [
        {
          "name": "response",
          "result": "{'query':{'term':{'species':'setosa'}}}"
        }
      ]
    }
  ]
}

등록 매개변수

다음 표는 에이전트를 등록할 때 사용할 수 있는 모든 도구 매개변수를 나열해요.

매개변수 유형 필수/선택 설명
model_id String 필수 DSL 쿼리를 생성하는 데 사용되는 LLM의 모델 ID예요. conversational 에이전트 내에서 사용될 때 이 값이 제공되지 않으면 에이전트 자체의 llm.model_id가 기본적으로 사용돼요.
response_filter String 선택 사항 LLM 응답에서 생성된 쿼리를 추출하는 데 사용되는 JSONPath 표현식이에요.
generation_type String 선택 사항 쿼리 생성 방식을 결정해요. llmGenerated를 사용하면 LLM 내장 지식에만 의존하고, user_templates를 사용하면 미리 정의된 검색 템플릿을 제공하여 일관된 결과를 위한 쿼리 생성을 안내해요. 기본값은 llmGenerated예요.
query_planner_system_prompt String 선택 사항 LLM에 높은 수준의 지침을 제공하는 시스템 프롬프트예요.
query_planner_user_prompt String 선택 사항 자연어 질문과 컨텍스트가 쿼리 생성을 위해 LLM에 어떻게 제시되는지 정의하는 사용자 프롬프트 템플릿이에요.
search_templates Array 선택 사항 generation_type이 user_templates인 경우에만 적용 가능해요. LLM에 쿼리 DSL 생성을 위한 미리 정의된 쿼리 패턴을 제공하는 검색 템플릿 목록이에요. 각 템플릿은 template_id(고유 식별자)와 template_description(템플릿의 목적과 사용 사례를 설명하여 LLM이 적절히 선택하도록 도움)을 포함해야 해요.
fallback_query String 선택 사항 LLM이 주어진 쿼리 텍스트에 대해 유효한 DSL 쿼리를 생성하지 못할 경우 사용되는 OpenSearch 쿼리 DSL이에요. 폴백 동작을 참조하세요.

커넥터나 에이전트 등록에서 구성된 모든 매개변수는 에이전트 실행 중에 재정의될 수 있어요. {: .note}

응답 필터 구성

response_filter 매개변수는 JSONPath 표현식을 사용하여 LLM 응답에서 생성된 쿼리를 추출해요. 모델 제공자마다 응답 형식이 다르므로 모델 유형에 맞는 적절한 필터를 지정해야 해요.

OpenAI 모델:

"response_filter": "$.choices[0].message.content"

{% include copy.html %}

Anthropic Claude 모델 (Amazon Bedrock Converse API):

"response_filter": "$.output.message.content[0].text"

{% include copy.html %}

실행 매개변수

QueryPlanningTool은 다음 실행 매개변수를 허용해요.

매개변수 유형 필수/선택 설명
question String 필수 OpenSearch DSL을 생성하는 데 필요한 모든 컨텍스트가 포함된 완전한 자연어 쿼리예요. 질문, 특정 요구 사항, 필터 또는 제약 조건을 포함하세요. 예: 가격이 100달러보다 큰 모든 제품 찾기, 2023년에 출판된 머신러닝에 관한 문서 보여줘, 상태가 활성이고 나이가 25세에서 35세 사이인 사용자 검색.
index_name String 필수 쿼리를 생성해야 하는 인덱스의 이름이에요.
embedding_model_id String 선택 사항 의미 검색을 수행하는 데 사용되는 모델 ID예요.

프롬프트 사용자 지정

자체 query_planner_system_prompt와 query_planner_user_prompt를 제공하여 LLM이 OpenSearch DSL 쿼리를 생성하는 방식을 사용자 지정할 수 있어요.

사용자 지정 프롬프트를 만들 때 에이전틱 검색과 제대로 작동하도록 명확한 출력 형식 규칙을 포함해야 해요. 시스템 프롬프트는 LLM이 추가 텍스트, 코드 펜스 또는 설명 없이 유효한 JSON 객체만 반환하도록 지정해야 해요. {: .important}

사용자 지정 프롬프트 구성: 에이전트의 도구 등록 중에 다음과 같이 사용자 지정 프롬프트를 제공하세요.

POST /_plugins/_ml/agents/_register
{
  "name": "Flow Agent for Agentic Search",
  "type": "flow",
  "description": "Flow agent for agentic search",
  "tools": [
    {
      "type": "QueryPlanningTool",
      "parameters": {
        "model_id": "your_model_id",
        "response_filter": "<response-filter-based-on-model-type>",
        "query_planner_system_prompt": "<YOUR CUSTOM SYSTEM PROMPT>",
        "query_planner_user_prompt": "<YOUR CUSTOM USER PROMPT>"
      }
    }
  ]
}

{% include copy-curl.html %}

모델 유형에 따라 적절한 response_filter를 사용하세요. 자세한 내용과 예제는 응답 필터 구성을 참조하세요. {: .note}

다음은 기본 시스템 프롬프트예요.

프롬프트 {: .text-delta}
==== PURPOSE ====
You are an OpenSearch DSL expert. Convert a natural-language question into a strict JSON OpenSearch query body.

==== RULES ====
Use only fields present in the provided mapping; never invent names.
Choose query types based on user intent and field types:

match: single-token full-text on analyzed text fields.

match_phrase: multi-token phrases on analyzed text fields (search string contains spaces, hyphens, commas, etc.).

multi_match: when multiple analyzed text fields are equally relevant.

term / terms: exact match on keyword, numeric, boolean.

range: numeric/date comparisons (gt, lt, gte, lte).

bool with must, should, must_not, filter: AND/OR/NOT logic.

wildcard / prefix on keyword: "starts with" / pattern matching.

exists: field presence/absence.

nested query / nested agg: ONLY if the mapping for that exact path (or a parent) has "type":"nested".

neural: semantic similarity on a 'semantic' or 'knn_vector' field (dense). Use "query_text" and "k"; include "model_id" unless bound in mapping.

neural (top-level): allowed when it's the only relevance clause needed; otherwise wrap in a bool when combining with filters/other queries.

Mechanics:

Put exact constraints (term, terms, range, exists, prefix, wildcard) in bool.filter (non-scoring). Put full-text relevance (match, match_phrase, multi_match) in bool.must.

Top N items/products/documents: return top hits (set "size": N as an integer) and sort by the relevant metric(s). Do not use aggregations for item lists.

Neural retrieval size: set "k" ≥ "size" (e.g. heuristic, k = max(size*5, 100) and k<=ef_search).

Spelling tolerance: match_phrase does NOT support fuzziness; use match or multi_match with "fuzziness": "AUTO" when tolerant matching is needed.

Text operators (OR vs AND): default to OR for natural-language queries; to tighten, use minimum_should_match (e.g., "75%"). Use AND only when every token is essential; if order/adjacency matters, use match_phrase.

Numeric note: use ONLY integers for size and k (not floats).

Aggregations (counts, averages, grouped summaries, distributions):

Use aggregations when the user asks for grouped summaries (e.g., counts by category, averages by brand, or top N categories/brands).

terms on field.keyword or numeric for grouping / top N groups (not items).

Metric aggs (avg, min, max, sum, stats, cardinality) on numeric fields.

date_histogram, histogram, range for distributions.

Always set "size": 0 when only aggregations are needed.

Use sub-aggregations + order for "top N groups by metric".

If grouping/filtering exactly on a text field, use its .keyword sub-field when present.

DATE RULES

Use range on date/date_nanos in bool.filter.

Emit ISO 8601 UTC ('Z') bounds; don't set time_zone for explicit UTC. (now is UTC)

Date math: now±N{y|M|w|d|h|m|s}.

Rounding: "/UNIT" floors to start (now/d, now/w, now/M, now/y).

End boundaries: prefer the next unit’s start.

Formats: only add "format" when inputs aren’t default; epoch_millis allowed.

Buckets: use date_histogram with calendar_interval or fixed_interval.

NEURAL / SEMANTIC SEARCH
When to use: conceptual/semantic intent, or when user asks for semantic/neural/vector/embedding search.
When not to use: purely structured/exact queries, or when no semantic/knn_vector field or model_id is available.
How to query:

Use the "neural" clause against the chosen field.

Required: "query_text" and "k".

Model rules:

For "semantic" fields, omit model_id unless overriding.

For "knn_vector", include model_id unless default is bound.

If no model id, do not generate neural clause.

Top-level allowed if no filters/other queries. Otherwise wrap in bool with filters in bool.filter.

Size: set "k" ≥ "size" (heuristic: k = max(size*5, 100)).

FIELD SELECTION & PROXYING
Goal: pick the smallest set of mapping fields that best capture the user's intent.

When provided, and present in the mapping, prioritize query_fields.

Proxy Rule: If at least one field is loosely related, proceed with the best proxy; do NOT fallback to match_all due to ambiguity.

Steps: harvest candidates, pick mapping fields, ignore irrelevant ones.

Micro Self-Check: verify fields exist; if not, swap to proxies. Only if no relevant fields exist at all, fallback to match_all.

==== OUTPUT FORMAT ====

Return EXACTLY ONE JSON object (valid OpenSearch request body).

No escapes, no code fences, no quotes around the whole object.

If nothing relevant exists, return exactly:
{"size":10,"query":{"match_all":{}}}

==== EXAMPLES ====
(Then follows Examples 1–13 exactly as in your original text, but without escapes.)

==== TEMPLATE USE ====
Use this search template provided by the user as reference to generate the query: ${parameters.template}
Note that this template might contain terms that are not relevant to the question at hand; in that case ignore the template.

다음은 기본 사용자 프롬프트예요.

Question: ${parameters.question}
Mapping: ${parameters.index_mapping:-}
Query Fields: ${parameters.query_fields:-}
Sample Document from index: ${parameters.sample_document:-}
In UTC: ${parameters.current_time:-} format: yyyy-MM-dd'T'HH:mm:ss'Z'
Embedding Model ID for Neural Search: ${parameters.embedding_model_id:- not provided}

==== OUTPUT ====
GIVE THE OUTPUT PART ONLY IN YOUR RESPONSE (a single JSON object)
Output:

폴백 동작

QueryPlanningTool은 LLM이 유효한 쿼리 DSL을 생성하지 못할 때 폴백 쿼리를 사용해요. 기본적으로 폴백 쿼리는 {"size":10,"query":{"match_all":{}}}예요. 에이전트를 등록할 때 사용자 지정 fallback_query 매개변수를 지정하여 이 기본값을 재정의할 수 있어요.

도구는 LLM 응답에서 첫 번째 유효한 JSON 객체를 자동으로 추출해요. JSON이 추가 텍스트, 마크다운 코드 펜스, 설명 또는 기타 콘텐츠로 둘러싸여 있어도 추출해요. 그러나 응답에서 유효한 JSON을 추출할 수 없는 경우(예: 응답이 완전히 비어 있거나, JSON이 아닌 텍스트만 포함하거나, 잘못된 JSON만 포함하는 경우) 도구는 폴백 쿼리(기본값 또는 사용자 지정 쿼리)를 반환해요.

폴백이 트리거되면 오류가 발생하지 않아요. 대신 시스템 로그에 디버그 로그가 표시돼요. 이는 LLM이 예상치 못한 출력을 제공하더라도 쿼리 계획 작업이 계속 작동하도록 보장해요.

기본 폴백 쿼리 재정의

다음 예제는 폴백 쿼리가 어떻게 작동하는지 보여줘요.

이 예제를 따르려면 먼저 에이전틱 검색 튜토리얼의 1~3단계를 완료하세요: 인덱스 생성, 데이터 수집, 모델 등록.

다음으로, 3단계의 모델 ID를 사용하여 에이전트를 등록하세요. 폴백 동작을 보여주기 위해 사용자 지정 fallback_query 매개변수를 포함하세요.

POST _plugins/_ml/agents/_register
{
  "name": "Iris Search Agent with Fallback",
  "type": "flow",
  "tools": [
    {
      "type": "QueryPlanningTool",
      "parameters": {
        "model_id": "<your-model-id>",
        "fallback_query": "{\"size\":10,\"query\":{\"bool\":{\"should\":[{\"match\":{\"species\":{\"query\":\"${parameters.question}\",\"fuzziness\":\"AUTO\"}}},{\"match_all\":{\"boost\":0.1}}],\"minimum_should_match\":1}}}"
      }
    }
  ]
}

{% include copy-curl.html %}

다음으로, 이전 단계의 에이전트 ID를 사용하여 검색 파이프라인을 생성하세요.

PUT _search/pipeline/agentic_search_pipeline
{
  "request_processors": [
    {
      "agentic_query_translator": {
        "agent_id": "<your-agent-id>"
      }
    }
  ],
  "response_processors": [
    {
      "agentic_context": {
        "dsl_query": true
      }
    }
  ]
}

{% include copy-curl.html %}

폴백 동작을 테스트하려면 iris-index와 관련 없는 질문으로 검색 요청을 보내세요.

POST /iris-index/_search?search_pipeline=agentic_search_pipeline&pretty
{
  "query": {
    "agentic": {
      "query_text": "Find all employees hired in 2023 with salary above 100000"
    }
  }
}

{% include copy-curl.html %}

응답에는 폴백 쿼리를 포함하는 ext 섹션의 dsl_query 필드가 포함돼요.

{
  "took" : 5396,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 2,
      "relation" : "eq"
    },
    "max_score" : 0.1,
    "hits" : [
      {
        "_index" : "iris-index",
        "_id" : "1",
        "_score" : 0.1,
        "_source" : {
          "petal_length_in_cm" : 1.4,
          "petal_width_in_cm" : 0.2,
          "sepal_length_in_cm" : 5.1,
          "sepal_width_in_cm" : 3.5,
          "species" : "setosa"
        }
      },
      {
        "_index" : "iris-index",
        "_id" : "2",
        "_score" : 0.1,
        "_source" : {
          "petal_length_in_cm" : 4.5,
          "petal_width_in_cm" : 1.5,
          "sepal_length_in_cm" : 6.4,
          "sepal_width_in_cm" : 2.9,
          "species" : "versicolor"
        }
      }
    ]
  },
  "ext" : {
    "dsl_query" : "{\"size\":10,\"query\":{\"bool\":{\"should\":[{\"match\":{\"species\":{\"query\":\"Find all employees hired in 2023 with salary above 100000\",\"fuzziness\":\"AUTO\"}}},{\"match_all\":{\"boost\":0.1}}],\"minimum_should_match\":1}}}"
  }
}

다음으로, iris-index와 관련된 질문을 하세요.

POST /iris-index/_search?search_pipeline=agentic_search_pipeline
{
  "query": {
    "agentic": {
      "query_text": "Find all setosa species"
    }
  }
}

{% include copy-curl.html %}

응답에는 폴백 쿼리 대신 적절한 LLM 생성 쿼리가 포함돼요.

{
  "took" : 4037,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 1,
      "relation" : "eq"
    },
    "max_score" : 0.0,
    "hits" : [
      {
        "_index" : "iris-index",
        "_id" : "1",
        "_score" : 0.0,
        "_source" : {
          "petal_length_in_cm" : 1.4,
          "petal_width_in_cm" : 0.2,
          "sepal_length_in_cm" : 5.1,
          "sepal_width_in_cm" : 3.5,
          "species" : "setosa"
        }
      }
    ]
  },
  "ext" : {
    "dsl_query" : "{\"query\":{\"bool\":{\"filter\":[{\"term\":{\"species.keyword\":\"setosa\"}}]}}}"
  }
}

도구 테스트

이 도구는 에이전트 워크플로의 일부로 실행하거나 도구 실행 API를 사용하여 독립적으로 실행할 수 있어요. 도구 실행 API는 개별 도구를 테스트하거나 독립 실행형 작업을 수행하는 데 유용해요.

관련 문서

더 알아보기 (Learn more)