Write data and integrate SDKs
This topic describes how to use the official Elasticsearch clients (GO, PYTHON, JAVASCRIPT, and JAVA) to access Agentic ES, specify a _slice Slice, perform continuous bulk writes, and configure the connection pool and 429 throttling retries to avoid client-side queue stalls or connection-pool exhaustion under high concurrency.
1. Official client access and connection pool best practices
You do not need to install a proprietary SDK to access Agentic ES. Use the official Elasticsearch v9 clients directly:
-
Routine document reads, writes, searches, and bulk writes: Call the standard methods of the official client (such as
get,index,search, andbulk) and pass the target Slice name through theroutingparameter (within a Collection,routingis fully equivalent to the URL parameter_slice). -
Create or delete Collections and manage Slices: Use the generic HTTP request method built into the official client to send
/_slice_collection/...requests, reusing the same connection pool, credentials, and timeout/retry configuration.
|
Language |
Official client package (v9) |
Routine reads, writes, and searches |
Collection/Slice management entry point |
|
GO |
|
Strongly typed |
|
|
PYTHON |
|
|
|
|
JAVASCRIPT / Node.js |
|
|
|
|
JAVA |
|
|
|
Reuse a single client (Client) instance globally; do not create a new connection pool for each request. Set the ES_ENDPOINT environment variable to the application access endpoint provided by the console (reads, writes, and searches share this single endpoint).
GO
// Install dependencies (v9.5.x requires Go 1.25+):
// go mod init example.com/agentic-es-example
// go get github.com/elastic/go-elasticsearch/v9@v9.5
// Required configuration for high concurrency:
// 1. The Go standard library keeps only 2 idle connections per host by default (MaxIdleConnsPerHost=2), with a global idle-connection cap of 100.
// After Clone(), enlarge both MaxIdleConns and MaxIdleConnsPerHost (recommended >= peak concurrency, e.g. 200);
// otherwise every request re-creates a TCP connection under high concurrency.
// 2. Enable AutoDrainBody: true — even if the caller reads only part of the response body before Close(), the client drains the remaining bytes automatically,
// ensuring the underlying TCP connection can be returned to the pool for reuse.
// 3. Write clients may add 429 to RetryOnStatus (online query clients keep the default 502/503/504; see read/write isolation below);
// also configure a RetryOnError that skips timeouts and a RetryBackoff with random jitter (return 0 when attempt > MaxRetries to avoid an extra wait after the last failure).
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, compatible with both client.Perform and esutil.NewBulkIndexer)
client, err := elasticsearch.NewTypedClient(elasticsearch.Config{
Addresses: []string{os.Getenv("ES_ENDPOINT")},
Username: os.Getenv("ES_USER"),
Password: os.Getenv("ES_PASSWORD"),
Transport: transport,
RetryOnStatus: []int{429, 502, 503, 504}, // Write clients may retry 429; online query clients keep only 502/503/504 (see read/write isolation below)
MaxRetries: 3,
AutoDrainBody: true,
RetryOnError: func(_ *http.Request, err error) bool {
// Do not retry timeout errors: avoid resending a timed-out slow query 4 times in a row, which piles up and worsens congestion
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
return false
}
var ne net.Error
return !(errors.As(err, &ne) && ne.Timeout())
},
RetryBackoff: func(attempt int) time.Duration {
if attempt > 3 {
return 0 // elastic-transport-go also calls backoff after the last failure; return 0 to avoid a pointless wait
}
base := time.Duration(1<<attempt) * 100 * time.Millisecond
return base + rand.N(base) // Use math/rand/v2 lock-free random jitter to avoid a thundering herd when many goroutines retry at once
},
})
PYTHON
# Install dependencies (v9.5.x requires Python 3.10+):
# python -m pip install 'elasticsearch>=9.5.0,<10.0.0'
# Required configuration for high concurrency:
# 1. Always set headers={"accept": "application/json"}:
# The Python v9 client automatically appends a version number to Content-Type; if the request headers have no matching Accept,
# calling generic APIs such as collection creation returns 400 due to a media-type mismatch.
# 2. The connection count must be >= the maximum number of concurrent threads:
# The Python client connection pool has only 10 connections by default, and new threads block and queue (block=True) when all are in use,
# which easily stalls locally on the client under multithreaded high concurrency; enlarge connections_per_node to >= peak concurrent threads (e.g. 100).
# 3. Explicitly set retry_on_status=(502, 503, 504) (remove the default 429):
# Python v9.5.x includes 429 in retry_on_status by default and does not sleep on status-code retries (retry_backoff_base applies only to connection errors).
# For 429 throttling, retry at the business layer with random jitter after excluding search_timeout_exception, or let helpers.bulk(..., raise_on_error=False) back off and resend.
from elasticsearch import Elasticsearch
import os
client = Elasticsearch(
os.environ["ES_ENDPOINT"],
basic_auth=(os.environ["ES_USER"], os.environ["ES_PASSWORD"]),
headers={"accept": "application/json"},
connections_per_node=100,
request_timeout=30,
max_retries=3,
retry_on_status=(502, 503, 504),
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
// Required configuration for high concurrency:
// 1. Run only on server-side Node.js (22 or later); never bundle the username and password into front-end web code.
// 2. The v9 client uses an undici connection pool by default (up to 256 concurrent connections per node, with keep-alive reuse);
// reuse a single Client globally and call await client.close() before exit.
// If a single process issues more than 256 concurrent requests, pass agent: { connections: 512 } to raise the cap.
// 3. Note: the built-in maxRetries only auto-retries network failures and 502/503/504, not 429;
// under high-concurrency search or write, catch 429 at the business layer (err.meta?.statusCode === 429) and retry after a random sleep.
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 },
requestTimeout: 30000,
maxRetries: 3,
})
JAVA
// Maven dependencies (JDK 17+):
// co.elastic.clients:elasticsearch-java:9.5.6 + com.fasterxml.jackson.core:jackson-databind
//
// Required configuration for high concurrency:
// 1. Rest5Client allows only 10 concurrent connections per route by default (DEFAULT_MAX_CONN_PER_ROUTE = 10), with a total cap of 30.
// Agentic ES uses a single fixed endpoint, so under high concurrency be sure to enlarge MaxConnTotal and MaxConnPerRoute (e.g. 200) and set ConnectionRequestTimeout to fail fast.
// 2. Explicitly call disableAutomaticRetries() to turn off the underlying HttpClient5 default retry, avoiding double retries stacked with the upper-layer RetryConfig;
// also enable evictExpiredConnections() + evictIdleConnections(30s) + setTimeToLive(2m) to avoid reusing half-closed connections after the cloud load balancer silently drops them.
// 3. The built-in BackoffPolicy.exponentialBackoff has no random jitter; for high-concurrency 429, use a custom jittered exponential backoff;
// also set retryableExceptions(Set.of()) to skip retrying timeout exceptions (IOException is included by default), preventing resends from amplifying traffic after a slow-query timeout.
// Note: RetryConfig applies only to ElasticsearchClient; when calling restClient.performRequest(...) directly, handle 503/429 retries yourself.
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));
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; // 200ms, 400ms, 800ms
return base + ThreadLocalRandom.current().nextLong(base);
})
.iterator();
}
};
RetryConfig retryConfig = RetryConfig.of(r -> r
.retryableStatuses(429, 502, 503, 504) // Write clients may retry 429; online query clients keep only 502/503/504 (see read/write isolation below)
.retryableExceptions(Set.of()) // Skip retrying timeout exceptions to avoid resends amplifying traffic after a slow-query timeout
.backoffPolicy(jitterBackoff));
ElasticsearchClient client = new ElasticsearchClient(new Rest5ClientTransport(
restClient, new JacksonJsonpMapper(), new Rest5ClientOptions(RequestOptions.DEFAULT, false, retryConfig)));
Core client configuration by language
|
Configuration item |
|
|
|
|
|
Connection pool |
|
|
Defaults to |
|
|
Status-code retries |
Write clients retry |
Explicitly set |
Retries only |
|
|
Key details |
Enable |
Always set |
Run on server-side Node 22+; on exit, call |
|
Read/write isolation and preventing slow queries from starving others (required for high concurrency)
Agentic ES provides only a single fixed endpoint ES_ENDPOINT, but this does not mean you can create only one Client instance in your code. If the same application performs real-time writes and sub-second hot-data queries alongside cold-Slice searches, large aggregations, or Scroll bulk exports, and they share the same connection pool or thread pool, slow queries occupy all connections and threads, starving subsequent writes and normal queries. Follow these three isolation principles:
-
Split into independent
Clientinstances by scenario (connection-pool bulkhead isolation): createwriteClient(write-only),readClient(online fast reads only) andheavyClient(cold queries / large aggregations / exports only).-
Even when they all connect to the same
ES_ENDPOINT, independentlynew-created clients each own a separate connection pool, so no matter how congested slow queries get, they cannot steal connections from writes and fast reads. -
Do not misuse "sub-clients":
PYTHONclient.options(...),JAVASCRIPTclient.child(...), andJAVAclient.withTransportOptions(...)still share the parent client connection pool, providing no isolation. You must instantiate clients separately (JAVArequires creating separateRest5Clientinstances). -
Set a lower concurrency cap for the heavy-query pool: the total per-Slice query concurrency cap is
16(counted globally per Slice on the server side). Keep the per-processheavyClientconnection cap low (e.g.4:GOsetMaxConnsPerHost = 4,PYTHONsetconnections_per_node=4,JSsetagent: { connections: 4 },JAVAsetsetMaxConnPerRoute(4)), and reserve enough quota for online fast reads in multi-replica deployments (or confine export tasks to a dedicated single-instance worker).
-
-
Also separate business thread pools and coroutine queues: In
GO/PYTHON/JAVA, never put large bulk exports/slow queries and online writes/fast reads into the same fixed-size worker thread pool; otherwise, when worker threads are saturated by slow queries, write requests already stall while queuing on the client. -
Set timeouts on both the client and the server, and do not retry slow-query timeouts (note that a timeout also returns
429):-
After a client configured with only an HTTP timeout (such as
context.WithTimeout,request_timeout, orresponseTimeout) disconnects, a slow query may keep running on the server and still occupy one of the per-Slice16query slots. When issuing an online search or a heavy query, also pass the server-side parametertimeout(such as"timeout": "2s") orterminate_after, so the server also actively terminates the query and releases resources when time is up. -
Distinguish "throttling
429" from "query timeout429": When a request carries bothallow_partial_search_results=falseand a server-sidetimeout, a server-side timeout also returns HTTP429(error.root_cause[].typeissearch_timeout_exception). Therefore the online fast-read client (fastReadClient) should not auto-retry429at the transport layer (auto-retry only502/503/504); if the business layer retries429with backoff, it must first excludesearch_timeout_exception. -
Do not auto-retry HTTP timeouts:
GOauto-retries after an HTTP timeout by default, andMaxRetries: 0falls back to the default of 3 (you must useDisableRetry: trueto disable retries);JAVArequires disabling low-level retries and settingretryableExceptions(Set.of());PYTHON(defaults toretry_on_timeout=False) andJAVASCRIPTdo not retry request timeouts by default.
-
GO
// Shared helpers: skip-timeout retry predicate and jittered backoff (used by both write and fast-read clients; returns 0 when attempt > maxRetries to avoid an extra wait after the last failure)
skipTimeout := func(_ *http.Request, err error) bool {
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
return false
}
var ne net.Error
return !(errors.As(err, &ne) && ne.Timeout())
}
makeJitterBackoff := func(maxRetries int) func(int) time.Duration {
return func(attempt int) time.Duration {
if attempt > maxRetries {
return 0
}
base := time.Duration(1<<attempt) * 100 * time.Millisecond
return base + rand.N(base)
}
}
// 1. Write-only client: a large connection pool, jittered-backoff retries for 429/5xx, and no retry on timeouts
writeTransport := http.DefaultTransport.(*http.Transport).Clone()
writeTransport.MaxIdleConns = 200
writeTransport.MaxIdleConnsPerHost = 200
writeTransport.ResponseHeaderTimeout = 15 * time.Second
writeClient, _ := elasticsearch.NewTypedClient(elasticsearch.Config{
Addresses: []string{os.Getenv("ES_ENDPOINT")},
Username: os.Getenv("ES_USER"),
Password: os.Getenv("ES_PASSWORD"),
Transport: writeTransport,
AutoDrainBody: true,
RetryOnStatus: []int{429, 502, 503, 504},
MaxRetries: 3,
RetryOnError: skipTimeout,
RetryBackoff: makeJitterBackoff(3),
})
// 2. Online fast-read-only client: an independent connection pool + short timeout + retries only 502/503/504 by default (does not auto-retry a 429 query timeout)
fastReadTransport := http.DefaultTransport.(*http.Transport).Clone()
fastReadTransport.MaxIdleConns = 200
fastReadTransport.MaxIdleConnsPerHost = 200
fastReadTransport.ResponseHeaderTimeout = 3 * time.Second
fastReadClient, _ := elasticsearch.NewTypedClient(elasticsearch.Config{
Addresses: []string{os.Getenv("ES_ENDPOINT")},
Username: os.Getenv("ES_USER"),
Password: os.Getenv("ES_PASSWORD"),
Transport: fastReadTransport,
AutoDrainBody: true,
MaxRetries: 2,
RetryOnError: skipTimeout,
RetryBackoff: makeJitterBackoff(2),
})
// 3. Heavy-query/export-only client: per-instance concurrency capped at 4 (plan global concurrency across replicas and reserve enough quota for online fast reads) + DisableRetry to turn off retries
heavyTransport := http.DefaultTransport.(*http.Transport).Clone()
heavyTransport.MaxConnsPerHost = 4
heavyTransport.MaxIdleConnsPerHost = 4
heavyTransport.ResponseHeaderTimeout = 30 * time.Second
heavyClient, _ := elasticsearch.NewTypedClient(elasticsearch.Config{
Addresses: []string{os.Getenv("ES_ENDPOINT")},
Username: os.Getenv("ES_USER"),
Password: os.Getenv("ES_PASSWORD"),
Transport: heavyTransport,
AutoDrainBody: true,
DisableRetry: true, // Note: setting MaxRetries: 0 falls back to the default of 3; you must use DisableRetry: true to turn off retries
})
// For online queries, also pass the server-side timeout parameter so the client and server both cut losses
res, err := fastReadClient.Search().
Index("demo-knowledge-chunks").
Routing("kb-a").
Timeout("2s").
Query(&types.Query{Match: map[string]types.MatchQuery{"content": {Query: "refund"}}}).
Do(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Println(res.Hits.Hits)
PYTHON
import os
from elasticsearch import Elasticsearch
common = dict(
hosts=os.environ["ES_ENDPOINT"],
basic_auth=(os.environ["ES_USER"], os.environ["ES_PASSWORD"]),
headers={"accept": "application/json"},
)
# Note: do not use client.options(...) instead of multiple instances — options() still shares the underlying connection pool!
# The Python transport does not sleep on status-code retries, so both write and query use (502, 503, 504); 429 throttling is handled with backoff at the business layer or in helpers.bulk
# 1. Write-only client
write_client = Elasticsearch(
**common,
connections_per_node=100,
request_timeout=15,
max_retries=3,
retry_on_status=(502, 503, 504),
retry_backoff_base=0.2, # Backs off only on connection errors (status-code retries do not sleep)
retry_backoff_cap=2,
)
# 2. Online fast-read-only client (exclude 429 to avoid retrying search_timeout_exception; keep retry_on_timeout=False)
fast_read_client = Elasticsearch(
**common,
connections_per_node=100,
request_timeout=3,
max_retries=2,
retry_on_status=(502, 503, 504),
retry_backoff_base=0.2,
retry_backoff_cap=2,
retry_on_timeout=False,
)
# 3. Slow-query/export-only client (per-instance cap of 4; plan global concurrency across replicas; retries disabled)
heavy_client = Elasticsearch(
**common, connections_per_node=4, request_timeout=30, max_retries=0, retry_on_timeout=False
)
# Also pass the server-side timeout="2s" on queries so the client and server cut losses together
res = fast_read_client.search(
index="demo-knowledge-chunks",
routing="kb-a",
timeout="2s",
query={"match": {"content": "refund"}},
)
JAVASCRIPT
import { Client } from '@elastic/elasticsearch'
const auth = { username: process.env.ES_USER, password: process.env.ES_PASSWORD }
// Note: do not use client.child() for isolation — child() still shares the parent client undici connection pool!
// 1. Write-only client
const writeClient = new Client({
node: process.env.ES_ENDPOINT,
auth,
requestTimeout: 15000,
maxRetries: 3,
agent: { connections: 128 },
})
// 2. Online fast-read-only client (short timeout; the client does not retry request timeouts or 429 by default; an independent connection pool unaffected by slow queries and writes)
const fastReadClient = new Client({
node: process.env.ES_ENDPOINT,
auth,
requestTimeout: 3000,
maxRetries: 2,
agent: { connections: 128 },
})
// 3. Slow-query/export-only client (per-instance cap of 4; plan global concurrency across replicas)
const heavyClient = new Client({
node: process.env.ES_ENDPOINT,
auth,
requestTimeout: 30000,
maxRetries: 0,
agent: { connections: 4 },
})
// Also pass the server-side timeout: '2s' on queries, so a disconnected slow query does not keep occupying a server-side concurrency slot
const res = await fastReadClient.search({
index: 'demo-knowledge-chunks',
routing: 'kb-a',
timeout: '2s',
query: { match: { content: 'refund' } },
})
JAVA
// Note: do not use client.withTransportOptions(...) instead of multiple instances — it still shares the underlying Rest5Client connection pool!
// Build 3 independent Rest5Client + ElasticsearchClient pairs to fully isolate connection pools and timeouts:
// 1. Write-only client (large connection pool + relaxed timeout + jittered-backoff retries for 429/5xx)
Rest5Client writeRest = 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(15)))
.setHttpClientConfigCallback(hc -> hc
.disableAutomaticRetries().evictExpiredConnections().evictIdleConnections(TimeValue.ofSeconds(30)))
.build();
ElasticsearchClient writeClient = new ElasticsearchClient(new Rest5ClientTransport(
writeRest, new JacksonJsonpMapper(), new Rest5ClientOptions(
RequestOptions.DEFAULT, false,
RetryConfig.of(r -> r.retryableStatuses(429, 502, 503, 504)
.retryableExceptions(Set.of())
.backoffPolicy(jitterBackoff)))));
// 2. Online fast-read-only client (independent connection pool + short timeout + auto-retry only 502/503/504, preventing a 429 timeout from being resent as throttling)
Rest5Client fastReadRest = 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(1))
.setResponseTimeout(Timeout.ofSeconds(3)))
.setHttpClientConfigCallback(hc -> hc
.disableAutomaticRetries().evictExpiredConnections().evictIdleConnections(TimeValue.ofSeconds(30)))
.build();
ElasticsearchClient fastReadClient = new ElasticsearchClient(new Rest5ClientTransport(
fastReadRest, new JacksonJsonpMapper(), new Rest5ClientOptions(
RequestOptions.DEFAULT, false,
RetryConfig.of(r -> r.retryableStatuses(502, 503, 504)
.retryableExceptions(Set.of())
.backoffPolicy(jitterBackoff)))));
// 3. Slow-query/export-only client (per-instance cap of 4; plan global concurrency across replicas + retries fully disabled)
Rest5Client heavyRest = 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(4).setMaxConnPerRoute(4))
.setRequestConfigCallback(rc -> rc
.setConnectionRequestTimeout(Timeout.ofSeconds(3))
.setResponseTimeout(Timeout.ofSeconds(30)))
.setHttpClientConfigCallback(hc -> hc
.disableAutomaticRetries().evictExpiredConnections().evictIdleConnections(TimeValue.ofSeconds(30)))
.build();
ElasticsearchClient heavyClient = new ElasticsearchClient(new Rest5ClientTransport(
heavyRest, new JacksonJsonpMapper(), new Rest5ClientOptions(
RequestOptions.DEFAULT, false, RetryConfig.disabled())));
// For online queries, also pass the server-side timeout("2s") so the client and server both cut losses
SearchResponse<Map> res = fastReadClient.search(s -> s
.index("demo-knowledge-chunks")
.routing("kb-a")
.timeout("2s")
.query(q -> q.match(m -> m.field("content").query("refund"))),
Map.class);
2. _slice parameter placement
|
Operation type |
How to pass the parameter |
Example |
|
Single-document reads/writes (GET / Index) and Search |
URL query parameter |
|
|
Writing to multiple different Slices in one Bulk request |
Specify the Slice in the operation header (for hand-written raw NDJSON use |
|
|
Set the default Slice for single-table mode |
When creating the Collection, set the top-level request body field |
|
|
|
Do not use the URL |
|
Notes:
-
_sliceandrouting— choose one: The two are fully equivalent; pass only one per request (passing both returns400). -
Do not write platform routing identifiers from responses back as business Slice names: The
_routingor_indexreturned in read or search responses are platform routing identifiers. In business code, always use the Slice and Collection names you defined. -
Distinguish the
"slice"in the query body: in the_searchrequest body, the"slice"is a slicing parameter forScrollbatched parallel exports, not the business Slice_slice.
3. Continuous bulk writes and concurrency/queue pitfalls
The per-Slice write throughput cap is 32 MiB/s (a single write to the same Slice also cannot exceed 32 MiB), and the single HTTP request body cap is 100 MiB (exceeding it returns 413). Keep each Bulk batch within 2-5 MiB.
For continuous large-volume imports, use the Bulk helpers of each language SDK (GO esutil.BulkIndexer PYTHON helpers.bulk / streaming_bulk, JAVASCRIPT client.helpers.bulk, JAVA BulkIngester); this avoids local queue blocking or retry deadlocks under high QPS that occur with default configurations:
Why also handle per-item 429? When you pack multiple records into a single /_bulk request, even if the per-Slice 32 MiB/s throttling is triggered, the outer HTTP request may still return 200, while the many (or even all) records in that batch sent to the same throttled Slice return items within status: 429. In this case the client transport-layer auto-retry does not take effect; the Bulk helper or your business code must pick them out, slow down, and resend with backoff.
GO
// Required esutil.BulkIndexer tuning for high concurrency (avoid the default config stalling business goroutines):
// 1. QueueSizeMultiplier defaults to 1 (Add blocks at the slightest slowdown); enlarge it for high QPS (e.g. 64). FlushInterval is recommended at 2s + 500ms jitter.
// 2. Never Sleep, do a blocking channel send, or call indexer.Add() inside the OnFailure callback (it stalls the worker or panics on Close).
// Correct approach: write non-blockingly to an external retry queue and let a background goroutine resend; for sustained widespread 429, first slow down on the write side, and persist dead letters when the queue is full or retries are exhausted.
// (If the same _id is updated concurrently, replaying old data may overwrite a newer version; combine with an external version number or use only for one-off imports.)
type retryItem struct {
id, slice string
payload []byte
}
retryQueue := make(chan retryItem, 4096)
var retryWG sync.WaitGroup
retryWG.Add(1)
go func() {
defer retryWG.Done()
for r := range retryQueue {
var lastErr error
for attempt := range 3 {
base := time.Duration(1<<attempt) * 150 * time.Millisecond
time.Sleep(base + rand.N(base))
// Use an independent one-shot timeout so queued items can still be drained after the business ctx is canceled during graceful shutdown
reqCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
_, lastErr = client.Index("demo-knowledge-chunks").
Id(r.id).Routing(r.slice).Raw(bytes.NewReader(r.payload)).Do(reqCtx)
cancel()
if lastErr == nil {
break
}
}
if lastErr != nil {
log.Printf("429 retries exhausted, moving to dead-letter compensation: id=%s slice=%s err=%v", r.id, r.slice, lastErr)
}
}
}()
indexer, err := esutil.NewBulkIndexer(esutil.BulkIndexerConfig{
Client: client,
Index: "demo-knowledge-chunks",
NumWorkers: 8, // Multi-Slice imports can run in parallel; when writing to a single Slice, lower the worker count per the 32 MiB/s limit
FlushBytes: 5_000_000, // Auto-commit each batch at about 5 MB
FlushInterval: 2 * time.Second, // Flush the trailing data after at most 2 seconds (the 30-second default is too long)
FlushJitter: 500 * time.Millisecond, // Stagger the flush cadence across workers to avoid spikes
QueueSizeMultiplier: 64, // Enlarge per-worker buffer slots to prevent Add() from blocking
})
if err != nil {
log.Fatal(err)
}
data, err := json.Marshal(map[string]any{
"title": "Refund policy",
"category": "after-sales",
})
if err != nil {
log.Fatal(err)
}
// This example demonstrates "index" (overwrite or insert) writes and 429 retries;
// If you also use "create" (insert-only, no overwrite) or "delete", retryItem must also store the Action and replay the original operation (create goes to /_create/{id}, delete goes to DELETE).
err = indexer.Add(ctx, esutil.BulkIndexerItem{
Action: "index",
DocumentID: "bulk-1001",
Routing: "kb-a", // Equivalent to _slice; for hand-written raw NDJSON, use "_slice" instead
Body: bytes.NewReader(data),
OnFailure: func(_ context.Context, item esutil.BulkIndexerItem, res esutil.BulkIndexerResponseItem, err error) {
// create+409 (document already exists) or delete+404 (does not exist) is usually an expected state
if err == nil && ((item.Action == "create" && res.Status == 409) ||
(item.Action == "delete" && res.Status == 404)) {
return
}
if err == nil && res.Status == 429 {
// Write non-blockingly to an external retry queue (never Sleep, do a blocking channel send, or call indexer.Add here)
if _, seekErr := item.Body.Seek(0, io.SeekStart); seekErr == nil {
if raw, readErr := io.ReadAll(item.Body); readErr == nil {
select {
case retryQueue <- retryItem{id: item.DocumentID, slice: item.Routing, payload: raw}:
default:
log.Printf("Retry queue full, moving to dead-letter compensation: id=%s slice=%s", item.DocumentID, item.Routing)
}
}
}
return
}
log.Printf("Write failed (record dead-letter compensation) id=%s status=%d err=%v reason=%s", item.DocumentID, res.Status, err, res.Error.Reason)
},
})
if err != nil {
log.Fatalf("Enqueue failed: %v", err)
}
// Graceful shutdown: call Close with an independent timeout ctx, and close retryQueue to drain only after Close returns normally (to avoid in-flight workers panicking on a closed channel;
// in production, bound the drain time to the container termination grace period and persist undrained items as dead letters)
shutdownCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := indexer.Close(shutdownCtx); err != nil {
log.Printf("indexer.Close error (check dead-letter compensation): %v", err)
} else {
close(retryQueue)
retryWG.Wait()
}
PYTHON
import random
import time
from elasticsearch import helpers
actions = [
{
"_op_type": "index", # Overwrite or insert; set to "create" for insert-only (no overwrite)
"_index": "demo-knowledge-chunks",
"_id": "bulk-1001",
"_routing": "kb-a", # Equivalent to _slice
"_source": {"title": "Refund policy", "category": "after-sales"},
}
]
# Notes:
# 1. helpers.bulk defaults to a 100 MiB batch and max_retries=0; you must also set raise_on_error=False for max_retries to take effect on individual 429s.
# 2. For tens of millions of records or large multi-Slice imports, prefer helpers.streaming_bulk (pass max_chunk_bytes and raise_on_error=False;
# to zip-align with the original documents by position, keep the default max_retries=0 and resend 429 at the business layer with jittered backoff; parallel_bulk is not recommended).
success_count, errors = helpers.bulk(
client,
actions,
max_chunk_bytes=5 * 1024 * 1024,
max_retries=3,
initial_backoff=0.2,
raise_on_error=False,
)
# With raise_on_error=False, errors contains only _id/status/error; for multiple Slices, use streaming_bulk (max_retries=0) to align by order, and for a single-Slice batch, look up by _id
retry_ids, fatal_errors = [], []
for err_item in errors:
op_type, info = next(iter(err_item.items()))
status = info.get("status")
if (op_type == "create" and status == 409) or (op_type == "delete" and status == 404):
continue
if status == 429:
retry_ids.append(info.get("_id"))
else:
fatal_errors.append(info)
if retry_ids:
time.sleep(0.2 + random.uniform(0, 0.2))
# Use retry_ids to fetch the documents from the same Slice original batch and resend with backoff or write to dead letters...
if fatal_errors:
raise RuntimeError(f"Bulk per-item write failed ({len(fatal_errors)} items in total), example: {fatal_errors[:3]}")
JAVASCRIPT
import { setTimeout as sleep } from 'node:timers/promises'
const documents = [
{ id: 'bulk-1001', sliceName: 'kb-a', title: 'Refund policy', category: 'after-sales' },
{ id: 'bulk-1001', sliceName: 'kb-b', title: 'Logistics query', category: 'shipping' },
]
// Best-practice configuration for high throughput:
// 1. concurrency defaults to 5, flushInterval to 30000ms, and wait to 5000ms.
// On a single-item 429, the default wait: 5000 makes a concurrency slot idle for a full 5 seconds!
// Setting flushInterval: 2000, wait: 500, and concurrency: 8 noticeably reduces queue backlog and tail-batch latency.
// 2. Note: when the whole batch is throttled and returns HTTP 429 directly (rather than an outer 200 with per-item 429),
// helpers.bulk throws a ResponseError directly; catch it externally, retry with random backoff, and keep each batch within 2-5 MiB.
try {
const stats = await client.helpers.bulk({
datasource: documents,
flushBytes: 5_000_000, // About 5 MB per batch (avoid exceeding the 32 MiB per-Slice limit in a single request)
flushInterval: 2000, // Flush the trailing partial batch after at most 2 seconds
concurrency: 8, // Number of parallel batches across Slices (lower it per the 32 MiB/s limit when writing to a single Slice)
retries: 3, // Auto-retry a single-item 429 up to 3 times
wait: 500, // Wait 500ms per single-item 429 (avoid the default 5000ms hogging a concurrency slot)
refreshOnCompletion: false, // Do not force a refresh after writes
onDocument(doc) {
return [
// First item: operation metadata (index overwrites or inserts; use create for insert-only, no overwrite)
{ index: { _index: 'demo-knowledge-chunks', _id: doc.id, routing: doc.sliceName } },
// Second item: the actual business document (avoid writing control fields such as sliceName into _source)
{ title: doc.title, category: doc.category },
]
},
onDrop(doc) {
if (doc.status === 409) return
console.error('Write still failed after retries exhausted; compensate and resend:', doc.status, doc.error, doc.document)
},
})
console.log('Bulk stats:', stats)
} catch (err) {
if (err?.meta?.statusCode === 429) {
await sleep(300 + Math.random() * 300)
// Back off and resend the failed batch here...
} else {
throw err
}
}
JAVA
// Required BulkIngester tuning for high concurrency (avoid serial slow writes or callback blocking):
// 1. maxConcurrentRequests defaults to only 1 (serial requests); enlarge it for high-throughput writes (e.g. 4-8);
// 2. Keep maxSize within 2-5 MiB (e.g. 4 MiB), together with flushInterval(2, SECONDS) to balance throughput and timely flushing;
// 3. BulkIngester natively auto-retries a single-item status == 429: after passing a jittered backoffPolicy,
// the internal scheduler asynchronously backs off and resends 429 items; BulkListener only needs to handle alerting or dead-letter persistence for items that "still fail after retries are exhausted" (never Thread.sleep in the callback).
record DocItem(String id, String slice, Map<String, Object> doc) {}
List<DocItem> docs = List.of(
new DocItem("bulk-1001", "kb-a", Map.of("title", "Refund policy", "category", "after-sales")),
new DocItem("bulk-1001", "kb-b", Map.of("title", "Logistics query", "category", "shipping"))
);
BulkListener<DocItem> listener = new BulkListener<>() {
@Override
public void beforeBulk(long executionId, BulkRequest request, List<DocItem> contexts) {}
@Override
public void afterBulk(long executionId, BulkRequest request, List<DocItem> contexts, BulkResponse response) {
if (!response.errors()) {
return;
}
var items = response.items();
for (int i = 0; i < items.size(); i++) {
var item = items.get(i);
if (item.error() != null) {
// Reaching here means the backoffPolicy retries are exhausted or this is a non-429 business error; record a dead letter / compensate
System.err.printf("Bulk per-item final failure id=%s slice=%s status=%d reason=%s%n",
item.id(), contexts.get(i).slice(), item.status(), item.error().reason());
}
}
}
@Override
public void afterBulk(long executionId, BulkRequest request, List<DocItem> contexts, Throwable failure) {
System.err.printf("Bulk batch exception count=%d err=%s%n", contexts.size(), failure.getMessage());
}
};
try (BulkIngester<DocItem> ingester = BulkIngester.of(b -> b
.client(writeClient)
.maxOperations(500)
.maxSize(4 * 1024 * 1024L)
.maxConcurrentRequests(4)
.flushInterval(2, TimeUnit.SECONDS)
.backoffPolicy(jitterBackoff)
.listener(listener))) {
for (DocItem item : docs) {
ingester.add(op -> op.index(idx -> idx
.index("demo-knowledge-chunks")
.id(item.id())
.routing(item.slice())
.document(item.doc())), item);
}
}
4. Complete runnable examples (create a collection, bulk-write, read by ID, and search)
The following single-file examples demonstrate the full flow: create a Collection → write documents to kb-a and kb-b with the same ID (chunk-1001) → read by ID in real time → wait for the automatic background refresh, then search.
GO
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"math/rand/v2"
"net"
"net/http"
"os"
"strings"
"time"
"github.com/elastic/go-elasticsearch/v9"
"github.com/elastic/go-elasticsearch/v9/typedapi/some"
"github.com/elastic/go-elasticsearch/v9/typedapi/types"
)
func run() error {
transport := http.DefaultTransport.(*http.Transport).Clone()
transport.MaxIdleConns = 200
transport.MaxIdleConnsPerHost = 200
transport.ResponseHeaderTimeout = 30 * time.Second
client, err := elasticsearch.NewTypedClient(elasticsearch.Config{
Addresses: []string{os.Getenv("ES_ENDPOINT")},
Username: os.Getenv("ES_USER"),
Password: os.Getenv("ES_PASSWORD"),
Transport: transport,
RetryOnStatus: []int{502, 503, 504}, // In production, split write/fast-read into independent Clients; see read/write isolation in section 1
MaxRetries: 3,
AutoDrainBody: true,
RetryOnError: func(_ *http.Request, err error) bool {
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
return false
}
var ne net.Error
return !(errors.As(err, &ne) && ne.Timeout())
},
RetryBackoff: func(attempt int) time.Duration {
if attempt > 3 {
return 0
}
base := time.Duration(1<<attempt) * 100 * time.Millisecond
return base + rand.N(base)
},
})
if err != nil {
return err
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
const collection = "demo-sdk-go"
// 1. Create the Collection (call the extended management API via client.Perform; enable dynamic: "strict" field validation)
createReq, err := http.NewRequestWithContext(ctx, "PUT", "/_slice_collection/"+collection, strings.NewReader(
`{"mappings":{"dynamic":"strict","properties":{"title":{"type":"text"},"category":{"type":"keyword"}}}}`))
if err != nil {
return err
}
createReq.Header.Set("Content-Type", "application/json")
createResp, err := client.Perform(createReq)
if err != nil {
return err
}
raw, err := io.ReadAll(createResp.Body)
createResp.Body.Close()
if err != nil {
return err
}
if createResp.StatusCode >= 300 {
return fmt.Errorf("HTTP %d: %s", createResp.StatusCode, strings.TrimSpace(string(raw)))
}
var created struct {
Acknowledged bool `json:"acknowledged"`
}
if err := json.Unmarshal(raw, &created); err != nil || !created.Acknowledged {
return fmt.Errorf("Check the Collection creation status and configuration: %s", string(raw))
}
// 2. Bulk-write documents with the same ID (chunk-1001) to kb-a and kb-b; they do not overwrite each other
bulkReq := client.Bulk()
if err := bulkReq.IndexOp(
types.IndexOperation{Index_: some.String(collection), Id_: some.String("chunk-1001"), Routing: some.String("kb-a")},
map[string]any{"title": "Refund policy", "category": "after-sales"},
); err != nil {
return err
}
if err := bulkReq.IndexOp(
types.IndexOperation{Index_: some.String(collection), Id_: some.String("chunk-1001"), Routing: some.String("kb-b")},
map[string]any{"title": "Logistics query", "category": "shipping"},
); err != nil {
return err
}
bulkRes, err := bulkReq.Do(ctx)
if err != nil {
return err
}
if bulkRes.Errors {
return fmt.Errorf("Bulk partially failed: %+v", bulkRes.Items)
}
// 3. Read by ID in real time (visible immediately after the write; standard methods specify the Slice via Routing)
document, err := client.Get(collection, "chunk-1001").Routing("kb-a").Do(ctx)
if err != nil {
return err
}
fmt.Println(string(document.Source_))
// 4. Run a search (wait for the automatic background refresh within a few seconds; do not call _refresh in regular business writes)
for attempt := 0; attempt < 20; attempt++ {
result, err := client.Search().
Index(collection).
Routing("kb-a").
AllowPartialSearchResults(false).
Query(&types.Query{Term: map[string]types.TermQuery{"category": {Value: "after-sales"}}}).
Do(ctx)
if err != nil {
return err
}
if result.TimedOut || result.Shards_.Failed != 0 {
return fmt.Errorf("Search timed out or has failed shards")
}
if result.Hits.Total != nil && result.Hits.Total.Value == 1 {
fmt.Println(result.Hits.Hits)
return nil
}
time.Sleep(time.Second)
}
return fmt.Errorf("Data is not yet searchable; check the write and refresh status")
}
func main() {
if err := run(); err != nil {
log.Fatal(err)
}
}
PYTHON
import os
import time
from elasticsearch import Elasticsearch
collection = "demo-sdk-python"
slice_name = "kb-a"
json_headers = {"content-type": "application/json"}
with Elasticsearch(
os.environ["ES_ENDPOINT"],
basic_auth=(os.environ["ES_USER"], os.environ["ES_PASSWORD"]),
headers={"accept": "application/json"},
connections_per_node=100,
request_timeout=30,
max_retries=3,
retry_on_status=(502, 503, 504),
retry_backoff_base=0.2, # Backs off only on connection errors (status-code retries do not sleep)
retry_backoff_cap=2,
) as client:
# 1. Create the Collection (enable dynamic: "strict" field validation)
created = client.perform_request(
"PUT", f"/_slice_collection/{collection}",
headers=json_headers,
body={"mappings": {"dynamic": "strict", "properties": {
"title": {"type": "text"},
"category": {"type": "keyword"},
}}},
)
if not created["acknowledged"]:
raise RuntimeError("Check the Collection creation status and configuration")
# 2. Bulk-write documents with the same ID (chunk-1001) to kb-a and kb-b; they do not overwrite each other
bulk = client.bulk(
operations=[
{"index": {"_index": collection, "_id": "chunk-1001", "routing": "kb-a"}},
{"title": "Refund policy", "category": "after-sales"},
{"index": {"_index": collection, "_id": "chunk-1001", "routing": "kb-b"}},
{"title": "Logistics query", "category": "shipping"},
]
)
# An outer HTTP 200 does not mean every item succeeded; check the top-level errors field
if bulk["errors"]:
failures = [item["index"] for item in bulk["items"]
if item["index"]["status"] >= 300]
raise RuntimeError(f"Bulk partially failed: {failures}")
# 3. Read by ID in real time (visible immediately after the write; standard methods specify the Slice via routing)
document = client.get(index=collection, id="chunk-1001", routing=slice_name)
print(document["_source"]) # {'title': 'Refund policy', 'category': 'after-sales'} (from kb-a)
# 4. Run a search (wait for the automatic background refresh within a few seconds; do not call _refresh in regular business code)
for _ in range(20):
result = client.search(
index=collection,
routing=slice_name,
allow_partial_search_results=False,
query={"term": {"category": "after-sales"}},
)
if result["timed_out"] or result["_shards"]["failed"]:
raise RuntimeError("Search timed out or has failed shards")
if result["hits"]["total"]["value"] == 1:
break
time.sleep(1)
else:
raise TimeoutError("Data is not yet searchable; check the write and refresh status")
print(result["hits"]["hits"])
JAVASCRIPT
import { Client } from '@elastic/elasticsearch'
import { setTimeout as sleep } from 'node:timers/promises'
const client = new Client({
node: process.env.ES_ENDPOINT,
auth: { username: process.env.ES_USER, password: process.env.ES_PASSWORD },
requestTimeout: 30000,
maxRetries: 3,
})
const collection = 'demo-sdk-js'
const sliceName = 'kb-a'
try {
// 1. Create the Collection (enable dynamic: 'strict' field validation)
const created = await client.transport.request({
method: 'PUT', path: `/_slice_collection/${collection}`,
body: { mappings: { dynamic: 'strict', properties: {
title: { type: 'text' }, category: { type: 'keyword' }
} } }
})
if (!created.acknowledged) throw new Error('Check the Collection creation status and configuration')
// 2. Bulk-write documents with the same ID (chunk-1001) to kb-a and kb-b; they do not overwrite each other
const bulk = await client.bulk({
operations: [
{ index: { _index: collection, _id: 'chunk-1001', routing: 'kb-a' } },
{ title: 'Refund policy', category: 'after-sales' },
{ index: { _index: collection, _id: 'chunk-1001', routing: 'kb-b' } },
{ title: 'Logistics query', category: 'shipping' },
],
})
if (bulk.errors) {
const failures = bulk.items.map(item => item.index).filter(item => item.status >= 300)
throw new Error(`Bulk partially failed: ${JSON.stringify(failures)}`)
}
// 3. Read by ID in real time (visible immediately after the write; standard methods specify the Slice via routing)
const document = await client.get({
index: collection,
id: 'chunk-1001',
routing: sliceName,
})
console.log(document._source) // { title: 'Refund policy', category: 'after-sales' } (from kb-a)
// 4. Run a search (wait for the automatic background refresh within a few seconds; do not call _refresh in regular business writes)
let visible = false
for (let attempt = 0; attempt < 20; attempt++) {
const result = await client.search({
index: collection,
routing: sliceName,
allow_partial_search_results: false,
query: { term: { category: 'after-sales' } },
})
if (result.timed_out || result._shards.failed) throw new Error('Search timed out or has failed shards')
if (result.hits.total.value === 1) {
console.log(result.hits.hits)
visible = true
break
}
await sleep(1000)
}
if (!visible) throw new Error('Data is not yet searchable; check the write and refresh status')
} finally {
await client.close()
}
JAVA
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.BulkResponse;
import co.elastic.clients.elasticsearch.core.GetResponse;
import co.elastic.clients.elasticsearch.core.SearchResponse;
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.Request;
import co.elastic.clients.transport.rest5_client.low_level.RequestOptions;
import co.elastic.clients.transport.rest5_client.low_level.Response;
import co.elastic.clients.transport.rest5_client.low_level.Rest5Client;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.io.entity.EntityUtils;
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.Map;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.IntStream;
public class AgenticEsQuickstart {
public static void main(String[] args) throws Exception {
String endpoint = System.getenv("ES_ENDPOINT");
String user = System.getenv("ES_USER");
String password = System.getenv("ES_PASSWORD");
String collection = "demo-sdk-java";
String basic = "Basic " + Base64.getEncoder()
.encodeToString((user + ":" + password).getBytes(StandardCharsets.UTF_8));
Rest5Client restClient = Rest5Client.builder(URI.create(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) // In production, split write/fast-read into independent Clients; see read/write isolation in section 1
.retryableExceptions(Set.of())
.backoffPolicy(jitterBackoff));
try (ElasticsearchClient client = new ElasticsearchClient(new Rest5ClientTransport(
restClient, new JacksonJsonpMapper(),
new Rest5ClientOptions(RequestOptions.DEFAULT, false, retryConfig)))) {
// 1. Create the Collection (ignore a 400 resource_already_exists_exception when it already exists)
Request createReq = new Request("PUT", "/_slice_collection/" + collection);
createReq.setJsonEntity("""
{
"mappings": {
"dynamic": "strict",
"properties": {
"title": { "type": "text" },
"category": { "type": "keyword" }
}
}
}
""");
Response createResp = restClient.performRequest(createReq);
int status = createResp.getStatusCode();
String createBody = createResp.getEntity() != null
? EntityUtils.toString(createResp.getEntity(), StandardCharsets.UTF_8) : "";
if (status >= 300 && !(status == 400 && createBody.contains("resource_already_exists_exception"))) {
throw new IllegalStateException("Failed to create Collection, HTTP " + status + ": " + createBody);
}
// 2. Write documents with the same ID (chunk-1001) to kb-a and kb-b (routing keeps them isolated)
BulkResponse bulkResp = client.bulk(b -> b
.operations(op -> op.index(idx -> idx
.index(collection).id("chunk-1001").routing("kb-a")
.document(Map.of("title", "Refund policy", "category", "after-sales"))))
.operations(op -> op.index(idx -> idx
.index(collection).id("chunk-1001").routing("kb-b")
.document(Map.of("title", "Logistics query", "category", "shipping")))));
if (bulkResp.errors()) {
throw new IllegalStateException("Bulk has failed items: " + bulkResp.items());
}
// 3. Read by ID in real time (visible immediately after the write; verify the same ID in two Slices does not overwrite)
GetResponse<Map> docA = client.get(
g -> g.index(collection).id("chunk-1001").routing("kb-a"), Map.class);
GetResponse<Map> docB = client.get(
g -> g.index(collection).id("chunk-1001").routing("kb-b"), Map.class);
System.out.println("Real-time read result: " + docA.source().get("title") + " | " + docB.source().get("title"));
// 4. Poll until the automatic background refresh completes, then run a search (do not call _refresh frequently in regular business code)
boolean visible = false;
for (int i = 0; i < 15; i++) {
SearchResponse<Map> res = client.search(s -> s
.index(collection)
.routing("kb-a")
.allowPartialSearchResults(false)
.query(q -> q.term(t -> t.field("category").value("after-sales"))),
Map.class);
if (Boolean.TRUE.equals(res.timedOut()) || res.shards().failed().intValue() > 0) {
throw new IllegalStateException("Search timed out or has failed shards");
}
if (res.hits().total() != null && res.hits().total().value() >= 1) {
System.out.println("Search hits: " + res.hits().hits());
visible = true;
break;
}
Thread.sleep(1000);
}
if (!visible) {
throw new IllegalStateException("Data is not yet searchable; check the write and refresh status");
}
}
}
}
5. Write refresh (refresh) and background async tasks (_tasks)
-
Do not pass the URL
refreshparameter for routine writes: The server ignores the URLrefreshand returns aWarningresponse header instead of waiting for or triggering an immediate refresh. Routine writes can simply rely on the server background refresh every few seconds (only callPOST /{collection}/_refreshexplicitly for very low-frequency strong-consistency debugging). -
Use async tasks for time-consuming operations (
_tasks):_update_by_query,_delete_by_query, and_reindexsupport async submission withwait_for_completion=false; check progress withGET /_tasks/{task_id}and cancel withPOST /_tasks/{task_id}/_cancel(canceling does not roll back already-written data; for Copy Slice tasks use the dedicated_copy/{copy_id}API).Importantcompleted == trueonly indicates the task has finished, not that it succeeded — you must also check theerrorfield in the response and the counts insideresponse(when a task fails,erroris non-empty whileresponse.total/createdisnull), the same as how_copyrequires checkingstate == "SUCCEEDED".
6. Response integrity checklist
|
Request type |
Fields to check beyond HTTP 2xx |
|
Search / KNN / aggregation |
Pass |
|
Bulk write |
Check the top-level |
|
MSearch batch query |
Iterate over the |
|
MGet batch read |
Iterate over the |
|
Slice batch registration |
Check the top-level |
|
Slice copy ( |
|
Common HTTP status codes and error handling (including 400 / 401/403 / 404 / 409 / 410 / 413 / 429 throttling-vs-timeout distinction / 503 / Warning — for the complete troubleshooting reference, see Migration guide, error codes, and FAQ: Common HTTP status codes and error handling.
What to do next
Data retrieval guide (full-text, vector, and hybrid search).