Manage collections and slices (Collection and Slice)
This topic describes how to design and manage Collection (collections) and Slice (slices).
-
Multi-tenant / multi-knowledge-base scenarios: how to organize data with Collections and Slices, and how Slices are auto-created or pre-registered;
-
Single-table scenarios: how to configure
"default_slice", and omit_sliceparameter; -
Lifecycle operations: viewing and deleting Slices, pre-query cache warm-up (
_warm_slice) and copying Slices within the same Collection (_copy).
All API examples in this topic provide CONSOLE / CURL / GO / PYTHON / JAVASCRIPT / JAVA code tabs (CONSOLE can be copied directly into Kibana Dev Tools). The other SDK examples reuse the Quick Start and the environment variables and client instance.
1. Plan Collections and Slices
Collection corresponds to a logical table, and Slice corresponds to a logical partition in the table (think of it as an independent subfolder or tenant compartment):
-
Share one Collection: As long as the data structure (Mapping field types and vector dimensions) is the same, data from different tenants, knowledge bases, code repositories, or Agent sessions should all be stored in different Slices of the same Collection.
-
Create separate Collections: Create separate Collections when two datasets have conflicting field definitions or use Embedding models of different dimensions.
-
Naming rules:
-
Collection names: Use lowercase letters, digits, and
-, follow the standard Elasticsearch index naming rules, with a UTF-8 length of no more than128bytes. -
Slice names: Length:
1..128characters; it must start and end with an ASCII letter or digit, and may contain letters, digits,.,_,-._allis a reserved value, and:(colon) is a system-reserved character and cannot be used in Slice names.
-
-
Access control: For multi-tenant workloads, verify on your application server whether the current user is allowed to access the target Slice before sending requests to Agentic ES (Slice-level RBAC is not provided).
2. Single-table scenarios: configure the default slice default_slice
If your workload needs only one plain table (for example, a product table products), and you do not need per-tenant splitting, set the following when you create the Collection: "default_slice": "main":
Scale reminder: single-table default_slice mode, all reads, writes, and searches of the table go to the same main slice and is subject to per-Slice quotas — suitable for an expected data volume of ≤ 10 GB, write at ≤ 32 MiB/s and in-flight query concurrency has sufficient headroom (per-Slice limit of 16, see FAQ) tables. If you expect to exceed this scale, split the table before creation by business keys that are immutable after write and routable in queries (such as sub-knowledge bases, fixed creation time windows, or business lines) into multiple Slices (see Section 4 below; default_slice cannot be cleared after being set).
CONSOLE
// 1. Create a Collection with default_slice
PUT /_slice_collection/products
{
"default_slice": "main",
"mappings": {
"dynamic": "strict",
"properties": {
"name": { "type": "text" },
"category": { "type": "keyword" },
"price": { "type": "double" }
}
}
}
// 2. View the collection configuration to confirm that default_slice took effect
GET /_slice_collection/products
CURL
# 1. Create a Collection with default_slice
curl -u "$ES_USER:$ES_PASSWORD" -X PUT \
"$ES_ENDPOINT/_slice_collection/products" \
-H 'Content-Type: application/json' \
--data-binary @- <<'JSON'
{"default_slice":"main","mappings":{"dynamic":"strict","properties":{"name":{"type":"text"},"category":{"type":"keyword"},"price":{"type":"double"}}}}
JSON
# 2. View the collection configuration to confirm that default_slice took effect
curl -u "$ES_USER:$ES_PASSWORD" \
"$ES_ENDPOINT/_slice_collection/products"
GO
// 1. Create a Collection with default_slice
req, _ := http.NewRequestWithContext(ctx, "PUT", "/_slice_collection/products",
strings.NewReader(`{"default_slice":"main","mappings":{"dynamic":"strict","properties":{"name":{"type":"text"},"category":{"type":"keyword"},"price":{"type":"double"}}}}`))
req.Header.Set("Content-Type", "application/json")
resp, err := client.Perform(req)
if err != nil {
log.Fatal(err)
}
resp.Body.Close()
// 2. View the collection configuration to confirm that default_slice took effect
getReq, _ := http.NewRequestWithContext(ctx, "GET", "/_slice_collection/products", nil)
getResp, _ := client.Perform(getReq)
defer getResp.Body.Close()
PYTHON
# 1. Create a Collection with default_slice
client.perform_request(
"PUT",
"/_slice_collection/products",
headers={"content-type": "application/json"},
body={
"default_slice": "main",
"mappings": {
"dynamic": "strict",
"properties": {
"name": {"type": "text"},
"category": {"type": "keyword"},
"price": {"type": "double"},
},
},
},
)
# 2. View the collection configuration to confirm that default_slice took effect
info = client.perform_request("GET", "/_slice_collection/products")
print(info)
JAVASCRIPT
// 1. Create a Collection with default_slice
await client.transport.request({
method: 'PUT',
path: '/_slice_collection/products',
body: {
default_slice: 'main',
mappings: {
dynamic: 'strict',
properties: {
name: { type: 'text' },
category: { type: 'keyword' },
price: { type: 'double' },
},
},
},
})
// 2. View the collection configuration to confirm that default_slice took effect
const info = await client.transport.request({
method: 'GET',
path: '/_slice_collection/products',
})
console.log(info)
JAVA
// 1. Create a Collection with default_slice
Request createReq = new Request("PUT", "/_slice_collection/products");
createReq.setJsonEntity("""
{
"default_slice": "main",
"mappings": {
"dynamic": "strict",
"properties": {
"name": { "type": "text" },
"category": { "type": "keyword" },
"price": { "type": "double" }
}
}
}
""");
restClient.performRequest(createReq);
// 2. View the collection configuration to confirm that default_slice took effect
Response infoResp = restClient.performRequest(new Request("GET", "/_slice_collection/products"));
System.out.println(EntityUtils.toString(infoResp.getEntity()));
When a Collection is created, the system automatically creates the default slice main (if initialization is briefly not ready, creation is skipped and a Warning, disable auto_create_slice, first confirm that main already exists). After it exists, even if you disable auto_create_slice, main slice remains readable and writable.
Daily reads, writes, and searches (you can omit _slice / routing parameter):
CONSOLE
// Write a document (written to the main slice automatically)
PUT /products/_doc/p-1001
{
"name": "Outdoor hiking backpack",
"category": "outdoor",
"price": 299.0
}
// Read by ID
GET /products/_doc/p-1001
// Search (visible after the background refresh in a few seconds)
POST /products/_search?allow_partial_search_results=false
{
"query": {
"term": { "category": "outdoor" }
}
}
CURL
# Write a document (written to the main slice automatically)
curl -u "$ES_USER:$ES_PASSWORD" -X PUT \
"$ES_ENDPOINT/products/_doc/p-1001" \
-H 'Content-Type: application/json' \
--data '{"name":"Outdoor hiking backpack","category":"outdoor","price":299.0}'
# Read by ID
curl -u "$ES_USER:$ES_PASSWORD" \
"$ES_ENDPOINT/products/_doc/p-1001"
# Search (visible after the background refresh in a few seconds)
curl -u "$ES_USER:$ES_PASSWORD" -X POST \
"$ES_ENDPOINT/products/_search?allow_partial_search_results=false" \
-H 'Content-Type: application/json' \
--data '{"query":{"term":{"category":"outdoor"}}}'
GO
// Write a document (no routing needed; routed to the main slice automatically)
if _, err := client.Index("products").
Id("p-1001").
Document(map[string]any{"name": "Outdoor hiking backpack", "category": "outdoor", "price": 299.0}).
Do(ctx); err != nil {
log.Fatal(err)
}
// Read by ID in real time
doc, err := client.Get("products", "p-1001").Do(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(doc.Source_))
// Search (visible after the background refresh in a few seconds)
searchRes, err := client.Search().
Index("products").
AllowPartialSearchResults(false).
Query(&types.Query{Term: map[string]types.TermQuery{"category": {Value: "outdoor"}}}).
Do(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Println(searchRes.Hits.Hits)
PYTHON
# Write a document (no routing needed; routed to the main slice automatically)
client.index(
index="products",
id="p-1001",
document={"name": "Outdoor hiking backpack", "category": "outdoor", "price": 299.0},
)
# Read by ID in real time
doc = client.get(index="products", id="p-1001")
# Search (visible after the background refresh in a few seconds)
res = client.search(
index="products",
allow_partial_search_results=False,
query={"term": {"category": "outdoor"}},
)
JAVASCRIPT
// Write a document (no routing needed; routed to the main slice automatically)
await client.index({
index: 'products',
id: 'p-1001',
document: { name: 'Outdoor hiking backpack', category: 'outdoor', price: 299.0 },
})
// Read by ID in real time
const doc = await client.get({ index: 'products', id: 'p-1001' })
// Search (visible after the background refresh in a few seconds)
const res = await client.search({
index: 'products',
allow_partial_search_results: false,
query: { term: { category: 'outdoor' } },
})
JAVA
// Write a document (written to the main slice automatically)
client.index(i -> i.index("products").id("p-1001")
.document(Map.of("name", "Outdoor hiking backpack", "category", "outdoor", "price", 299.0)));
// Read by ID
GetResponse<Map> doc = client.get(g -> g.index("products").id("p-1001"), Map.class);
System.out.println(doc.source());
// Search (visible after the background refresh in a few seconds)
SearchResponse<Map> res = client.search(s -> s
.index("products")
.allowPartialSearchResults(false)
.query(q -> q.term(t -> t.field("category").value("outdoor"))),
Map.class);
System.out.println(res.hits().hits());
Explicitly pass _slice (or the SDK routing), the default slice is overridden:
CONSOLE
PUT /products/_doc/p-1001?_slice=other
{
"name": "Other-slice product",
"category": "outdoor",
"price": 599.0
}
CURL
curl -u "$ES_USER:$ES_PASSWORD" -X PUT \
"$ES_ENDPOINT/products/_doc/p-1001?_slice=other" \
-H 'Content-Type: application/json' \
--data '{"name":"Other-slice product","category":"outdoor","price":599.0}'
GO
if _, err := client.Index("products").
Id("p-1001").
Routing("other").
Document(map[string]any{"name": "Other-slice product", "category": "outdoor", "price": 599.0}).
Do(ctx); err != nil {
log.Fatal(err)
}
PYTHON
client.index(
index="products",
id="p-1001",
routing="other",
document={"name": "Other-slice product", "category": "outdoor", "price": 599.0},
)
JAVASCRIPT
await client.index({
index: 'products',
id: 'p-1001',
routing: 'other',
document: { name: 'Other-slice product', category: 'outdoor', price: 599.0 },
})
JAVA
client.index(i -> i.index("products").id("p-1001").routing("other")
.document(Map.of("name", "Other-slice product", "category", "outdoor", "price", 599.0)));
omit _slice, reads, writes, and searches access only the default slice main, and never merges queries from other and other slices.main and other can each store documents with the same ID (p-1001) different documents.
3. Create and update Collection configurations
|
Operation |
API and rules |
Notes |
|
creating a Collection |
Supported top-level fields: |
After creation, call |
|
Update Collection behavior |
Supports the initial binding of |
|
|
View and update Mappings |
|
Use |
|
View and update Settings |
|
|
|
Manage Collection aliases |
|
Applies only to Collections in the current application |
4. Auto-create and pre-register Slices
Recommended: auto-create on write (auto_create_slice: true)
Agentic ES enables auto-creation of Slices on write, which is the most recommended approach:
-
When you run a single write (Index / Create), an update (Update), or a
_bulkbulk write, if the specified_slicedoes not exist, the system creates the slice according toauto_create_sliceto auto-create the slice (for a single_bulkkeep the number of new Slices involved within the default limit of512or fewer; entries beyond the limit return a per-item429). -
Reads (GET), searches (Search), and deletes (DELETE) do not trigger auto-creation.
-
Why “create-on-write”?
Compared with bulk pre-registering many empty slices on an empty Collection, creating Slices when real writes occur spreads storage gradually as data grows and avoids hot spots.
On demand: pre-register Slices
If you need to eliminate the slice-creation latency of the first write for some tenants, or your workload has disabled auto_create_slice, you can call the registration API to create Slices in advance.
Slice planning and import best practices (important):
-
Never bulk pre-register a large number of Slices on an empty Collection for data that will be written only later: Each Slice is bound to its storage space at creation time and is never migrated; bulk pre-registering many empty slices on an empty Collection creates hot spots later and degrades query latency.
-
For large-scale backfills, prefer “create-on-write”or“batched registration + + batched writes”: if pre-registration is truly required, register only a small batch of Slices that will be written immediately, and proceed to the next batch after the write completes.
-
As a rule of thumb, keep a single Slice within
10 GBor less (not a hard limit; it mainly ensures stable low latency and controls cold-query and warm-up costs): if you expect to exceed it, split into multiple Slices on the business side instead of creating a new Collection:-
Relieves only capacity or write throughput (
32 MiB/s): split it into multiple Slices by hash bucket and query them together with commas (for example,?_slice=tenant-a-1,tenant-a-2); -
Also relieves the per-Slice
16query concurrency limit: split by business keys that are routable in queries and immutable after write (such as sub-knowledge bases, fixed creation time windows, or regions) so that each query hits only the target Slice (do not setdefault_slice); -
Avoid
404: If any Slice in a multi-slice query list does not exist or has been deleted, the whole request returns404; for slices that may be empty (such as new time windows or hash buckets), passignore_missing_slice=trueto skip missing slices.
-
Other API notes:
-
Registering a Slice immediately after creating a Collection may briefly return
503, retry with exponential backoff. -
Registering a Slice only requires the logical Slice name; storage is fully managed by the platform.
-
For the batch registration API, even when the outer HTTP status is
200, still check the top-levelerrors == false.
Pre-register a single Slice:
CONSOLE
PUT /_slice_collection/demo-knowledge-chunks/slices/kb-a
CURL
curl -u "$ES_USER:$ES_PASSWORD" -X PUT \
"$ES_ENDPOINT/_slice_collection/demo-knowledge-chunks/slices/kb-a"
GO
req, _ := http.NewRequestWithContext(ctx, "PUT",
"/_slice_collection/demo-knowledge-chunks/slices/kb-a", nil)
resp, err := client.Perform(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
PYTHON
res = client.perform_request(
"PUT", "/_slice_collection/demo-knowledge-chunks/slices/kb-a"
)
assert not res.get("errors", False), f"Slice registration failed: {res}"
JAVASCRIPT
const res = await client.transport.request({
method: 'PUT',
path: '/_slice_collection/demo-knowledge-chunks/slices/kb-a',
})
if (res.errors) throw new Error(`Slice registration failed: ${JSON.stringify(res)}`)
JAVA
Response resp = restClient.performRequest(
new Request("PUT", "/_slice_collection/demo-knowledge-chunks/slices/kb-a"));
String body = EntityUtils.toString(resp.getEntity());
// Parse the JSON and check the top-level "errors": false
System.out.println(body);
Pre-register multiple Slices in a batch:
CONSOLE
PUT /_slice_collection/demo-knowledge-chunks/slices
{
"slices": ["kb-a", "kb-b"]
}
CURL
curl -u "$ES_USER:$ES_PASSWORD" -X PUT \
"$ES_ENDPOINT/_slice_collection/demo-knowledge-chunks/slices" \
-H 'Content-Type: application/json' \
--data '{"slices":["kb-a","kb-b"]}'
GO
req, _ := http.NewRequestWithContext(ctx, "PUT",
"/_slice_collection/demo-knowledge-chunks/slices",
strings.NewReader(`{"slices":["kb-a","kb-b"]}`))
req.Header.Set("Content-Type", "application/json")
resp, err := client.Perform(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
var out struct {
Errors bool `json:"errors"`
}
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil || out.Errors {
log.Fatalf("batch Slice registration contains failed items: err=%v", err)
}
PYTHON
res = client.perform_request(
"PUT",
"/_slice_collection/demo-knowledge-chunks/slices",
headers={"content-type": "application/json"},
body={"slices": ["kb-a", "kb-b"]},
)
assert not res["errors"], f"batch registration contains failed items: {res['items']}"
JAVASCRIPT
const res = await client.transport.request({
method: 'PUT',
path: '/_slice_collection/demo-knowledge-chunks/slices',
body: { slices: ['kb-a', 'kb-b'] },
})
if (res.errors) throw new Error(`batch registration contains failed items: ${JSON.stringify(res.items)}`)
JAVA
Request req = new Request("PUT", "/_slice_collection/demo-knowledge-chunks/slices");
req.setJsonEntity("""
{"slices":["kb-a","kb-b"]}
""");
Response resp = restClient.performRequest(req);
String body = EntityUtils.toString(resp.getEntity());
// Even on HTTP 200, check the top-level "errors": false and each result in items[] each result in items[]
System.out.println(body);
Check the top-level errors: false and items[].result:
-
createdindicates a new Slice was created; -
noopindicates the Slice already exists; no extra handling is needed (the API is idempotent).
Disable auto-creation
To allow writes only to registered slices and prevent unregistered _slice names from auto-creating new slices, disable auto-creation:
CONSOLE
POST /_slice_collection/demo-knowledge-chunks/_update
{
"auto_create_slice": false
}
CURL
curl -u "$ES_USER:$ES_PASSWORD" -X POST \
"$ES_ENDPOINT/_slice_collection/demo-knowledge-chunks/_update" \
-H 'Content-Type: application/json' \
--data '{"auto_create_slice":false}'
GO
req, _ := http.NewRequestWithContext(ctx, "POST",
"/_slice_collection/demo-knowledge-chunks/_update",
strings.NewReader(`{"auto_create_slice":false}`))
req.Header.Set("Content-Type", "application/json")
resp, err := client.Perform(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
PYTHON
updated = client.perform_request(
"POST",
"/_slice_collection/demo-knowledge-chunks/_update",
headers={"content-type": "application/json"},
body={"auto_create_slice": False},
)
assert updated["acknowledged"]
JAVASCRIPT
const updated = await client.transport.request({
method: 'POST',
path: '/_slice_collection/demo-knowledge-chunks/_update',
body: { auto_create_slice: false },
})
JAVA
Request req = new Request("POST", "/_slice_collection/demo-knowledge-chunks/_update");
req.setJsonEntity("""
{"auto_create_slice":false}
""");
restClient.performRequest(req);
5. View and delete Slices
GET /_slice_collection/{collection}/slices returns Slices in ascending name order with pagination; page_size default 10 (range 1..10000). When a next page exists, the response returns next_cursor. To view the document count of a slice, call the single-slice detail API GET /_slice_collection/{collection}/slices/{slice}?include_doc_count=true pass this parameter (for the batch list API /slices pass include_doc_count returns 400).
Cursor pagination notes: If the first page request passes prefix to filter by prefix (for example, prefix=kb-), then subsequent cursor when paginating must also carry the same prefix parameter, otherwise, the server returns 400 (indicating that the cursor does not match the current collection or prefix).
CONSOLE
// 1. List Slices by prefix with pagination (if next_cursor is returned, the next page must carry the same prefix and cursor)
GET /_slice_collection/products/slices?page_size=100&prefix=main
// 2. View the details of a single Slice
GET /_slice_collection/products/slices/main
// 3. Delete a single Slice (delete the test slice other created in Section 2 and keep the default slice main for the warm-up and copy examples in the next section)
DELETE /_slice_collection/products/slices/other
CURL
# 1. List Slices by prefix with pagination (if next_cursor is returned, the next page must carry the same prefix and cursor)
curl -u "$ES_USER:$ES_PASSWORD" \
"$ES_ENDPOINT/_slice_collection/products/slices?page_size=100&prefix=main"
# 2. View the details of a single Slice
curl -u "$ES_USER:$ES_PASSWORD" \
"$ES_ENDPOINT/_slice_collection/products/slices/main"
# 3. Delete a single Slice (here, delete the test slice other created in Section 2 and keep the default slice main for the warm-up and copy examples in the next section)
curl -u "$ES_USER:$ES_PASSWORD" -X DELETE \
"$ES_ENDPOINT/_slice_collection/products/slices/other"
GO
// 1. List matching Slices with cursor pagination (keep the same prefix parameter when paginating)
cursor := ""
for {
q := url.Values{"page_size": {"100"}, "prefix": {"main"}}
if cursor != "" {
q.Set("cursor", cursor)
}
req, _ := http.NewRequestWithContext(ctx, "GET", "/_slice_collection/products/slices?"+q.Encode(), nil)
resp, err := client.Perform(req)
if err != nil {
log.Fatal(err)
}
var page struct {
Slices []map[string]any `json:"slices"`
NextCursor string `json:"next_cursor"`
}
_ = json.NewDecoder(resp.Body).Decode(&page)
resp.Body.Close()
if page.NextCursor == "" {
break
}
cursor = page.NextCursor
}
// 2. Delete a single Slice (delete the test slice other and keep main for later examples)
delReq, _ := http.NewRequestWithContext(ctx, "DELETE", "/_slice_collection/products/slices/other", nil)
delResp, _ := client.Perform(delReq)
defer delResp.Body.Close()
PYTHON
# 1. List matching Slices with cursor pagination (keep the same prefix parameter when paginating)
cursor = None
while True:
params = {"page_size": 100, "prefix": "main"}
if cursor:
params["cursor"] = cursor
page = client.perform_request("GET", "/_slice_collection/products/slices", params=params)
cursor = page.get("next_cursor")
if not cursor:
break
# 2. View the details of a single Slice
detail = client.perform_request("GET", "/_slice_collection/products/slices/main")
# 3. Delete a single Slice (delete the test slice other and keep main for later examples)
client.perform_request("DELETE", "/_slice_collection/products/slices/other")
JAVASCRIPT
// 1. List matching Slices with cursor pagination (keep the same prefix parameter when paginating)
let cursor = undefined
do {
const page = await client.transport.request({
method: 'GET',
path: '/_slice_collection/products/slices',
querystring: { page_size: 100, prefix: 'main', ...(cursor ? { cursor } : {}) },
})
cursor = page.next_cursor
} while (cursor)
// 2. View the details of a single Slice
const detail = await client.transport.request({
method: 'GET',
path: '/_slice_collection/products/slices/main',
})
// 3. Delete a single Slice (delete the test slice other and keep main for later examples)
await client.transport.request({
method: 'DELETE',
path: '/_slice_collection/products/slices/other',
})
JAVA
// 1. List Slices by prefix with pagination (keep the same prefix when passing cursor)
Request listReq = new Request("GET", "/_slice_collection/products/slices");
listReq.addParameter("page_size", "100");
listReq.addParameter("prefix", "main");
System.out.println(EntityUtils.toString(restClient.performRequest(listReq).getEntity()));
// 2. View the details of a single Slice
System.out.println(EntityUtils.toString(
restClient.performRequest(new Request("GET", "/_slice_collection/products/slices/main")).getEntity()));
// 3. Delete a single Slice
restClient.performRequest(new Request("DELETE", "/_slice_collection/products/slices/other"));
-
What happens after deletion: returns
acknowledged: true, the existing data of the slice immediately unqueryable, the underlying storage is reclaimed asynchronously in the background (a_copydestination slice returns409; deleting the source slice is not blocked and causes the copy to fail, so make sure the_copyreachesstate == "SUCCEEDED"before deleting the source slice). Whenauto_create_slice=true, late writes or update retries may recreate an empty slice with the same name. Before permanently retiring a slice, stop its writes and updates at the application layer, drain the retry queue, and then delete it (do not disable the Collection-levelauto_create_slice). -
Impact of deleting the default Slice: if you delete the default slice
main, the"default_slice": "main"configuration of the Collection is retained — at this point, reads without_slicereturn404; when writing again without_sliceon write, ifauto_create_slice(is enabled by default) automatically recreatesmain, otherwise, you must register it again manually.
6. Cache warm-up and Slice copy
Pre-query cache warm-up (_warm_slice)
Preloads the vector index data of a Slice into the query-node cache to reduce first-query latency on cold data. Use synchronous waiting (wait_for_completion=true&timeout=25s, note that the server-side timeout must be shorter than the client-side request_timeout), after warm-up completes, statistics fields are returned (segments_matched, ranges_warmed, docs_read):
CONSOLE
POST /products/_warm_slice?_slice=main&wait_for_completion=true&timeout=25s
CURL
curl -u "$ES_USER:$ES_PASSWORD" -X POST \
"$ES_ENDPOINT/products/_warm_slice?_slice=main&wait_for_completion=true&timeout=25s"
GO
req, _ := http.NewRequestWithContext(ctx, "POST",
"/products/_warm_slice?_slice=main&wait_for_completion=true&timeout=25s", nil)
resp, err := client.Perform(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
PYTHON
warm_stats = client.perform_request(
"POST",
"/products/_warm_slice",
params={"_slice": "main", "wait_for_completion": "true", "timeout": "25s"},
)
print(warm_stats)
JAVASCRIPT
const warmStats = await client.transport.request({
method: 'POST',
path: '/products/_warm_slice',
querystring: { _slice: 'main', wait_for_completion: true, timeout: '25s' },
})
console.log(warmStats)
JAVA
Request warmReq = new Request("POST", "/products/_warm_slice");
warmReq.addParameter("_slice", "main");
warmReq.addParameter("wait_for_completion", "true");
warmReq.addParameter("timeout", "25s");
Response warmResp = restClient.performRequest(warmReq);
System.out.println(EntityUtils.toString(warmResp.getEntity()));
Copy a Slice within the same Collection (_copy)
Copies all currently searchable data of a slice in the same Collection to a new slice (for example, from the production knowledge base main to create an evaluation slice main-eval for effect testing without affecting the source slice data).
Copy task state and search visibility:
-
How to verify a successful copy: In the response,
completed: trueonly means the task has ended — regardless of success (SUCCEEDED), failure (FAILED) or cancellation (CANCELLED),completedaretrue, so always checkstate == "SUCCEEDED". -
When copied data becomes searchable: the copy task becomes
"SUCCEEDED", documents in the new slice are immediately readable by ID; to use_searchorknnto find all documents in the new slice, you must also wait a few seconds for the background index refresh. -
Synchronous waiting and asynchronous submission: By default, synchronous waiting lasts up to 30 seconds; on timeout the API returns
HTTP 202(timed_out: true,state: "RUNNING"), usecopy_idto keep polling. For large data volumes, passwait_for_completion=falseasynchronous submission and pollGET /_slice_collection/{collection}/_copy/{copy_id}for progress, and call_cancel(copy_idcannot be queried via/_tasksquery). If the destination slice is not empty or a conflicting task exists, the API returns409; If a copy fails or is cancelled and you need to copy again, use a new destination name (or delete the old destination first and reuse the name), and clean up the half-finished slice as needed.
CONSOLE
// 1. Start the copy (default wait_for_completion=true synchronous waiting; for large data volumes, set wait_for_completion=false asynchronous submission)
POST /_slice_collection/products/slices/main/_copy/main-eval?wait_for_completion=false
{
"workers": 8,
"batch_size": 5000,
"requests_per_second": -1
}
// 2. Replace <copy_id> with the copy_id returned in step 1 and check state == "SUCCEEDED" to determine copy completion
GET /_slice_collection/products/_copy/<copy_id>
// 3. To cancel a running copy task
POST /_slice_collection/products/_copy/<copy_id>/_cancel
CURL
# 1. Start the copy (default wait_for_completion=true synchronous waiting; for large data volumes, set wait_for_completion=false asynchronous submission)
curl -u "$ES_USER:$ES_PASSWORD" -X POST \
"$ES_ENDPOINT/_slice_collection/products/slices/main/_copy/main-eval?wait_for_completion=false" \
-H 'Content-Type: application/json' \
--data '{"workers":8,"batch_size":5000,"requests_per_second":-1}'
# 2. Replace <copy_id> with the copy_id returned in step 1 (or the status_url in the request response) and check state == "SUCCEEDED" to determine copy completion
curl -u "$ES_USER:$ES_PASSWORD" \
"$ES_ENDPOINT/_slice_collection/products/_copy/<copy_id>"
# 3. To cancel a running copy task
curl -u "$ES_USER:$ES_PASSWORD" -X POST \
"$ES_ENDPOINT/_slice_collection/products/_copy/<copy_id>/_cancel"
GO
// Set an overall timeout for polling (adjust it to the slice data volume; a client-side timeout does not abort the background copy, and you can keep polling or call _cancel with the printed copy_id)
copyCtx, cancel := context.WithTimeout(ctx, 5*time.Minute)
defer cancel()
req, _ := http.NewRequestWithContext(copyCtx, "POST",
"/_slice_collection/products/slices/main/_copy/main-eval?wait_for_completion=true&timeout=25s",
strings.NewReader(`{"workers":8,"batch_size":5000,"requests_per_second":-1}`))
req.Header.Set("Content-Type", "application/json")
resp, err := client.Perform(req)
if err != nil {
log.Fatal(err)
}
raw, _ := io.ReadAll(resp.Body)
resp.Body.Close()
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusAccepted {
log.Fatalf("copy request failed HTTP %d: %s", resp.StatusCode, string(raw))
}
var copyRes struct {
CopyId string `json:"copy_id"`
Completed bool `json:"completed"`
State string `json:"state"`
}
if err := json.Unmarshal(raw, ©Res); err != nil || copyRes.CopyId == "" {
log.Fatalf("failed to parse copy_id: err=%v body=%s", err, string(raw))
}
fmt.Println("copy_id:", copyRes.CopyId)
// Poll until a terminal state and use state == "SUCCEEDED" to determine success
for !copyRes.Completed {
time.Sleep(time.Second)
pollReq, _ := http.NewRequestWithContext(copyCtx, "GET",
"/_slice_collection/products/_copy/"+url.PathEscape(copyRes.CopyId), nil)
pollResp, err := client.Perform(pollReq)
if err != nil {
log.Fatal(err)
}
pollRaw, _ := io.ReadAll(pollResp.Body)
pollResp.Body.Close()
if pollResp.StatusCode >= 300 {
log.Fatalf("copy progress query failed HTTP %d: %s", pollResp.StatusCode, string(pollRaw))
}
if err := json.Unmarshal(pollRaw, ©Res); err != nil {
log.Fatal(err)
}
}
if copyRes.State != "SUCCEEDED" {
log.Fatalf("Slice copy failed, final state: : %s", copyRes.State)
}
PYTHON
import time
copy_res = client.perform_request(
"POST",
"/_slice_collection/products/slices/main/_copy/main-eval",
params={"wait_for_completion": "true", "timeout": "25s"},
headers={"content-type": "application/json"},
body={"workers": 8, "batch_size": 5000, "requests_per_second": -1},
)
# If synchronous waiting times out (HTTP 202, completed=False), and keep polling the state (in production, set an overall polling timeout based on the data volume)
while not copy_res["completed"]:
time.sleep(1)
copy_res = client.perform_request(
"GET", f"/_slice_collection/products/_copy/{copy_res['copy_id']}"
)
# completed=True indicates a terminal state; check state == "SUCCEEDED"
if copy_res["state"] != "SUCCEEDED":
raise RuntimeError(f"Slice copy failed: {copy_res}")
JAVASCRIPT
let copyRes = await client.transport.request({
method: 'POST',
path: '/_slice_collection/products/slices/main/_copy/main-eval',
querystring: { wait_for_completion: true, timeout: '25s' },
body: { workers: 8, batch_size: 5000, requests_per_second: -1 },
})
// If synchronous waiting times out (completed is false), poll until a terminal state (in production, set an overall polling timeout based on the data volume)
while (!copyRes.completed) {
await new Promise(r => setTimeout(r, 1000))
copyRes = await client.transport.request({
method: 'GET',
path: `/_slice_collection/products/_copy/${encodeURIComponent(copyRes.copy_id)}`,
})
}
// completed === true indicates a terminal state; check state === 'SUCCEEDED'
if (copyRes.state !== 'SUCCEEDED') {
throw new Error(`Slice copy failed, state: : ${copyRes.state}`)
}
JAVA
ObjectMapper mapper = new ObjectMapper();
// 1. Start the copy asynchronously
Request copyReq = new Request("POST", "/_slice_collection/products/slices/main/_copy/main-eval");
copyReq.addParameter("wait_for_completion", "false");
copyReq.setJsonEntity("""
{"workers":8,"batch_size":5000,"requests_per_second":-1}
""");
JsonNode copyNode = mapper.readTree(EntityUtils.toString(restClient.performRequest(copyReq).getEntity()));
String copyId = copyNode.get("copy_id").asText();
// 2. Poll until completed == true (in production, set an overall polling timeout based on the data volume)
while (!copyNode.path("completed").asBoolean(false)) {
Thread.sleep(1000);
Response statusResp = restClient.performRequest(
new Request("GET", "/_slice_collection/products/_copy/" + copyId));
copyNode = mapper.readTree(EntityUtils.toString(statusResp.getEntity()));
}
// completed == true only means the task reached a terminal state; check state == "SUCCEEDED"
if (!"SUCCEEDED".equals(copyNode.path("state").asText())) {
throw new IllegalStateException("Slice copy failed, state: : " + copyNode.path("state").asText());
}
Read next: Data write and SDK integration guide.
Related features
The following advanced features can be adopted per business scenario. Each topic includes applicable scenarios, precautions, and complete code examples:
-
Tenant-level custom fields: flattened: tenants in one Collection write independent custom fields and heterogeneous metadata while occupying only one Mapping field.
-
Single-table mode without slices: default slices: single-table configuration with
default_slice, daily reads, writes, and searches no longer need_slice. -
Reduce cold-query latency: warm slices: preload cold slice indexes into the query-layer cache before concentrated access to reduce first-query latency.
-
Slice copy: copy slices: fully copy an evaluation or canary slice within the same Collection without modifying the source slice data; the source slice stays online for reads and writes during the copy.