Data retrieval guide (full-text, vector, and hybrid search)

Updated at:

Agentic ES Agentic ES supports five retrieval modes: exact filtering, full-text tokenized search, vector semantic search, hybrid search (RRF), and wildcard matching. They differ in whether they test conditions, match keywords, match semantics, or match code patterns. Every query must specify a slice scope; the recall and latency of vector search are tuned with the visit_percentage and rescore_vector parameters.

Note

All API examples in this topic provide CONSOLE / CURL / GO / PYTHON / JAVASCRIPT / JAVA code tabs (CONSOLE can be copied directly into Kibana Dev Tools). All SDK examples reuse the Quick start-created demo-knowledge-chunks collection and sample data.

1. Choose among the five retrieval modes?

If you are unsure which Query DSL to use, pick the mode that matches your scenario:

Business need

Recommended query

Recommended field type

How it works in one sentence

Filter by tag, status, category, time, or price range

(Example: only documents with category = "after-sales" after-sales documents)

term / terms / range

(placed in bool.filter )

keyword, long, double, date, boolean

It behaves exactly like a database WHERE clause: it only tests “whether the condition holds”, It does not compute relevance scores, so it is the fastest and cacheable.

Search titles or bodies by the words the user typed

(Example: search for “Refund policy”, and find documents containing those words)

match / multi_match / match_phrase

text

The system tokenizes sentences, finds documents containing those words, and ranks them by term frequency and match degree (BM25).

Filter by “similar meaning”knowledge bases by similar meaning (AI semantic search)

(Example: a user searches for “I bought the wrong item, how do I get a refund”, and hits “7-day no-reason return policy”)

top-level knn

dense_vector

The application converts text into vectors with an AI Embedding model, and the server returns the Top-K records with the nearest vector distance.

Exact matches on proper nouns (model/ID numbers) plus semantic synonyms

(RAG (most common in RAG knowledge bases)

retriever + rrf (hybrid search)

text + dense_vector

runs both “keyword search”and“vector search”, then merges the two rankings with the RRF (Reciprocal Rank Fusion) algorithm, balancing literal precision and semantic recall without manual score weighting.

Search by *wildcard*, prefix, or regex to search codes or paths

(Example: product code *iph*16*)

wildcard / prefix / regexp

  • Wildcard/regex: wildcard

  • Prefix queries: enable index_prefixes text (or search_as_you_type / wildcard)

  • Agentic ES Agentic ES enables query performance protection by default (search.allow_expensive_queries = false), to prevent plain keyword/text field triggers a full dictionary scan (running it directly returns 400);

  • Choose the dedicated field types per requirement for fast execution (see Section 5).

2. Scope queries (single slice and multiple slices)

Every query must tell the server which slice to search. You can query a single slice or several slices separated by commas:

CONSOLE

POST /demo-knowledge-chunks/_search?_slice=kb-a,kb-b&allow_partial_search_results=false
{
  "query": { "match_all": {} },
  "_source": ["title", "category"]
}

CURL

curl -u "$ES_USER:$ES_PASSWORD" -X POST \
  "$ES_ENDPOINT/demo-knowledge-chunks/_search?_slice=kb-a,kb-b&allow_partial_search_results=false" \
  -H 'Content-Type: application/json' \
  --data '{"query":{"match_all":{}},"_source":["title","category"]}'

GO

res, err := client.Search().
	Index("demo-knowledge-chunks").
	Routing("kb-a,kb-b").
	AllowPartialSearchResults(false).
	Query(&types.Query{MatchAll: &types.MatchAllQuery{}}).
	SourceIncludes_("title", "category").
	Do(ctx)
if err != nil {
	log.Fatal(err)
}
fmt.Println(res.Hits.Hits)

PYTHON

res = client.search(
    index="demo-knowledge-chunks",
    routing="kb-a,kb-b",
    allow_partial_search_results=False,
    query={"match_all": {}},
    source=["title", "category"],
)
print(res["hits"]["hits"])

JAVASCRIPT

const res = await client.search({
  index: 'demo-knowledge-chunks',
  routing: 'kb-a,kb-b',
  allow_partial_search_results: false,
  query: { match_all: {} },
  _source: ['title', 'category'],
})
console.log(res.hits.hits)

JAVA

SearchResponse<Map> res = client.search(s -> s
    .index("demo-knowledge-chunks")
    .routing("kb-a,kb-b")
    .allowPartialSearchResults(false)
    .query(q -> q.matchAll(m -> m))
    .source(src -> src.filter(f -> f.includes("title", "category"))),
    Map.class);
System.out.println(res.hits().hits());

Query scope parameter rules:

  1. _slice and routing are equivalent and mutually exclusive: URL parameter _slice and the official SDK routing parameter behave identically (both select the business slice). Pass only one per request; passing both returns 400.

  2. Explicitly specify query slices: For multi-slice queries, list slice names separated by commas (for example, kb-a,kb-b), to keep the search scope explicit and controllable; passing _slice=_all returns 400. By default, if any Slice in the list does not exist, the whole request returns 404; If the query list may include slices that are not yet written or already deleted, append ignore_missing_slice=true to skip missing slices.

  3. Platform-managed routing: Query routing is optimized automatically by Agentic ES; do not pass routing control parameters in requests (passing _msearch in the request header of preference returns 400; URL parameter preference is ignored by the platform and returns a Warning response header).

  4. When you can omit _slice: You can omit it only when the Collection was created with a default slice (such as "default_slice": "main"), can you omit _slice (, queries default to the main slice). If no default slice is configured, omitting _slice returns 400.

  5. Add a timeout parameter to guard against slow queries: For latency-sensitive online search, add a server-side timeout (such as ?timeout=2s or pass "timeout": "2s"), combine it with short client timeouts and separate read/write connection pools so that individual slow queries do not hold the 16 concurrency slots of a single slice (see Data write and SDK integration guide).

3. Vector search (KNN) and hybrid search (RRF)

3.1 Vector KNN search with filters

In real workloads you typically need to “filter by category or permission first, then find the top K most similar vectors among the matching documents”. Just add a knn add a filter clause:

CONSOLE

POST /demo-knowledge-chunks/_search?_slice=kb-a&allow_partial_search_results=false
{
  "knn": {
    "field": "embedding",
    "query_vector": [0.80, 0.12, 0.05, 0.03],
    "k": 2,
    "num_candidates": 10,
    "filter": {
      "term": { "category": "after-sales" }
    }
  },
  "_source": ["title", "category"]
}

CURL

curl -u "$ES_USER:$ES_PASSWORD" -X POST \
  "$ES_ENDPOINT/demo-knowledge-chunks/_search?_slice=kb-a&allow_partial_search_results=false" \
  -H 'Content-Type: application/json' \
  --data-binary @- <<'JSON'
{
  "knn": {
    "field": "embedding",
    "query_vector": [0.80, 0.12, 0.05, 0.03],
    "k": 2,
    "num_candidates": 10,
    "filter": {
      "term": { "category": "after-sales" }
    }
  },
  "_source": ["title", "category"]
}
JSON

GO

res, err := client.Search().
	Index("demo-knowledge-chunks").
	Routing("kb-a").
	AllowPartialSearchResults(false).
	Knn(&types.KnnSearch{
		Field:         "embedding",
		QueryVector:   []float32{0.80, 0.12, 0.05, 0.03},
		K:             some.Int(2),
		NumCandidates: some.Int(10),
		Filter:        []types.Query{{Term: map[string]types.TermQuery{"category": {Value: "after-sales"}}}},
	}).
	SourceIncludes_("title", "category").
	Do(ctx)
if err != nil {
	log.Fatal(err)
}
fmt.Println(res.Hits.Hits)

PYTHON

res = client.search(
    index="demo-knowledge-chunks",
    routing="kb-a",
    allow_partial_search_results=False,
    knn={
        "field": "embedding",
        "query_vector": [0.80, 0.12, 0.05, 0.03],
        "k": 2,
        "num_candidates": 10,
        "filter": {"term": {"category": "after-sales"}},
    },
    source=["title", "category"],
)
print(res["hits"]["hits"])

JAVASCRIPT

const res = await client.search({
  index: 'demo-knowledge-chunks',
  routing: 'kb-a',
  allow_partial_search_results: false,
  knn: {
    field: 'embedding',
    query_vector: [0.80, 0.12, 0.05, 0.03],
    k: 2,
    num_candidates: 10,
    filter: { term: { category: 'after-sales' } },
  },
  _source: ['title', 'category'],
})
console.log(res.hits.hits)

JAVA

SearchResponse<Map> res = client.search(s -> s
    .index("demo-knowledge-chunks")
    .routing("kb-a")
    .allowPartialSearchResults(false)
    .knn(k -> k
        .field("embedding")
        .queryVector(0.80f, 0.12f, 0.05f, 0.03f)
        .k(2)
        .numCandidates(10)
        .filter(f -> f.term(t -> t.field("category").value("after-sales"))))
    .source(src -> src.filter(f -> f.includes("title", "category"))),
    Map.class);
System.out.println(res.hits().hits());

Vector search parameter reference:

  • k and num_candidates: k is the number of nearest neighbors finally returned; when the DiskBBQ visit_percentage is at its default 0 with rescoring enabled (default oversample = 10.0), the approximate-search candidate size is max(num_candidates, k × rescore_vector.oversample). in bbq_disk, num_candidates exceeds k × oversample has little effect on the scan range (for example, k=2, default oversample=10, num_candidates from 10 to 20, the effective candidate count remains 20); To noticeably improve recall, increase visit_percentage or rescore_vector.oversample, see Section 3.3.

  • knn.filter (pre-filtering): conditions in knn.filter take effect during vector comparison, avoiding the “fetching Top-K first and then filtering, which returns fewer than K results”.

  • Cosine similarity score (_score) How to read it: Elasticsearch maps the cosine similarity in [-1, 1], i.e. cosθ, into _score = (1 + cosθ) / 2 (range [0, 1], the closer to 1 means more similar). To convert back to the cosine distance in [0, 2], use the formula distance = 2 * (1 - _score).

  • Always use /_search endpoint for KNN search: Call the standard /_search API and pass knn (and seamlessly combines with knn.filter filters; to fuse full-text keywords with vector search, use retriever.rrf).

3.2 full-text + hybrid search (RRF)

Keyword search excels at exact matches on proper nouns (such as model numbers or order IDs), while vector search understands synonyms and colloquial expressions. However, raw BM25 scores (which may range from fractions to tens) and cosine similarity scores (fixed in [0, 1])) have completely different scales, so adding them directly lets one route dominate.

Through the retriever in the rrf (Reciprocal Rank Fusion), the server runs keyword search (standard) and vector search (knn), rank-based fusion that ignores raw score magnitudes — It takes the top-ranked results of each route and computes a fused score by 1 / (rank_constant + rank) and aggregates the fused scores for sorting. No manual weight tuning is needed; documents that rank high on both routes automatically come first:

CONSOLE

POST /demo-knowledge-chunks/_search?_slice=kb-a&allow_partial_search_results=false
{
  "retriever": {
    "rrf": {
      "retrievers": [
        {
          "standard": {
            "query": {
              "bool": {
                "must": [{ "match": { "title": "refund" } }],
                "filter": [{ "term": { "category": "after-sales" } }]
              }
            }
          }
        },
        {
          "knn": {
            "field": "embedding",
            "query_vector": [0.80, 0.12, 0.05, 0.03],
            "k": 5,
            "num_candidates": 20,
            "filter": { "term": { "category": "after-sales" } }
          }
        }
      ],
      "rank_window_size": 10,
      "rank_constant": 60
    }
  },
  "size": 5,
  "_source": ["title", "category"]
}

CURL

curl -u "$ES_USER:$ES_PASSWORD" -X POST \
  "$ES_ENDPOINT/demo-knowledge-chunks/_search?_slice=kb-a&allow_partial_search_results=false" \
  -H 'Content-Type: application/json' \
  --data-binary @- <<'JSON'
{
  "retriever": {
    "rrf": {
      "retrievers": [
        {
          "standard": {
            "query": {
              "bool": {
                "must": [{ "match": { "title": "refund" } }],
                "filter": [{ "term": { "category": "after-sales" } }]
              }
            }
          }
        },
        {
          "knn": {
            "field": "embedding",
            "query_vector": [0.80, 0.12, 0.05, 0.03],
            "k": 5,
            "num_candidates": 20,
            "filter": { "term": { "category": "after-sales" } }
          }
        }
      ],
      "rank_window_size": 10,
      "rank_constant": 60
    }
  },
  "size": 5,
  "_source": ["title", "category"]
}
JSON

GO

res, err := client.Search().
	Index("demo-knowledge-chunks").
	Routing("kb-a").
	AllowPartialSearchResults(false).
	Retriever(&types.RetrieverContainer{
		Rrf: &types.RRFRetriever{
			Retrievers: []types.RRFRetrieverEntry{
				// full-text search + scalar filter
				types.RetrieverContainer{
					Standard: &types.StandardRetriever{
						Query: &types.Query{
							Bool: &types.BoolQuery{
								Must:   []types.Query{{Match: map[string]types.MatchQuery{"title": {Query: "refund"}}}},
								Filter: []types.Query{{Term: map[string]types.TermQuery{"category": {Value: "after-sales"}}}},
							},
						},
					},
				},
				// vector search + scalar filter
				types.RetrieverContainer{
					Knn: &types.KnnRetriever{
						Field:         "embedding",
						QueryVector:   []float32{0.80, 0.12, 0.05, 0.03},
						K:             5,
						NumCandidates: some.Int(20),
						Filter:        []types.Query{{Term: map[string]types.TermQuery{"category": {Value: "after-sales"}}}},
					},
				},
			},
			RankWindowSize: some.Int(10),
			RankConstant:   some.Int(60),
		},
	}).
	Size(5).
	SourceIncludes_("title", "category").
	Do(ctx)
if err != nil {
	log.Fatal(err)
}
fmt.Println(res.Hits.Hits)

PYTHON

res = client.search(
    index="demo-knowledge-chunks",
    routing="kb-a",
    allow_partial_search_results=False,
    retriever={
        "rrf": {
            "retrievers": [
                {
                    "standard": {
                        "query": {
                            "bool": {
                                "must": [{"match": {"title": "refund"}}],
                                "filter": [{"term": {"category": "after-sales"}}],
                            }
                        }
                    }
                },
                {
                    "knn": {
                        "field": "embedding",
                        "query_vector": [0.80, 0.12, 0.05, 0.03],
                        "k": 5,
                        "num_candidates": 20,
                        "filter": {"term": {"category": "after-sales"}},
                    }
                },
            ],
            "rank_window_size": 10,
            "rank_constant": 60,
        }
    },
    size=5,
    source=["title", "category"],
)
print(res["hits"]["hits"])

JAVASCRIPT

const res = await client.search({
  index: 'demo-knowledge-chunks',
  routing: 'kb-a',
  allow_partial_search_results: false,
  retriever: {
    rrf: {
      retrievers: [
        {
          standard: {
            query: {
              bool: {
                must: [{ match: { title: 'refund' } }],
                filter: [{ term: { category: 'after-sales' } }],
              },
            },
          },
        },
        {
          knn: {
            field: 'embedding',
            query_vector: [0.80, 0.12, 0.05, 0.03],
            k: 5,
            num_candidates: 20,
            filter: { term: { category: 'after-sales' } },
          },
        },
      ],
      rank_window_size: 10,
      rank_constant: 60,
    },
  },
  size: 5,
  _source: ['title', 'category'],
})
console.log(res.hits.hits)

JAVA

SearchResponse<Map> res = client.search(s -> s
    .index("demo-knowledge-chunks")
    .routing("kb-a")
    .allowPartialSearchResults(false)
    .retriever(r -> r.rrf(rrf -> rrf
        // full-text search + scalar filter
        .retrievers(e -> e.retriever(sub -> sub.standard(st -> st
            .query(q -> q.bool(b -> b
                .must(m -> m.match(mt -> mt.field("title").query("refund")))
                .filter(f -> f.term(t -> t.field("category").value("after-sales"))))))))
        // vector search + scalar filter
        .retrievers(e -> e.retriever(sub -> sub.knn(k -> k
            .field("embedding")
            .queryVector(0.80f, 0.12f, 0.05f, 0.03f)
            .k(5)
            .numCandidates(20)
            .filter(f -> f.term(t -> t.field("category").value("after-sales"))))))
        .rankWindowSize(10)
        .rankConstant(60)))
    .size(5)
    .source(src -> src.filter(f -> f.includes("title", "category"))),
    Map.class);
System.out.println(res.hits().hits());

RRF Key hybrid search parameters:

  • rank_window_size ((candidate set size per route): controls how many top results of each route (keyword and vector) participate in the fusion (must be greater than or equal to the outer size, typically size 2–5 times. For example, to return the top 5 documents, set rank_window_size to 10–25).

  • rank_constant ((smoothing constant, default 60): computes the per-route rank score 1 / (rank_constant + rank) as the smoothing baseline. The default 60 balances “very high rank on one route”and“high ranks on both routes”and balances "top ranks on one route" against "high ranks on both routes". You rarely need to change it.

  • Combine scalar filters in RRF: If both routes share the same scalar filter (such as category = "after-sales"), you can write the filter once at the top level of rrf.filter to apply one filter to both routes; if the two routes need different filter logic, write them separately under standard.query (bool.filter) and knn.filter; it also works with multi-slice queries (for example, ?_slice=kb-a,kb-b).

  • Syntax convention: Always use the standard retriever.rrf syntax for hybrid search.

3.3 DiskBBQ Tune vector recall (visit_percentage and rescore_vector)

Agentic ES vector indexes are built on bbq_disk (DiskBBQ):: at query time it first performs 1-bit compressed vector clusters on disk for fast coarse filtering (, greatly reducing memory and disk reads), then reads the raw float vectors of the selected candidates for exact rescoring.

Besides k and num_candidates, DiskBBQ has two key parameters that directly affect the recall/latency trade-off:

parameter

Stage

Default (Agentic ES)

Plain-language explanation and tuning tips

visit_percentage

(Collection default: default_visit_percentage)

Coarse filtering stage

((how many vector clusters are scanned)

0.0

(Value range: 0–100)

Controls the ratio of vector clusters scanned per shard.

• default 0, num_candidates derives the scan range;

• As long as the effective value is greater than 0, visit_percentage takes over the scan ratio, and num_candidates no longer controls the scan ratio;

• A larger value (for example, 2.0 → 5.0 → 10.0) the higher the recall, but disk reads and compute time also increase.

• You can set a default in the collection Mapping under index_options.default_visit_percentage sets the default; a per-query visit_percentage takes precedence (passing 0 switches back to num_candidates mode).

rescore_vector.oversample

Rescoring stage

((how many candidates are rescored with raw vectors)

10.0

(such as k=10 rescores 100 documents)

Coarse filtering uses 1-bit compressed vectors, so distances carry quantization error. In the rescoring stage, k × oversample candidates, reads their raw vectors to recompute exact similarities, and truncates to the top k documents.

• At query time you can set it to 0 (disables rescoring for the lowest latency but noticeably lower recall) or >= 1.0 (such as 5.0, 10.0, 15.0, 20.0, increasing it reduces quantization error and improves Top-K recall; note that decimals in (0, 1) return 400);

• the collection Mapping under index_options.rescore_vector.oversample already defaults to 10.0 (Mapping -level cap is 10.0), To use a larger oversample multiplier, pass it in the individual query.

Note
  1. Start with defaults: omit visit_percentage (via num_candidates) and keep the default rescore_vector.oversample = 10.0, balances low latency with high recall (see Performance benchmarks test conditions).

  2. When recall is insufficient: gradually increase visit_percentage (such as 2.0, 5.0, 10.0) to widen coarse coverage, then increase rescore_vector.oversample (such as 15.0, 20.0) to refine rescoring; the top-level top-level knn, retriever.knn and retriever.rrf inside the knn clauses all accept these two parameters.

Specify visit_percentage and rescore_vector

CONSOLE

POST /demo-knowledge-chunks/_search?_slice=kb-a&allow_partial_search_results=false
{
  "knn": {
    "field": "embedding",
    "query_vector": [0.80, 0.12, 0.05, 0.03],
    "k": 5,
    "visit_percentage": 10.0,
    "rescore_vector": {
      "oversample": 15.0
    },
    "filter": { "term": { "category": "after-sales" } }
  },
  "_source": ["title", "category"]
}

CURL

curl -u "$ES_USER:$ES_PASSWORD" -X POST \
  "$ES_ENDPOINT/demo-knowledge-chunks/_search?_slice=kb-a&allow_partial_search_results=false" \
  -H 'Content-Type: application/json' \
  --data-binary @- <<'JSON'
{
  "knn": {
    "field": "embedding",
    "query_vector": [0.80, 0.12, 0.05, 0.03],
    "k": 5,
    "visit_percentage": 10.0,
    "rescore_vector": {
      "oversample": 15.0
    },
    "filter": { "term": { "category": "after-sales" } }
  },
  "_source": ["title", "category"]
}
JSON

GO

res, err := client.Search().
	Index("demo-knowledge-chunks").
	Routing("kb-a").
	AllowPartialSearchResults(false).
	Knn(&types.KnnSearch{
		Field:           "embedding",
		QueryVector:     []float32{0.80, 0.12, 0.05, 0.03},
		K:               some.Int(5),
		VisitPercentage: some.Float32(10.0),
		RescoreVector:   &types.RescoreVector{Oversample: 15.0},
		Filter:          []types.Query{{Term: map[string]types.TermQuery{"category": {Value: "after-sales"}}}},
	}).
	SourceIncludes_("title", "category").
	Do(ctx)
if err != nil {
	log.Fatal(err)
}
fmt.Println(res.Hits.Hits)

PYTHON

res = client.search(
    index="demo-knowledge-chunks",
    routing="kb-a",
    allow_partial_search_results=False,
    knn={
        "field": "embedding",
        "query_vector": [0.80, 0.12, 0.05, 0.03],
        "k": 5,
        "visit_percentage": 10.0,
        "rescore_vector": {"oversample": 15.0},
        "filter": {"term": {"category": "after-sales"}},
    },
    source=["title", "category"],
)
print(res["hits"]["hits"])

JAVASCRIPT

const res = await client.search({
  index: 'demo-knowledge-chunks',
  routing: 'kb-a',
  allow_partial_search_results: false,
  knn: {
    field: 'embedding',
    query_vector: [0.80, 0.12, 0.05, 0.03],
    k: 5,
    visit_percentage: 10.0,
    rescore_vector: { oversample: 15.0 },
    filter: { term: { category: 'after-sales' } },
  },
  _source: ['title', 'category'],
})
console.log(res.hits.hits)

JAVA

SearchResponse<Map> res = client.search(s -> s
    .index("demo-knowledge-chunks")
    .routing("kb-a")
    .allowPartialSearchResults(false)
    .knn(k -> k
        .field("embedding")
        .queryVector(0.80f, 0.12f, 0.05f, 0.03f)
        .k(5)
        .visitPercentage(10.0f)
        .rescoreVector(rv -> rv.oversample(15.0f))
        .filter(f -> f.term(t -> t.field("category").value("after-sales"))))
    .source(src -> src.filter(f -> f.includes("title", "category"))),
    Map.class);
System.out.println(res.hits().hits());
Note

Collection-level default configuration example: To make all queries on a vector field use a higher scan ratio by default, or to change the default rescore multiplier (Mapping-level oversample value 0 or 1.0–10.0, already defaults to the cap 10.0; exceeds 10.0; pass larger values per query). You can specify it directly in the collection Mapping at creation:

"embedding": {
  "type": "dense_vector",
  "dims": 1024,
  "index": true,
  "similarity": "cosine",
  "index_options": {
    "type": "bbq_disk",
    "default_visit_percentage": 5.0,
    "rescore_vector": { "oversample": 10.0 }
  }
}

4. Aggregations, Scroll export, and batch queries (MSearch)

4.1 Count documents by category (terms aggregation)

To implement a database-like SELECT category, COUNT(*) GROUP BY category grouping, set "size": 0 ((do not return document hits, only statistics) and pass aggs:

CONSOLE

POST /demo-knowledge-chunks/_search?_slice=kb-a&allow_partial_search_results=false
{
  "size": 0,
  "aggs": {
    "by_category": {
      "terms": { "field": "category" }
    }
  }
}

CURL

curl -u "$ES_USER:$ES_PASSWORD" -X POST \
  "$ES_ENDPOINT/demo-knowledge-chunks/_search?_slice=kb-a&allow_partial_search_results=false" \
  -H 'Content-Type: application/json' \
  --data-binary @- <<'JSON'
{"size":0,"aggs":{"by_category":{"terms":{"field":"category"}}}}
JSON

GO

res, err := client.Search().
	Index("demo-knowledge-chunks").
	Routing("kb-a").
	AllowPartialSearchResults(false).
	Size(0).
	Aggregations(map[string]types.Aggregations{
		"by_category": {Terms: &types.TermsAggregation{Field: some.String("category")}},
	}).
	Do(ctx)
if err != nil {
	log.Fatal(err)
}
fmt.Println(res.Aggregations["by_category"])

PYTHON

res = client.search(
    index="demo-knowledge-chunks",
    routing="kb-a",
    allow_partial_search_results=False,
    size=0,
    aggs={"by_category": {"terms": {"field": "category"}}},
)
print(res["aggregations"]["by_category"]["buckets"])

JAVASCRIPT

const res = await client.search({
  index: 'demo-knowledge-chunks',
  routing: 'kb-a',
  allow_partial_search_results: false,
  size: 0,
  aggs: { by_category: { terms: { field: 'category' } } },
})
console.log(res.aggregations.by_category.buckets)

JAVA

SearchResponse<Map> res = client.search(s -> s
    .index("demo-knowledge-chunks")
    .routing("kb-a")
    .allowPartialSearchResults(false)
    .size(0)
    .aggregations("by_category", a -> a.terms(t -> t.field("category"))),
    Map.class);
System.out.println(res.aggregations().get("by_category").sterms().buckets().array());

4.2 Pagination and full export (Scroll)

  • Regular pagination for the first pages: Use from ((start offset) + size ((page size).

  • Deep pagination: For deep pagination, use sort with search_after, and append a business-unique field (such as a global UUID; for single-slice queries you may also duplicate the document ID) as a tiebreaker sort key (direct sorting by _id sorting).

  • Bulk export of all data (Scroll pitfalls to avoid):

    1. Explicitly include vector fields: By default, searches may omit large vector fields to save bandwidth. To include dense_vector fields, set the following in the first-page request: "_source": {"exclude_vectors": false}.

    2. Update _scroll_id: Each paged response may return a new _scroll_id, the next page fetch and the final release must both use returned by the latest response: _scroll_id.

    3. Release proactively after use: When the export finishes or is interrupted, call defer / finally call DELETE /_search/scroll to release the server-side cursor context.

CONSOLE

// 1. First-page request: URL parameters scroll=1m and _slice=kb-a; To export vector fields, set exclude_vectors: false
POST /demo-knowledge-chunks/_search?scroll=1m&_slice=kb-a
{
  "size": 100,
  "_source": { "exclude_vectors": false },
  "query": { "match_all": {} }
}

// 2. Subsequent pages: put the _scroll_id from the latest response in the request body and keep fetching until hits.hits is empty
POST /_search/scroll
{
  "scroll": "1m",
  "scroll_id": "<the _scroll_id returned by the latest response>"
}

// 3. After the export: release the scroll context
DELETE /_search/scroll
{
  "scroll_id": "<the _scroll_id returned by the latest response>"
}

CURL

# 1. First-page request: URL parameters scroll=1m and _slice=kb-a; To export vector fields, set exclude_vectors: false
curl -u "$ES_USER:$ES_PASSWORD" -X POST \
  "$ES_ENDPOINT/demo-knowledge-chunks/_search?scroll=1m&_slice=kb-a" \
  -H 'Content-Type: application/json' \
  --data '{"size":100,"_source":{"exclude_vectors":false},"query":{"match_all":{}}}'

# 2. Subsequent pages: put the _scroll_id from the latest response in the request body and keep fetching until hits.hits is empty
curl -u "$ES_USER:$ES_PASSWORD" -X POST \
  "$ES_ENDPOINT/_search/scroll" \
  -H 'Content-Type: application/json' \
  --data '{"scroll":"1m","scroll_id":"<the _scroll_id returned by the latest response>"}'

# 3. After the export: release the scroll context
curl -u "$ES_USER:$ES_PASSWORD" -X DELETE \
  "$ES_ENDPOINT/_search/scroll" \
  -H 'Content-Type: application/json' \
  --data '{"scroll_id":"<the _scroll_id returned by the latest response>"}'

GO

// Import github.com/elastic/go-elasticsearch/v9/typedapi/core/scroll
// 1. First-page request (ExcludeVectors: some.Bool(false) explicitly include vector fields)
firstPage, err := client.Search().
	Index("demo-knowledge-chunks").
	Routing("kb-a").
	Scroll("1m").
	Size(100).
	Source_(&types.SourceFilter{ExcludeVectors: some.Bool(false)}).
	Query(&types.Query{MatchAll: &types.MatchAllQuery{}}).
	Do(ctx)
if err != nil {
	log.Fatal(err)
}

scrollID := ""
if firstPage.ScrollId_ != nil {
	scrollID = *firstPage.ScrollId_
}
// 3. release the server-side context with the latest scrollID on exit
defer func() {
	if scrollID != "" {
		_, _ = client.ClearScroll().ScrollId(scrollID).Do(ctx)
	}
}()

// 2. Paginate until the current page Hits is empty, updating scrollID each time
hits := firstPage.Hits.Hits
for len(hits) > 0 {
	for _, hit := range hits {
		_ = hit.Source_
	}
	nextPage, err := client.Scroll().
		Request(&scroll.Request{ScrollId: scrollID, Scroll: "1m"}).
		Do(ctx)
	if err != nil {
		log.Fatal(err)
	}
	if nextPage.ScrollId_ != nil {
		scrollID = *nextPage.ScrollId_
	}
	hits = nextPage.Hits.Hits
}

PYTHON

# 1. First-page request (exclude_vectors=False explicitly include vector fields)
page = client.search(
    index="demo-knowledge-chunks",
    routing="kb-a",
    scroll="1m",
    size=100,
    source={"exclude_vectors": False},
    query={"match_all": {}},
)
scroll_id = page["_scroll_id"]

try:
    # 2. Paginate with the cursor until hits is empty, updating scroll_id each time
    while page["hits"]["hits"]:
        for hit in page["hits"]["hits"]:
            _ = hit["_source"]
        page = client.scroll(scroll_id=scroll_id, scroll="1m")
        scroll_id = page["_scroll_id"]
finally:
    # 3. clear the scroll context when the export ends or exits abnormally
    client.clear_scroll(scroll_id=scroll_id)

JAVASCRIPT

// 1. First-page request (exclude_vectors: false explicitly include vector fields)
let page = await client.search({
  index: 'demo-knowledge-chunks',
  routing: 'kb-a',
  scroll: '1m',
  size: 100,
  _source: { exclude_vectors: false },
  query: { match_all: {} },
})
let scrollId = page._scroll_id

try {
  // 2. Paginate with the cursor until hits is empty, updating scrollId each time
  while (page.hits.hits.length > 0) {
    for (const hit of page.hits.hits) {
      const source = hit._source
    }
    page = await client.scroll({ scroll_id: scrollId, scroll: '1m' })
    scrollId = page._scroll_id
  }
} finally {
  // 3. clear the scroll context when the export ends or exits abnormally
  if (scrollId) {
    await client.clearScroll({ scroll_id: scrollId })
  }
}

JAVA

// 1. First-page request (excludeVectors(false) to explicitly include vector fields)
SearchResponse<Map> firstPage = client.search(s -> s
    .index("demo-knowledge-chunks")
    .routing("kb-a")
    .scroll(t -> t.time("1m"))
    .size(100)
    .query(q -> q.matchAll(m -> m))
    .source(src -> src.filter(f -> f.excludeVectors(false))),
    Map.class);

String scrollId = firstPage.scrollId();
try {
    var hits = firstPage.hits().hits();
    while (!hits.isEmpty()) {
        // process the hits of the current page ...
        String currentScrollId = scrollId;
        ScrollResponse<Map> nextPage = client.scroll(
            sc -> sc.scrollId(currentScrollId).scroll(t -> t.time("1m")), Map.class);
        if (nextPage.scrollId() != null) {
            scrollId = nextPage.scrollId();
        }
        hits = nextPage.hits().hits();
    }
} finally {
    // 3. release the scroll cursor when the export ends or exits abnormally
    if (scrollId != null) {
        String idToClear = scrollId;
        client.clearScroll(c -> c.scrollId(idToClear));
    }
}

4.3 Batch multiple queries in one request (_msearch)

To query multiple slices or different conditions in a single network request, use _msearch. In the NDJSON request body, each sub-query consists of two lines: the first specifies "_slice" (or "routing"), the second carries the query body:

CONSOLE

POST /demo-knowledge-chunks/_msearch
{"_slice":"kb-a"}
{"query":{"match_all":{}}}
{"_slice":"kb-b"}
{"query":{"match_all":{}}}

CURL

curl -u "$ES_USER:$ES_PASSWORD" -X POST \
  "$ES_ENDPOINT/demo-knowledge-chunks/_msearch" \
  -H 'Content-Type: application/x-ndjson' \
  --data-binary @- <<'NDJSON'
{"_slice":"kb-a"}
{"query":{"match_all":{}}}
{"_slice":"kb-b"}
{"query":{"match_all":{}}}
NDJSON

GO

// Use RouteSlice to specify "_slice" as a string (avoids serializing Routing as an array)
mreq := client.Msearch().Index("demo-knowledge-chunks")
_ = mreq.AddSearch(
	types.MultisearchHeader{RouteSlice: some.String("kb-a")},
	types.SearchRequestBody{Query: &types.Query{MatchAll: &types.MatchAllQuery{}}},
)
_ = mreq.AddSearch(
	types.MultisearchHeader{RouteSlice: some.String("kb-b")},
	types.SearchRequestBody{Query: &types.Query{MatchAll: &types.MatchAllQuery{}}},
)
mres, err := mreq.Do(ctx)
if err != nil {
	log.Fatal(err)
}
for _, item := range mres.Responses {
	if errItem, ok := item.(*types.ErrorResponseBase); ok {
		log.Fatalf("sub-query failed: %v", errItem.Error)
	}
}

PYTHON

mres = client.msearch(
    index="demo-knowledge-chunks",
    searches=[
        {"routing": "kb-a"},
        {"query": {"match_all": {}}},
        {"routing": "kb-b"},
        {"query": {"match_all": {}}},
    ],
)
for item in mres["responses"]:
    assert "error" not in item, f"sub-query failed: {item['error']}"

JAVASCRIPT

const mres = await client.msearch({
  index: 'demo-knowledge-chunks',
  searches: [
    { routing: 'kb-a' },
    { query: { match_all: {} } },
    { routing: 'kb-b' },
    { query: { match_all: {} } },
  ],
})
for (const item of mres.responses) {
  if (item.error) throw new Error(`sub-query failed: ${JSON.stringify(item.error)}`)
}

JAVA

// Use routeSlice("kb-a") to specify "_slice" as a string (avoids serializing routing() as an array)
MsearchResponse<Map> mres = client.msearch(m -> m
    .index("demo-knowledge-chunks")
    .searches(s -> s
        .header(h -> h.routeSlice("kb-a"))
        .body(b -> b.query(q -> q.matchAll(ma -> ma))))
    .searches(s -> s
        .header(h -> h.routeSlice("kb-b"))
        .body(b -> b.query(q -> q.matchAll(ma -> ma)))),
    Map.class);
for (MultiSearchResponseItem<Map> item : mres.responses()) {
    if (item.isFailure()) {
        throw new IllegalStateException("sub-query failed: " + item.failure().error());
    }
}
Important

_msearch returns HTTP 200; always iterate over the responses array and check whether each sub-response contains error, and timed_out and _shards.failed.

5. Query performance protection (expensive queries) and query templates

5.1 Why some wildcard/prefix queries return 400? (expensive-query protection)

In a regular database, running LIKE '%iph%' triggers a full-table scan. Similarly, on a plain keyword or text field triggers a wildcard (wildcard), regex (regexp), fuzzy matching (fuzzy) or prefix queries (prefix), without a dedicated index structure, the engine must traverse huge dictionaries, which easily causes query timeouts.

Therefore, Agentic ES enables expensive-query protection by default (search.allow_expensive_queries = false), so that such expensive queries do not slow down the shared cluster. If your workload truly needs prefix, wildcard, or fuzzy matching, choose the field types optimized for them at collection creation for efficient execution:

query syntax

Why they return 400?

Recommended field type at creation (fast execution, returns 200)

wildcard (wildcard */?), regexp (regex), fuzzy (fuzzy matching);

match / multi_match with fuzziness;

query_string or the URL parameter q with *, ~, /regex/

keyword, text, flattened

Define the field type as wildcard (a dedicated index for substring and regex matching at any position)

prefix (prefix queries), match_bool_prefix

keyword, flattened;

without index_prefixes plain text

Option A: add text field with "index_prefixes": {}

Option B: use search_as_you_type or wildcard Field type

range (range queries)

keyword, text, flattened

numeric (long, double, etc.), date (date), IP (ip) fields with range queries

Any query

Fields with "index": false fields

Do not set "index": false

Example: *wildcard* and prefix search

// 1. At collection creation: set sku_code to wildcard for wildcard search, and add index_prefixes to title for prefix search
PUT /_slice_collection/demo-goods
{
  "default_slice": "main",
  "mappings": {
    "properties": {
      "sku_code": { "type": "wildcard" },
      "title": { "type": "text", "index_prefixes": {} }
    }
  }
}

// 2. At query time, wildcard, regexp, fuzzy, and prefix work normally (HTTP 200)
POST /demo-goods/_search
{
  "query": {
    "bool": {
      "must": [
        { "wildcard": { "sku_code": "*iph*16*" } },
        { "prefix": { "title": "iph" } }
      ]
    }
  }
}

5.2 Query templates (Mustache)

If a long query JSON is reused repeatedly with only the search terms or filters changing, save it as a parameterized query template (It supports standard mustache template syntax, similar to prepared statements in databases). To keep multi-tenant operation stable and secure, templates only substitute parameters and never execute dynamic script code:

  • Template ID naming rules: Length: 1–200 characters, may contain only lowercase letters a-z, digits 0-9 and ., _, - (uppercase letters return 400).

  • Template size limit: The template source must not exceed 10240 bytes (UTF-8) and cannot nest script definitions.

// 1. Save a query template
PUT /_scripts/kb_category_search
{
  "script": {
    "lang": "mustache",
    "source": {
      "query": {
        "term": { "category": "{{target_category}}" }
      }
    }
  }
}

// 2. Pass parameters to run a templated search
POST /demo-knowledge-chunks/_search/template?_slice=kb-a
{
  "id": "kb_category_search",
  "params": {
    "target_category": "after-sales"
  }
}

Read next: Migration guide, error codes, and FAQ or consult the Appendix: capability allowlist.

Related features

You can adopt the following advanced retrieval features per business scenario. Each topic includes selection guidance, parameter descriptions, and complete code examples: