Quick start
This tutorial walks through the six core steps of Agentic ES: connect to the service → create a vector Collection → write data to Slices → read by ID in real time → full-text filtering and KNN search → RRF hybrid search. The collection name used in the examples (demo-knowledge-chunks) and the sample data are consistent with the built-in example in the Kibana Dev Tools console.
Each API example provides CONSOLE / CURL / GO / PYTHON / JAVASCRIPT / JAVA code tabs. Switch to the tab you need. Requests in the CONSOLE tab can be copied directly to Kibana Dev Tools without configuring environment variables. The other tabs show HTTP calls and examples for the official SDKs.
Preparations
Create an application
Agentic ES is billed by application. Before you can write and search data, you must create an application and complete its access configuration. The creation process consists of two steps: Basic Information and Basic settings.
-
Log on to the Alibaba Cloud Elasticsearch console. In the left-side navigation pane, choose . On the application management page, click Create Application.
-
In the Basic Information step, configure the basic properties of the application:
Parameter
Description
Application Name
Required. The name must be 3 to 50 characters in length and can contain lowercase letters, digits, and hyphens (-). It must start and end with a lowercase letter or digit. The name cannot be modified after creation, so plan the naming in advance.
Region
Required. The region where the application is deployed. The region cannot be modified after creation. We recommend that you select the same region as your business systems or VPC so that you can access the application over a private network.
Remarks
Optional. The description can be up to 128 characters in length and cannot start with a space.
Service Version
Required. Only the Standard Edition is available. It uses a shared resource pool, and the base fee includes a fixed storage capacity and hourly query and write usage. For prices and billable items, see Billing rules. The edition card is not selected by default. You must click the card to select it; otherwise, you cannot proceed to the next step.
-
Click Next. In the Basic settings step, configure the access method and access credentials:
Parameter
Description
Network Access Method
Required. You can select Public Access (selected by default) or VPC Access (Recommended). If you select VPC access, you must also select a VPC and associate at least one private endpoint. We recommend that you use VPC access in production environments.
Access whitelist
IPv4 addresses or CIDR blocks, separated by commas. If you leave this parameter empty, no IP address is allowed to access the application, so specify at least one CIDR block that is allowed to access the application. If you select Internet access, configure Public Access Whitelist; if you select VPC access, configure Private Access Allowlist. Kibana and the application initially share the same access whitelist, which can be modified separately after creation.
Username
You do not need to specify this parameter. The system automatically generates a 3-character random suffix of letters or digits and appends it to the application name to form the complete username. The username is used for data reads and writes and for logging on to Kibana. You can view it in the application details after creation.
User Password
Required. The password must be 8 to 32 characters in length and must contain at least three of the following character types: uppercase letters, lowercase letters, digits, and special characters. You can click Auto-generate Password to generate a password. Keep it safe.
-
Click Create Now. The application is created asynchronously. Wait until the Status column in the application list changes to Running (usually about 2 minutes). Then, in the Actions column, click Enter Application to go to the application Overview page.
The application name and region cannot be modified after creation. Confirm them before you submit. While the application is active, the base fee is charged even if there is no usage. For more information, see Billing rules. If you leave the access whitelist empty, all IP addresses are blocked from accessing the application. Make sure that you configure the allowed CIDR blocks during or after creation.
Configure the connection information
Log on to the Alibaba Cloud Elasticsearch console. In the left-side navigation pane, choose . In the application list, find the target application and click Enter Application in the Actions column. On the Overview page, obtain the App Access URL from the Application Access section. Obtain the Username and User Password from the Basic Information section:
-
Address format: The private endpoint is in the format of
http://<appId>.private.<region>.agentic.elasticsearch.aliyuncs.com:9200, and the public endpoint is in the format ofhttp://<appId>.public.<region>.agentic.elasticsearch.aliyuncs.com:9200(where<appId>and<region>vary with the actual application and region; refer to the endpoints displayed in the console). In production environments, we recommend that you access the application over the private endpoint of a VPC in the same region. If you use the public endpoint, configure an IP address access whitelist in the console and keep your credentials safe. -
Unified endpoint: Agentic ES uses a single fully managed application entry point. Reads, writes, and searches all go directly to the same application endpoint. Unlike read/write splitting instances, you do not need to configure separate query and write endpoints (use the application access endpoint instead of the Kibana endpoint in the console).
CURL
# Replace with the private or public application endpoint copied from the console Overview page (without a trailing slash)
export ES_ENDPOINT='http://<appId>.private.<region>.agentic.elasticsearch.aliyuncs.com:9200'
export ES_USER='<username>'
# Enter the password interactively and export it as an environment variable to avoid writing the plaintext password to the Shell history
read -rs ES_PASSWORD && export ES_PASSWORD
GO
// Install dependencies (v9.5.x requires Go 1.25+): go get github.com/elastic/go-elasticsearch/v9@v9.5
package main
import (
"net/http"
"os"
"time"
"github.com/elastic/go-elasticsearch/v9"
"github.com/elastic/go-elasticsearch/v9/typedapi/some"
"github.com/elastic/go-elasticsearch/v9/typedapi/types"
)
// Clone the default Transport and enlarge the idle connection pool (Go keeps only 2 idle connections per host and at most 100 globally by default); also set the response header timeout
transport := http.DefaultTransport.(*http.Transport).Clone()
transport.MaxIdleConns = 200
transport.MaxIdleConnsPerHost = 200
transport.ResponseHeaderTimeout = 30 * time.Second
// We recommend the strongly typed client NewTypedClient (with IDE autocompletion, while still compatible with client.Perform for extended management APIs)
// For read/write isolation, 429 jittered backoff, and no-retry-on-timeout in production, see "Data writes and SDK integration"
client, err := elasticsearch.NewTypedClient(elasticsearch.Config{
Addresses: []string{os.Getenv("ES_ENDPOINT")},
Username: os.Getenv("ES_USER"),
Password: os.Getenv("ES_PASSWORD"),
Transport: transport,
MaxRetries: 3, // Retries only 502/503/504 by default; does not auto-retry a 429 query timeout
AutoDrainBody: true, // Automatically drains the unread response body on Close() after client.Perform to ensure connection reuse
})
PYTHON
# Install dependencies (v9.5.x requires Python 3.10+): python -m pip install 'elasticsearch>=9.5.0,<10.0.0'
import os
from elasticsearch import Elasticsearch
client = Elasticsearch(
os.environ["ES_ENDPOINT"],
basic_auth=(os.environ["ES_USER"], os.environ["ES_PASSWORD"]),
headers={"accept": "application/json"}, # Explicitly declare JSON acceptance to avoid a 400 from generic-request and v9 header version checks
connections_per_node=100, # Defaults to only 10 and blocks threads when the pool is full; set it >= the maximum number of concurrent threads
request_timeout=30, # Defaults to only 10 seconds; set it explicitly to 30 seconds to exceed the synchronous wait timeout
max_retries=3,
retry_on_status=(502, 503, 504), # Includes 429 by default and retries status codes without sleeping; back off and retry 429 throttling at the business layer or in helpers.bulk
retry_backoff_base=0.2, # Backs off only on connection errors (status-code retries do not sleep)
retry_backoff_cap=2,
)
JAVASCRIPT
// Install dependencies (v9.5.x requires Node.js 22+): npm install @elastic/elasticsearch@^9.5.0
import { Client } from '@elastic/elasticsearch'
const client = new Client({
node: process.env.ES_ENDPOINT,
auth: {
username: process.env.ES_USER,
password: process.env.ES_PASSWORD,
},
maxRetries: 3,
requestTimeout: 30000,
})
JAVA
// Maven dependencies (JDK 17+):
// co.elastic.clients:elasticsearch-java:9.5.6 + com.fasterxml.jackson.core:jackson-databind
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.BackoffPolicy;
import co.elastic.clients.transport.RetryConfig;
import co.elastic.clients.transport.rest5_client.Rest5ClientOptions;
import co.elastic.clients.transport.rest5_client.Rest5ClientTransport;
import co.elastic.clients.transport.rest5_client.low_level.RequestOptions;
import co.elastic.clients.transport.rest5_client.low_level.Rest5Client;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.message.BasicHeader;
import org.apache.hc.core5.util.TimeValue;
import org.apache.hc.core5.util.Timeout;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.IntStream;
String basic = "Basic " + Base64.getEncoder().encodeToString(
(System.getenv("ES_USER") + ":" + System.getenv("ES_PASSWORD")).getBytes(StandardCharsets.UTF_8));
// Enlarge the per-route connection pool (only 10 by default), disable low-level duplicate retries, and periodically reclaim idle connections
Rest5Client restClient = Rest5Client.builder(URI.create(System.getenv("ES_ENDPOINT")))
.setDefaultHeaders(new Header[]{ new BasicHeader("Authorization", basic) })
.setConnectionConfigCallback(cc -> cc.setConnectTimeout(Timeout.ofSeconds(3)).setTimeToLive(TimeValue.ofMinutes(2)))
.setConnectionManagerCallback(cm -> cm.setMaxConnTotal(200).setMaxConnPerRoute(200))
.setRequestConfigCallback(rc -> rc
.setConnectionRequestTimeout(Timeout.ofSeconds(3))
.setResponseTimeout(Timeout.ofSeconds(30)))
.setHttpClientConfigCallback(hc -> hc
.disableAutomaticRetries().evictExpiredConnections().evictIdleConnections(TimeValue.ofSeconds(30)))
.build();
BackoffPolicy jitterBackoff = new BackoffPolicy() {
@Override
public Iterator<Long> iterator() {
return IntStream.range(0, 3)
.mapToObj(i -> {
long base = 200L << i;
return base + ThreadLocalRandom.current().nextLong(base);
})
.iterator();
}
};
RetryConfig retryConfig = RetryConfig.of(r -> r
.retryableStatuses(502, 503, 504)
.retryableExceptions(Set.of())
.backoffPolicy(jitterBackoff));
ElasticsearchClient client = new ElasticsearchClient(new Rest5ClientTransport(
restClient, new JacksonJsonpMapper(), new Rest5ClientOptions(RequestOptions.DEFAULT, false, retryConfig)));
If a Collection named demo-knowledge-chunks already exists in the application, use a different name, or delete it after verification as described in Clean up sample data.
1. Create a Collection (define fields and the vector index)
Create a Collection named demo-knowledge-chunks that contains a title field (title), a body field (content), a category field (category), and a 4-dimensional vector field (embedding, using the bbq_disk vector index):
CONSOLE
PUT /_slice_collection/demo-knowledge-chunks
{
"mappings": {
"properties": {
"title": { "type": "text" },
"content": { "type": "text" },
"category": { "type": "keyword" },
"embedding": {
"type": "dense_vector",
"dims": 4,
"index": true,
"similarity": "cosine",
"index_options": { "type": "bbq_disk" }
}
}
}
}
CURL
curl --include -u "$ES_USER:$ES_PASSWORD" -X PUT \
"$ES_ENDPOINT/_slice_collection/demo-knowledge-chunks" \
-H 'Content-Type: application/json' \
--data-binary @- <<'JSON'
{
"mappings": {
"properties": {
"title": { "type": "text" },
"content": { "type": "text" },
"category": { "type": "keyword" },
"embedding": {
"type": "dense_vector",
"dims": 4,
"index": true,
"similarity": "cosine",
"index_options": { "type": "bbq_disk" }
}
}
}
}
JSON
GO
createReq, err := http.NewRequestWithContext(ctx, "PUT", "/_slice_collection/demo-knowledge-chunks", strings.NewReader(`{
"mappings": {
"properties": {
"title": { "type": "text" },
"content": { "type": "text" },
"category": { "type": "keyword" },
"embedding": {
"type": "dense_vector", "dims": 4, "index": true,
"similarity": "cosine", "index_options": { "type": "bbq_disk" }
}
}
}
}`))
if err != nil {
log.Fatal(err)
}
createReq.Header.Set("Content-Type", "application/json")
createResp, err := client.Perform(createReq)
if err != nil {
log.Fatal(err)
}
defer createResp.Body.Close()
PYTHON
created = client.perform_request(
"PUT",
"/_slice_collection/demo-knowledge-chunks",
headers={"content-type": "application/json"},
body={
"mappings": {
"properties": {
"title": {"type": "text"},
"content": {"type": "text"},
"category": {"type": "keyword"},
"embedding": {
"type": "dense_vector",
"dims": 4,
"index": True,
"similarity": "cosine",
"index_options": {"type": "bbq_disk"},
},
},
}
},
)
assert created["acknowledged"]
JAVASCRIPT
const created = await client.transport.request({
method: 'PUT',
path: '/_slice_collection/demo-knowledge-chunks',
body: {
mappings: {
properties: {
title: { type: 'text' },
content: { type: 'text' },
category: { type: 'keyword' },
embedding: {
type: 'dense_vector',
dims: 4,
index: true,
similarity: 'cosine',
index_options: { type: 'bbq_disk' },
},
},
},
},
})
JAVA
Request createReq = new Request("PUT", "/_slice_collection/demo-knowledge-chunks");
createReq.setJsonEntity("""
{
"mappings": {
"properties": {
"title": { "type": "text" },
"content": { "type": "text" },
"category": { "type": "keyword" },
"embedding": {
"type": "dense_vector",
"dims": 4,
"index": true,
"similarity": "cosine",
"index_options": { "type": "bbq_disk" }
}
}
}
}
""");
Response createResp = restClient.performRequest(createReq);
System.out.println(EntityUtils.toString(createResp.getEntity()));
Expected response: {"acknowledged": true}
Note the following three points when you integrate Agentic ES into your business.
-
The 4-dimensional vector in this example is for demonstration only. Set
dimsandsimilarityto the actual output dimension and distance metric of your embedding model.dimscannot be modified after creation. -
For production environments, we recommend adding
"dynamic": "strict"undermappingsto enable strict field validation. Writes that contain undeclared field names fail immediately, which prevents dirty data caused by spelling errors. -
Creating a Collection with an existing name returns
400indicating that the collection already exists.
2. Bulk-write data to two Slices
Use a single _bulk request to write 3 documents to the kb-a and kb-b Slices:
-
The first write automatically creates the Slice: By default, you do not need to call a registration API in advance. The system automatically creates
kb-aandkb-b(compared with bulk pre-registration on an empty collection, creating Slices on write better spreads storage load as data grows; for planning recommendations, see Automatically create or pre-register Slices). -
The same ID is isolated by Slice:
kb-aandkb-bboth contain a document with"_id": "chunk-1001". Because they belong to different Slices, they do not overwrite each other.
CONSOLE
POST /_bulk
{"index":{"_index":"demo-knowledge-chunks","_id":"chunk-1001","_slice":"kb-a"}}
{"title":"Refund policy","content":"You can request a refund within seven days.","category":"after-sales","embedding":[0.82,0.10,0.05,0.03]}
{"index":{"_index":"demo-knowledge-chunks","_id":"chunk-1002","_slice":"kb-a"}}
{"title":"Change address","content":"You can change the shipping address before the order is shipped.","category":"orders","embedding":[0.75,0.16,0.06,0.03]}
{"index":{"_index":"demo-knowledge-chunks","_id":"chunk-1001","_slice":"kb-b"}}
{"title":"Logistics query","content":"Check the delivery status and tracking number.","category":"shipping","embedding":[0.12,0.78,0.06,0.04]}
CURL
curl -u "$ES_USER:$ES_PASSWORD" -X POST "$ES_ENDPOINT/_bulk" \
-H 'Content-Type: application/x-ndjson' \
--data-binary @- <<'NDJSON'
{"index":{"_index":"demo-knowledge-chunks","_id":"chunk-1001","_slice":"kb-a"}}
{"title":"Refund policy","content":"You can request a refund within seven days.","category":"after-sales","embedding":[0.82,0.10,0.05,0.03]}
{"index":{"_index":"demo-knowledge-chunks","_id":"chunk-1002","_slice":"kb-a"}}
{"title":"Change address","content":"You can change the shipping address before the order is shipped.","category":"orders","embedding":[0.75,0.16,0.06,0.03]}
{"index":{"_index":"demo-knowledge-chunks","_id":"chunk-1001","_slice":"kb-b"}}
{"title":"Logistics query","content":"Check the delivery status and tracking number.","category":"shipping","embedding":[0.12,0.78,0.06,0.04]}
NDJSON
GO
bulkReq := client.Bulk()
_ = bulkReq.IndexOp(
types.IndexOperation{
Index_: some.String("demo-knowledge-chunks"),
Id_: some.String("chunk-1001"),
Routing: some.String("kb-a"),
},
map[string]any{
"title": "Refund policy",
"content": "You can request a refund within seven days.",
"category": "after-sales",
"embedding": []float32{0.82, 0.10, 0.05, 0.03},
},
)
_ = bulkReq.IndexOp(
types.IndexOperation{
Index_: some.String("demo-knowledge-chunks"),
Id_: some.String("chunk-1002"),
Routing: some.String("kb-a"),
},
map[string]any{
"title": "Change address",
"content": "You can change the shipping address before the order is shipped.",
"category": "orders",
"embedding": []float32{0.75, 0.16, 0.06, 0.03},
},
)
_ = bulkReq.IndexOp(
types.IndexOperation{
Index_: some.String("demo-knowledge-chunks"),
Id_: some.String("chunk-1001"),
Routing: some.String("kb-b"),
},
map[string]any{
"title": "Logistics query",
"content": "Check the delivery status and tracking number.",
"category": "shipping",
"embedding": []float32{0.12, 0.78, 0.06, 0.04},
},
)
bulkRes, err := bulkReq.Do(ctx)
if err != nil {
log.Fatal(err)
}
if bulkRes.Errors {
log.Fatalf("Bulk partially failed: %+v", bulkRes.Items)
}
PYTHON
bulk = client.bulk(
operations=[
{
"index": {
"_index": "demo-knowledge-chunks",
"_id": "chunk-1001",
"routing": "kb-a",
},
},
{
"title": "Refund policy",
"content": "You can request a refund within seven days.",
"category": "after-sales",
"embedding": [0.82, 0.10, 0.05, 0.03],
},
{
"index": {
"_index": "demo-knowledge-chunks",
"_id": "chunk-1002",
"routing": "kb-a",
},
},
{
"title": "Change address",
"content": "You can change the shipping address before the order is shipped.",
"category": "orders",
"embedding": [0.75, 0.16, 0.06, 0.03],
},
{
"index": {
"_index": "demo-knowledge-chunks",
"_id": "chunk-1001",
"routing": "kb-b",
},
},
{
"title": "Logistics query",
"content": "Check the delivery status and tracking number.",
"category": "shipping",
"embedding": [0.12, 0.78, 0.06, 0.04],
},
]
)
assert not bulk["errors"], f"Bulk partially failed: {bulk['items']}"
JAVASCRIPT
const bulk = await client.bulk({
operations: [
{
index: {
_index: 'demo-knowledge-chunks',
_id: 'chunk-1001',
routing: 'kb-a',
},
},
{
title: 'Refund policy',
content: 'You can request a refund within seven days.',
category: 'after-sales',
embedding: [0.82, 0.10, 0.05, 0.03],
},
{
index: {
_index: 'demo-knowledge-chunks',
_id: 'chunk-1002',
routing: 'kb-a',
},
},
{
title: 'Change address',
content: 'You can change the shipping address before the order is shipped.',
category: 'orders',
embedding: [0.75, 0.16, 0.06, 0.03],
},
{
index: {
_index: 'demo-knowledge-chunks',
_id: 'chunk-1001',
routing: 'kb-b',
},
},
{
title: 'Logistics query',
content: 'Check the delivery status and tracking number.',
category: 'shipping',
embedding: [0.12, 0.78, 0.06, 0.04],
},
],
})
if (bulk.errors) throw new Error('Bulk write partially failed')
JAVA
BulkResponse bulkResp = client.bulk(b -> b
.operations(op -> op.index(idx -> idx
.index("demo-knowledge-chunks").id("chunk-1001").routing("kb-a")
.document(Map.of(
"title", "Refund policy",
"content", "You can request a refund within seven days.",
"category", "after-sales",
"embedding", List.of(0.82, 0.10, 0.05, 0.03)))))
.operations(op -> op.index(idx -> idx
.index("demo-knowledge-chunks").id("chunk-1002").routing("kb-a")
.document(Map.of(
"title", "Change address",
"content", "You can change the shipping address before the order is shipped.",
"category", "orders",
"embedding", List.of(0.75, 0.16, 0.06, 0.03)))))
.operations(op -> op.index(idx -> idx
.index("demo-knowledge-chunks").id("chunk-1001").routing("kb-b")
.document(Map.of(
"title", "Logistics query",
"content", "Check the delivery status and tracking number.",
"category", "shipping",
"embedding", List.of(0.12, 0.78, 0.06, 0.04))))));
if (bulkResp.errors()) {
throw new IllegalStateException("Bulk write partially failed: " + bulkResp.items());
}
Bulk requests use the application/x-ndjson format. Operation lines and document lines alternate, and the last line must end with a newline character (\n). If an individual write fails, including a per-item 429 throttling error, the outer HTTP status code can still be 200. Check for "errors": false in the response to confirm that all writes succeeded. Retry only failed items with backoff. Do not pass the refresh parameter for regular writes.
3. Read by ID in real time (verify same-ID isolation)
In normal cases, reading a document by ID (GET) returns the document immediately after a successful write, without waiting for a background refresh. For the rare visibility boundaries during failure recovery or node switchover windows, see Migration guide, error codes, and FAQ. In the official SDKs, the routing parameter of the standard methods is equivalent to the URL parameter _slice:
CONSOLE
GET /demo-knowledge-chunks/_doc/chunk-1001?_slice=kb-a
GET /demo-knowledge-chunks/_doc/chunk-1001?_slice=kb-b
CURL
curl -u "$ES_USER:$ES_PASSWORD" \
"$ES_ENDPOINT/demo-knowledge-chunks/_doc/chunk-1001?_slice=kb-a"
curl -u "$ES_USER:$ES_PASSWORD" \
"$ES_ENDPOINT/demo-knowledge-chunks/_doc/chunk-1001?_slice=kb-b"
GO
docA, err := client.Get("demo-knowledge-chunks", "chunk-1001").Routing("kb-a").Do(ctx)
if err != nil {
log.Fatal(err)
}
docB, err := client.Get("demo-knowledge-chunks", "chunk-1001").Routing("kb-b").Do(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(docA.Source_), string(docB.Source_))
PYTHON
doc_a = client.get(index="demo-knowledge-chunks", id="chunk-1001", routing="kb-a")
doc_b = client.get(index="demo-knowledge-chunks", id="chunk-1001", routing="kb-b")
print(doc_a["_source"]["title"], doc_b["_source"]["title"]) # Refund policy Logistics query
JAVASCRIPT
const docA = await client.get({ index: 'demo-knowledge-chunks', id: 'chunk-1001', routing: 'kb-a' })
const docB = await client.get({ index: 'demo-knowledge-chunks', id: 'chunk-1001', routing: 'kb-b' })
console.log(docA._source.title, docB._source.title) // Refund policy Logistics query
JAVA
GetResponse<Map> docA = client.get(
g -> g.index("demo-knowledge-chunks").id("chunk-1001").routing("kb-a"), Map.class);
GetResponse<Map> docB = client.get(
g -> g.index("demo-knowledge-chunks").id("chunk-1001").routing("kb-b"), Map.class);
System.out.println(docA.source().get("title") + " " + docB.source().get("title")); // Refund policy Logistics query
Expected response:
-
For
chunk-1001inkb-a, the response contains"found": true, andtitleis"Refund policy". -
For
chunk-1001inkb-b, the response contains"found": true, andtitleis"Logistics query".
To reduce transfer overhead, the _source returned by default does not include vector fields, such as embedding in the preceding example. This is native behavior of Elasticsearch 9.x and does not indicate a failed write. To verify vector values, append ?_source_exclude_vectors=false to the URL. The complete request is GET /demo-knowledge-chunks/_doc/chunk-1001?_slice=kb-a&_source_exclude_vectors=false. For search requests, you can also set _source: {"exclude_vectors": false} in the request body.
4. Full-text search + structured filtering
Full-text search (_search) and vector search (knn) rely on automatic background refresh on the server side. Written documents are usually searchable within a few seconds. If hits is empty when you query immediately after a write, retry a limited number of times at 1-second intervals. Do not call _refresh after business writes.
The following request searches the kb-a Slice for documents whose body contains "refund" and whose category is after-sales:
CONSOLE
POST /demo-knowledge-chunks/_search?_slice=kb-a&allow_partial_search_results=false
{
"query": {
"bool": {
"must": [{ "match": { "content": "refund" } }],
"filter": [{ "term": { "category": "after-sales" } }]
}
},
"_source": ["title", "content", "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'
{
"query": {
"bool": {
"must": [{ "match": { "content": "refund" } }],
"filter": [{ "term": { "category": "after-sales" } }]
}
},
"_source": ["title", "content", "category"]
}
JSON
GO
searchRes, err := client.Search().
Index("demo-knowledge-chunks").
Routing("kb-a").
AllowPartialSearchResults(false).
Query(&types.Query{
Bool: &types.BoolQuery{
Must: []types.Query{{Match: map[string]types.MatchQuery{"content": {Query: "refund"}}}},
Filter: []types.Query{{Term: map[string]types.TermQuery{"category": {Value: "after-sales"}}}},
},
}).
SourceIncludes_("title", "content", "category").
Do(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Println(searchRes.Hits.Hits)
PYTHON
res = client.search(
index="demo-knowledge-chunks",
routing="kb-a",
allow_partial_search_results=False,
query={
"bool": {
"must": [{"match": {"content": "refund"}}],
"filter": [{"term": {"category": "after-sales"}}],
}
},
source=["title", "content", "category"],
)
print(res["hits"]["hits"])
JAVASCRIPT
const res = await client.search({
index: 'demo-knowledge-chunks',
routing: 'kb-a',
allow_partial_search_results: false,
query: {
bool: {
must: [{ match: { content: 'refund' } }],
filter: [{ term: { category: 'after-sales' } }],
},
},
_source: ['title', 'content', 'category'],
})
console.log(res.hits.hits)
JAVA
SearchResponse<Map> res = client.search(s -> s
.index("demo-knowledge-chunks")
.routing("kb-a")
.allowPartialSearchResults(false)
.query(q -> q.bool(b -> b
.must(m -> m.match(mt -> mt.field("content").query("refund")))
.filter(f -> f.term(t -> t.field("category").value("after-sales")))))
.source(src -> src.filter(f -> f.includes("title", "content", "category"))),
Map.class);
System.out.println(res.hits().hits());
Expected hit: "title": "Refund policy" (also confirm that the response contains timed_out: false and _shards.failed: 0).
5. Vector nearest-neighbor search (KNN)
In the kb-a Slice, use the query vector [0.80, 0.12, 0.05, 0.03] to retrieve the 2 most similar documents:
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
},
"_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
},
"_source": ["title", "category"]
}
JSON
GO
knnRes, 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),
}).
SourceIncludes_("title", "category").
Do(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Println(knnRes.Hits.Hits)
PYTHON
knn_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,
},
source=["title", "category"],
)
print(knn_res["hits"]["hits"])
JAVASCRIPT
const knnRes = 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,
},
_source: ['title', 'category'],
})
console.log(knnRes.hits.hits)
JAVA
SearchResponse<Map> knnRes = 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))
.source(src -> src.filter(f -> f.includes("title", "category"))),
Map.class);
System.out.println(knnRes.hits().hits());
Expected response: Documents in kb-a are returned in descending order of cosine similarity (_score = (1 + cosθ) / 2; a larger value indicates higher similarity): "Refund policy" and "Change address". Data in the kb-b Slice is not included in the results.
Recall tuning tips: The bbq_disk vector index uses visit_percentage = 0 (search by num_candidates) and rescore_vector.oversample = 10.0 (rescoring with the original vectors) by default. To further improve recall in production evaluations, you can adjust these two parameters in the query or in the mapping. For more information, see Tune vector search accuracy and speed: DiskBBQ.
6. Hybrid search with full-text + vector + scalar filtering (RRF)
In real AI knowledge base (RAG) scenarios, keyword-only search easily misses synonyms, vector-only search sometimes fails to capture proper nouns (such as model numbers or order IDs), and you also need scalar filtering by category, status, or permission. With retriever.rrf, a single request combines full-text search (standard), vector search (knn), and scalar filtering (filter). The server uses only the rank of each retrieval path, not the raw score scale, and automatically merges the results with reciprocal rank fusion (documents hit by both paths rank higher, with no manual weight tuning required).
In the kb-a Slice, within the category = "after-sales" category only, run an RRF hybrid search that combines the body keyword "refund" and the query vector [0.80, 0.12, 0.05, 0.03]:
CONSOLE
// retrievers[0].standard: full-text search (matches the keyword "refund")
// retrievers[1].knn: vector search (matches the query vector)
// rrf.filter: scalar filter (keeps only category = "after-sales"; applies to both the full-text and vector paths)
POST /demo-knowledge-chunks/_search?_slice=kb-a&allow_partial_search_results=false
{
"retriever": {
"rrf": {
"retrievers": [
{
"standard": {
"query": {
"match": { "content": "refund" }
}
}
},
{
"knn": {
"field": "embedding",
"query_vector": [0.80, 0.12, 0.05, 0.03],
"k": 2,
"num_candidates": 10
}
}
],
"filter": {
"term": { "category": "after-sales" }
},
"rank_window_size": 5,
"rank_constant": 60
}
},
"size": 2,
"_source": ["title", "category"]
}
CURL
# retrievers[0].standard: full-text search (matches the keyword "refund")
# retrievers[1].knn: vector search (matches the query vector)
# rrf.filter: scalar filter (keeps only category = "after-sales"; applies to both the full-text and vector paths)
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": {
"match": { "content": "refund" }
}
}
},
{
"knn": {
"field": "embedding",
"query_vector": [0.80, 0.12, 0.05, 0.03],
"k": 2,
"num_candidates": 10
}
}
],
"filter": {
"term": { "category": "after-sales" }
},
"rank_window_size": 5,
"rank_constant": 60
}
},
"size": 2,
"_source": ["title", "category"]
}
JSON
GO
rrfRes, err := client.Search().
Index("demo-knowledge-chunks").
Routing("kb-a").
AllowPartialSearchResults(false).
Retriever(&types.RetrieverContainer{
Rrf: &types.RRFRetriever{
Retrievers: []types.RRFRetrieverEntry{
// Full-text search: match the body keyword
types.RetrieverContainer{
Standard: &types.StandardRetriever{
Query: &types.Query{Match: map[string]types.MatchQuery{"content": {Query: "refund"}}},
},
},
// Vector search: match the semantically closest vectors
types.RetrieverContainer{
Knn: &types.KnnRetriever{
Field: "embedding",
QueryVector: []float32{0.80, 0.12, 0.05, 0.03},
K: 2,
NumCandidates: some.Int(10),
},
},
},
// Scalar filter: keep only the after-sales category (applies to both paths)
Filter: []types.Query{{Term: map[string]types.TermQuery{"category": {Value: "after-sales"}}}},
RankWindowSize: some.Int(5),
RankConstant: some.Int(60),
},
}).
Size(2).
SourceIncludes_("title", "category").
Do(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Println(rrfRes.Hits.Hits)
PYTHON
rrf_res = client.search(
index="demo-knowledge-chunks",
routing="kb-a",
allow_partial_search_results=False,
retriever={
"rrf": {
"retrievers": [
# Full-text search: match the body keyword
{"standard": {"query": {"match": {"content": "refund"}}}},
# Vector search: match the semantically closest vectors
{
"knn": {
"field": "embedding",
"query_vector": [0.80, 0.12, 0.05, 0.03],
"k": 2,
"num_candidates": 10,
}
},
],
# Scalar filter: keep only the after-sales category (applies to both paths)
"filter": {"term": {"category": "after-sales"}},
"rank_window_size": 5,
"rank_constant": 60,
}
},
size=2,
source=["title", "category"],
)
print(rrf_res["hits"]["hits"])
JAVASCRIPT
const rrfRes = await client.search({
index: 'demo-knowledge-chunks',
routing: 'kb-a',
allow_partial_search_results: false,
retriever: {
rrf: {
retrievers: [
// Full-text search: match the body keyword
{ standard: { query: { match: { content: 'refund' } } } },
// Vector search: match the semantically closest vectors
{
knn: {
field: 'embedding',
query_vector: [0.80, 0.12, 0.05, 0.03],
k: 2,
num_candidates: 10,
},
},
],
// Scalar filter: keep only the after-sales category (applies to both paths)
filter: { term: { category: 'after-sales' } },
rank_window_size: 5,
rank_constant: 60,
},
},
size: 2,
_source: ['title', 'category'],
})
console.log(rrfRes.hits.hits)
JAVA
SearchResponse<Map> rrfRes = client.search(s -> s
.index("demo-knowledge-chunks")
.routing("kb-a")
.allowPartialSearchResults(false)
.retriever(r -> r.rrf(rrf -> rrf
// Full-text search: match the body keyword
.retrievers(e -> e.retriever(sub -> sub.standard(st -> st
.query(q -> q.match(m -> m.field("content").query("refund"))))))
// Vector search: match the semantically closest vectors
.retrievers(e -> e.retriever(sub -> sub.knn(k -> k
.field("embedding")
.queryVector(0.80f, 0.12f, 0.05f, 0.03f)
.k(2)
.numCandidates(10))))
// Scalar filter: keep only the after-sales category (applies to both paths)
.filter(f -> f.term(t -> t.field("category").value("after-sales")))
.rankWindowSize(5)
.rankConstant(60)))
.size(2)
.source(src -> src.filter(f -> f.includes("title", "category"))),
Map.class);
System.out.println(rrfRes.hits().hits());
Expected response: Only "Refund policy" (chunk-1001) in kb-a is returned. It satisfies the scalar filter category = "after-sales" and matches both the full-text and vector search paths. Its _score is approximately 0.0328. "Change address", with category = "orders", is excluded by the scalar filter. For more information about multi-path hybrid search and parameter tuning, see Hybrid keyword and semantic search: RRF.
Additional scenarios
View existing Collections and Slices
For operations and diagnostics, you can use the _cat API to view the current list of Collections and Slices. These are low-frequency management APIs; do not put them in high-frequency business query paths.
CONSOLE
GET /_cat/slice_collection?v
GET /_cat/slice_collection/demo-knowledge-chunks/slices?v
CURL
curl -u "$ES_USER:$ES_PASSWORD" "$ES_ENDPOINT/_cat/slice_collection?v"
curl -u "$ES_USER:$ES_PASSWORD" "$ES_ENDPOINT/_cat/slice_collection/demo-knowledge-chunks/slices?v"
GO
req1, _ := http.NewRequestWithContext(ctx, "GET", "/_cat/slice_collection?v&format=json", nil)
resp1, err := client.Perform(req1)
if err == nil {
defer resp1.Body.Close()
}
req2, _ := http.NewRequestWithContext(ctx, "GET", "/_cat/slice_collection/demo-knowledge-chunks/slices?v&format=json", nil)
resp2, err := client.Perform(req2)
if err == nil {
defer resp2.Body.Close()
}
PYTHON
collections = client.perform_request("GET", "/_cat/slice_collection", params={"v": "true", "format": "json"})
slices = client.perform_request(
"GET", "/_cat/slice_collection/demo-knowledge-chunks/slices",
params={"v": "true", "format": "json"},
)
print(collections, slices)
JAVASCRIPT
const collections = await client.transport.request({
method: 'GET',
path: '/_cat/slice_collection',
querystring: { v: true, format: 'json' },
})
const slices = await client.transport.request({
method: 'GET',
path: '/_cat/slice_collection/demo-knowledge-chunks/slices',
querystring: { v: true, format: 'json' },
})
console.log(collections, slices)
JAVA
Request req1 = new Request("GET", "/_cat/slice_collection");
req1.addParameter("v", "true");
req1.addParameter("format", "json");
System.out.println(EntityUtils.toString(restClient.performRequest(req1).getEntity()));
Request req2 = new Request("GET", "/_cat/slice_collection/demo-knowledge-chunks/slices");
req2.addParameter("v", "true");
req2.addParameter("format", "json");
System.out.println(EntityUtils.toString(restClient.performRequest(req2).getEntity()));
Single-table mode: use the default Slice (no _slice required)
If your business uses a single table without tenant-based partitioning, you can set "default_slice": "main" when creating the Collection. Subsequent writes and searches can then omit _slice (or the SDK routing) parameter:
CONSOLE
// 1. Create a Collection with default_slice
PUT /_slice_collection/demo-default-slice
{
"default_slice": "main"
}
// 2. Writes and searches no longer require _slice (the main Slice is used automatically)
POST /demo-default-slice/_doc
{
"doc": "abc"
}
GET /demo-default-slice/_search
CURL
# 1. Create a Collection with default_slice
curl -u "$ES_USER:$ES_PASSWORD" -X PUT \
"$ES_ENDPOINT/_slice_collection/demo-default-slice" \
-H 'Content-Type: application/json' --data '{"default_slice":"main"}'
# 2. Writes and searches no longer require _slice (the main Slice is used automatically)
curl -u "$ES_USER:$ES_PASSWORD" -X POST "$ES_ENDPOINT/demo-default-slice/_doc" \
-H 'Content-Type: application/json' --data '{"doc":"abc"}'
curl -u "$ES_USER:$ES_PASSWORD" "$ES_ENDPOINT/demo-default-slice/_search"
GO
// 1. Create a Collection with default_slice
req, _ := http.NewRequestWithContext(ctx, "PUT", "/_slice_collection/demo-default-slice",
strings.NewReader(`{"default_slice":"main"}`))
req.Header.Set("Content-Type", "application/json")
resp, _ := client.Perform(req)
defer resp.Body.Close()
// 2. Writes and searches no longer require Routing (the main Slice is used automatically)
_, _ = client.Index("demo-default-slice").Document(map[string]any{"doc": "abc"}).Do(ctx)
defaultRes, _ := client.Search().Index("demo-default-slice").Do(ctx)
fmt.Println(defaultRes.Hits.Hits)
PYTHON
# 1. Create a Collection with default_slice
client.perform_request(
"PUT", "/_slice_collection/demo-default-slice",
headers={"content-type": "application/json"},
body={"default_slice": "main"},
)
# 2. Writes and searches no longer require routing (the main Slice is used automatically)
client.index(index="demo-default-slice", document={"doc": "abc"})
res = client.search(index="demo-default-slice")
JAVASCRIPT
// 1. Create a Collection with default_slice
await client.transport.request({
method: 'PUT',
path: '/_slice_collection/demo-default-slice',
body: { default_slice: 'main' },
})
// 2. Writes and searches no longer require routing (the main Slice is used automatically)
await client.index({ index: 'demo-default-slice', document: { doc: 'abc' } })
const res = await client.search({ index: 'demo-default-slice' })
JAVA
// 1. Create a Collection with default_slice
Request createDefault = new Request("PUT", "/_slice_collection/demo-default-slice");
createDefault.setJsonEntity("""
{"default_slice":"main"}
""");
restClient.performRequest(createDefault);
// 2. Writes and searches no longer require routing (the main Slice is used automatically)
client.index(i -> i.index("demo-default-slice").document(Map.of("doc", "abc")));
SearchResponse<Map> defaultRes = client.search(s -> s.index("demo-default-slice"), Map.class);
System.out.println(defaultRes.hits().hits());
After waiting a few seconds for the automatic background refresh, searches return the newly written documents. Note that omitting _slice means accessing the default Slice main, not searching all Slices. For more information, see Manage Collections and Slices: configure the default Slice for a single table.
Clean up sample data (optional)
When you no longer need the sample collections, run the following commands to delete them (note: deleting a Collection also deletes the data of all its Slices):
CONSOLE
DELETE /_slice_collection/demo-knowledge-chunks
DELETE /_slice_collection/demo-default-slice
CURL
curl -u "$ES_USER:$ES_PASSWORD" -X DELETE "$ES_ENDPOINT/_slice_collection/demo-knowledge-chunks"
curl -u "$ES_USER:$ES_PASSWORD" -X DELETE "$ES_ENDPOINT/_slice_collection/demo-default-slice"
GO
for _, name := range []string{"demo-knowledge-chunks", "demo-default-slice"} {
req, _ := http.NewRequestWithContext(ctx, "DELETE", "/_slice_collection/"+name, nil)
resp, err := client.Perform(req)
if err == nil {
resp.Body.Close()
}
}
PYTHON
client.perform_request("DELETE", "/_slice_collection/demo-knowledge-chunks")
client.perform_request("DELETE", "/_slice_collection/demo-default-slice")
JAVASCRIPT
await client.transport.request({ method: 'DELETE', path: '/_slice_collection/demo-knowledge-chunks' })
await client.transport.request({ method: 'DELETE', path: '/_slice_collection/demo-default-slice' })
JAVA
restClient.performRequest(new Request("DELETE", "/_slice_collection/demo-knowledge-chunks"));
restClient.performRequest(new Request("DELETE", "/_slice_collection/demo-default-slice"));
What to do next
-
Manage Collections and Slices and configure
default_slicefor a single table: Manage collections and slices (Collection and Slice) -
Bulk writes with official SDKs and
429throttling handling: Write data and integrate SDKs -
Full-text + vector hybrid search (RRF), aggregations, pagination, and expensive query limits: Data retrieval guide (full-text, vector, and hybrid search)
-
Supported APIs, field types, and query syntax: Appendix: capability allowlist
-
Go deeper by scenario: Hybrid keyword and semantic search: RRF | Tune vector search accuracy and speed: DiskBBQ | Wildcard and prefix fuzzy search: wildcard | Tenant-level custom fields: Flattened |Single-table mode without slices: Default Slice