Data retrieval guide (full-text, vector, and hybrid search)
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.
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 |
(placed in |
| It behaves exactly like a database |
Search titles or bodies by the words the user typed (Example: search for “Refund policy”, and find documents containing those words) |
|
| 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 |
| 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) |
|
| 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 (Example: product code |
|
|
|
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:
_sliceandroutingare equivalent and mutually exclusive: URL parameter_sliceand the official SDKroutingparameter behave identically (both select the business slice). Pass only one per request; passing both returns400.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=_allreturns400. By default, if any Slice in the list does not exist, the whole request returns404; If the query list may include slices that are not yet written or already deleted, appendignore_missing_slice=trueto skip missing slices.Platform-managed routing: Query routing is optimized automatically by Agentic ES; do not pass routing control parameters in requests (passing
_msearchin the request header ofpreferencereturns400; URL parameterpreferenceis ignored by the platform and returns aWarningresponse header).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 themainslice). If no default slice is configured, omitting_slicereturns400.Add a
timeoutparameter to guard against slow queries: For latency-sensitive online search, add a server-side timeout (such as?timeout=2sor pass"timeout": "2s"), combine it with short client timeouts and separate read/write connection pools so that individual slow queries do not hold the16concurrency 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"]
}
JSONGO
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:
kandnum_candidates:kis the number of nearest neighbors finally returned; when the DiskBBQvisit_percentageis at its default0with rescoring enabled (defaultoversample = 10.0), the approximate-search candidate size ismax(num_candidates, k × rescore_vector.oversample). inbbq_disk,num_candidatesexceedsk × oversamplehas little effect on the scan range (for example,k=2, defaultoversample=10,num_candidatesfrom10to20, the effective candidate count remains20); To noticeably improve recall, increasevisit_percentageorrescore_vector.oversample, see Section 3.3.knn.filter(pre-filtering): conditions inknn.filtertake 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 to1means more similar). To convert back to the cosine distance in[0, 2], use the formuladistance = 2 * (1 - _score).Always use
/_searchendpoint for KNN search: Call the standard/_searchAPI and passknn(and seamlessly combines withknn.filterfilters; to fuse full-text keywords with vector search, useretriever.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"]
}
JSONGO
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 outersize, typicallysize2–5times. For example, to return the top5documents, setrank_window_sizeto10–25).rank_constant((smoothing constant, default60): computes the per-route rank score1 / (rank_constant + rank)as the smoothing baseline. The default60balances “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 ofrrf.filterto apply one filter to both routes; if the two routes need different filter logic, write them separately understandard.query(bool.filter) andknn.filter; it also works with multi-slice queries (for example,?_slice=kb-a,kb-b).Syntax convention: Always use the standard
retriever.rrfsyntax 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 |
(Collection default: | Coarse filtering stage ((how many vector clusters are scanned) |
(Value range: | Controls the ratio of vector clusters scanned per shard. • default • As long as the effective value is greater than • A larger value (for example, • You can set a default in the collection Mapping under |
| Rescoring stage ((how many candidates are rescored with raw vectors) |
(such as | Coarse filtering uses • At query time you can set it to • the collection Mapping under |
Start with defaults: omit
visit_percentage(vianum_candidates) and keep the defaultrescore_vector.oversample = 10.0, balances low latency with high recall (see Performance benchmarks test conditions).When recall is insufficient: gradually increase
visit_percentage(such as2.0,5.0,10.0) to widen coarse coverage, then increaserescore_vector.oversample(such as15.0,20.0) to refine rescoring; the top-level top-levelknn,retriever.knnandretriever.rrfinside theknnclauses 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"]
}
JSONGO
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());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"}}}}
JSONGO
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
sortwithsearch_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_idsorting).Bulk export of all data (
Scrollpitfalls to avoid):Explicitly include vector fields: By default, searches may omit large vector fields to save bandwidth. To include
dense_vectorfields, set the following in the first-page request:"_source": {"exclude_vectors": false}.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.Release proactively after use: When the export finishes or is interrupted, call
defer/finallycallDELETE /_search/scrollto 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":{}}}
NDJSONGO
// 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());
}
}_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 | Recommended field type at creation (fast execution, returns |
|
| Define the field type as |
|
without | Option A: add Option B: use |
|
| numeric ( |
Any query | Fields with | Do not set |
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–200characters, may contain only lowercase lettersa-z, digits0-9and.,_,-(uppercase letters return400).Template size limit: The template source must not exceed
10240bytes (UTF-8) and cannot nestscriptdefinitions.
// 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:
Keyword and semantic hybrid search: RRF: fuses BM25 full-text search and vector KNN search in a single request without manual score weighting.
Vector search precision and speed tuning: DiskBBQ:: tune
visit_percentageandrescore_vector.oversample, to balance recall and latency.Wildcard and prefix fuzzy search: wildcard:: use
wildcard, use aindex_prefixestext(orsearch_as_you_type/wildcard).Tenant-level custom fields: flattened: exact filtering, vector KNN pre-filtering, and
termsterms aggregation.