Slice replication: Copy Slice

Updated at:

Copy Slice (_copy) copies all currently searchable data of a slice under the same Collection to a new target slice (for example, copying the production knowledge base main to an evaluation or canary slice main-eval for retrieval effectiveness testing). During the copy, the source slice continues to serve reads, writes, and searches as usual, and its data is not modified. Copying a large amount of data consumes certain read and write resources, so we recommend that you control the rate by using workers, batch_size, and requests_per_second.

Note

All API examples in this topic provide CONSOLE / CURL / GO / PYTHON / JAVASCRIPT / JAVA code tabs (CONSOLE can be copied directly into Kibana Dev Tools and run). The other SDK examples continue from Quick start: they reuse the environment variables and the client instance initialized there, and, following Single-table mode without slices: Default Slice, use the products collection (main slice) created there as the example.

1. Applicable scenarios and key notes

  • Applicable scenarios: Quickly copy an independent evaluation, canary, or validation slice from a production knowledge base to prevent test writes from polluting production data.

  • Replication within the same Collection only: To migrate data across Collections, use /_reindex (see Appendix: capability allowlist).

  • Determine success by state == "SUCCEEDED" as the criterion: When the task reaches a terminal state (succeeded, failed, or cancelled), completed is always true. In your code, you must check state == "SUCCEEDED". After the copy completes, a regular read by ID is immediately available, while searches still require a few seconds of waiting for the background automatic refresh.

  • Synchronous and asynchronous modes: By default, the request waits synchronously for at most 30s (we recommend that you pass a timeout shorter than the HTTP timeout of the client). If the wait times out, HTTP 202 is returned and the copy continues in the background; you can poll the progress by copy_id. For large data volumes, we recommend that you directly pass wait_for_completion=false to submit the task asynchronously. To interrupt the task, call _cancel (copy_id cannot be queried in /_tasks).

  • Retain searchable fields in _source: _copy rebuilds the target slice by reading the document _source. If _source is disabled for the Collection, _source.includes is configured, or _source.excludes excludes searchable fields, starting the copy returns 400.

2. API parameters and task states

Request parameters (POST /_slice_collection/{collection}/slices/{source}/_copy/{target}, all optional):

Parameter

Position

Default value

Description

wait_for_completion

URL

true

Whether to wait synchronously for completion. If set to false, HTTP 202 and copy_id are returned immediately.

timeout

URL

30s

The upper limit of the synchronous wait (we recommend a value shorter than the HTTP timeout of the client). If the wait times out, HTTP 202 (timed_out: true) is returned and the copy continues in the background.

workers

Request body

Automatically selected

The number of parallel copy tasks. Valid values: 1 to 64.

batch_size

Request body

5000

The maximum number of documents copied per batch. Valid values: 1 to 10000.

requests_per_second

Request body

-1

The upper limit of the copy write rate (documents per second). -1 indicates no throttling.

Task state enumeration (GET /_slice_collection/{collection}/_copy/{copy_id} returns state):

State

completed

Meaning and handling

RUNNING

false

The copy is in progress. Continue polling at intervals.

CANCELLING

false

The copy is being cancelled. Continue polling until a terminal state is reached.

SUCCEEDED

true

The copy completed successfully (the only success indicator).

FAILED

true

The copy failed. Check the error field in the response.

CANCELLED

true

The copy was cancelled. The target slice and the partially copied data are retained and need to be cleaned up as required.

3. Start a copy, query progress, and cancel a task

CONSOLE

// 1. Start the copy (by default wait_for_completion=true waits synchronously; for large data volumes, you can set wait_for_completion=false to submit asynchronously)
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 the response of step 1, and determine completion by state == "SUCCEEDED"
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 (by default wait_for_completion=true waits synchronously; for large data volumes, you can set wait_for_completion=false to submit asynchronously)
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 the response of step 1 (or the status_url in the direct request response), and determine completion by state == "SUCCEEDED"
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 a sample total timeout for polling (adjust it based on the slice data volume; a client timeout does not stop the background copy, and you can continue querying 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("Failed to start the copy, 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, &copyRes); 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 is reached, and determine success by state == "SUCCEEDED"
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("Failed to query the copy progress, HTTP %d: %s", pollResp.StatusCode, string(pollRaw))
	}
	if err := json.Unmarshal(pollRaw, &copyRes); err != nil {
		log.Fatal(err)
	}
}
if copyRes.State != "SUCCEEDED" {
	log.Fatalf("Failed to copy the slice, terminal 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 the synchronous wait times out (HTTP 202, completed=False), keep polling the status (in production, set a total 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 means a terminal state is reached; you must check state == "SUCCEEDED"
if copy_res["state"] != "SUCCEEDED":
    raise RuntimeError(f"Failed to copy the slice: {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 the synchronous wait times out (completed is false), poll until a terminal state is reached (in production, set a total 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 means a terminal state is reached; you must check state === 'SUCCEEDED'
if (copyRes.state !== 'SUCCEEDED') {
  throw new Error(`Failed to copy the slice, state: ${copyRes.state}`)
}

JAVA

ObjectMapper mapper = new ObjectMapper();

// 1. Submit 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 a total 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 a terminal state is reached; you must check state == "SUCCEEDED"
if (!"SUCCEEDED".equals(copyNode.path("state").asText())) {
    throw new IllegalStateException("Failed to copy the slice, state: " + copyNode.path("state").asText());
}

Typical response examples (asynchronous in progress vs. copy succeeded):

// 1. Asynchronous submission (wait_for_completion=false, HTTP 202): timed_out is false; if 202 is returned because the synchronous wait timed out, timed_out is true
{
  "copy_id": "main-eval:vz7",
  "completed": false,
  "timed_out": false,
  "state": "RUNNING",
  "source": "main",
  "target": "main-eval",
  "progress": { "total": 5000, "created": 1200, "version_conflicts": 0 },
  "status_url": "/_slice_collection/products/_copy/main-eval%3Avz7",
  "cancel_url": "/_slice_collection/products/_copy/main-eval%3Avz7/_cancel"
}

// 2. Copy succeeded (HTTP 200): completed == true and state == "SUCCEEDED"
{
  "copy_id": "main-eval:vz7",
  "completed": true,
  "timed_out": false,
  "state": "SUCCEEDED",
  "source": "main",
  "target": "main-eval",
  "workers": 8,
  "took": 4430,
  "result": { "total": 5000, "created": 5000, "version_conflicts": 0 },
  "status_url": "/_slice_collection/products/_copy/main-eval%3Avz7"
}

4. Conflict handling and deletion notes

  • A non-empty or occupied target slice returns 409: If the target slice already contains data, or is being occupied by another copy or deletion task, starting the copy returns 409 Conflict. Note: if the 409 response contains status_url, it points to the existing task that occupies the target slice, not to a new task created by this request. If you need to copy again after a failure or cancellation, use a new target name, or delete the old target slice first and rerun with the original name.

  • Do not delete the source slice during the copy: Deleting the target slice of an in-progress _copy is blocked and returns 409. However, deleting the source slice of the copy is not blocked and causes the copy to fail. Make sure that _copy has entered state == "SUCCEEDED" before you delete the source slice as required.

  • Clean up the sample slice (optional): After the evaluation is complete, or before you copy to a target with the same name again, you can run DELETE /_slice_collection/products/slices/main-eval to clean up the test slice.