Elasticsearch HTTP API implementation reference
This page describes how the Elasticsearch wire is built: the HTTP listener, Basic authentication, the identity it reports, the full route table, the query DSL and aggregations, scoring and vector search, storage and durability, versioning, errors, limits and tests. For the port, the proof scores, how to connect and how to re-run the suites, see the operator page Elasticsearch. Authentication policy across all wires is in Security.
Code lives in src/protocol/elasticsearch/: mod.rs (listener, HTTP parsing, auth gate, routing, index and document handlers, search, scroll, aliases, templates, persistence), query_dsl.rs (the Query enum and its evaluator), query_string.rs (Lucene query-string syntax), aggs.rs (aggregations), bm25.rs (relevance scoring), knn.rs (dense_vector and kNN), function_score.rs, painless.rs (script expressions), field_types.rs (analyzers and field types), doc_write.rs (document write rules), journal.rs (the per-document write journal) and crosswire.rs (vector search over SynergyDB collections). Crates that matter: serde_json, base64 (Basic credentials), bytes, tokio, uuid (generated document ids). (source: src/protocol/elasticsearch/mod.rs, module declarations and imports)
Listener and connection loop
- The default port is 9200 (
elasticsearch_port). The server builds the handler withwith_storage, orwith_tlswhen a TLS config exists. TLS is implicit: each socket goes throughTlsListener::acceptbefore any HTTP byte is read. (source:src/config.rs;src/server/mod.rs;src/protocol/elasticsearch/mod.rs,ElasticsearchHandler::start) Not verified: no test covers this wire over TLS. - The HTTP/1.1 parser is hand-written. One
BufReaderis kept for the whole connection, so keep-alive requests are not lost between reads. The loop honoursConnection: close. (source:handle_connection) - Only
Content-Lengthbodies are read. A chunked body (Transfer-Encoding: chunked) is not decoded; the request is handled as if it had no body. (source:parse_request) Not verified: no test sends a chunked body. - A declared body over 256 MB (
MAX_HTTP_BODY) is refused before allocation. A body over 1 MB (PREAUTH_BODY_LIMIT) is read only if the headers already passauthenticate. A parse error, including both size refusals, closes the connection without an HTTP response. (source:parse_request,MAX_HTTP_BODY;src/protocol/buffer_limits.rs,PREAUTH_BODY_LIMIT) - Every response carries
X-Elastic-Product: Elasticsearch, because the official clients refuse a 2xx without it. A response toHEADkeeps its headers but drops its body. (source:handle_connection) - The status line names 200, 201, 204, 400, 401, 404, 405 and 500; any other code (for example 409 or 429) goes out with the reason phrase
Unknown. Clients read the number, so this is cosmetic. (source:HttpResponse::encode) - Each request is written to the audit log as read, write or admin access when auditing is on. (source:
audit_es_request) - Not cluster-aware: there is no replicated-write path or read-only check. (source:
src/protocol/elasticsearch/mod.rs, whole module) Not verified in cluster mode.
Authentication
authenticate runs before routing for every request, and again on the headers alone before a large body is read.
Authorization header |
Result |
|---|---|
Basic base64(user:pass) |
Checked with verify_wire_credential("elasticsearch", ...) against the catalog: the user needs a password and, unless SYNERGYDB_WIRE_ACCESS=open, membership of synergy_wire_elasticsearch or synergy_wire_all. Failure is 401 "unable to authenticate user". |
| Malformed Basic value | 401 "Invalid Basic authorization header". |
Any other scheme (ApiKey, Bearer) |
401 "Unsupported authorization scheme; use HTTP Basic". |
| Absent | Allowed only when SYNERGYDB_DEV_INSECURE_AUTH is set; otherwise 401 "missing authentication credentials". |
A 401 is a security_exception body with WWW-Authenticate: Basic realm="security", charset="UTF-8". There are no API keys, tokens, cookies or loopback exemptions, and the credential is checked on every request. After authentication there is no per-index or per-action authorization. (source: src/protocol/elasticsearch/mod.rs, authenticate, decode_basic, unauthorized; src/auth/wire_auth.rs, verify_wire_credential) Unit tests in mod.rs run with the dev flag; Not verified: no test in the proof pack sends Basic credentials (see Test coverage).
Reported identity
GET / answers as one of two products. A client that announces Elastic client major 8 or later (es= in x-elastic-client-meta, or compatible-with= in Accept or Content-Type) gets Elasticsearch 8.15.0 with Lucene 9.11.1; every other client gets OpenSearch 2.15.0, so 7.x-era clients that refuse an 8.x server still connect. SYNERGYDB_ES_DISTRIBUTION=elasticsearch or opensearch pins the answer. The same choice selects Elasticsearch 8 or OpenSearch error type names in some replies (document_parsing_exception versus mapper_parsing_exception). (source: src/protocol/elasticsearch/mod.rs, answer_as_elasticsearch, WriteOpts::es8)
Routes
route_request splits the path (query string removed) into segments and matches method and segments. Anything unmatched is 404 not_found "Route not found: METHOD path". In the table, {index} is any first segment that does not start with _. Index expressions resolve _all, *, comma lists, wildcards and aliases. (source: src/protocol/elasticsearch/mod.rs, route_request, resolve_index_expr)
| Area | Method and path | Notes |
|---|---|---|
| Root | GET / |
Identity, as above. |
| Cat |
GET _cat/indices[/{pattern}], _cat/aliases[/{alias}], _cat/health, _cat/nodes, _cat/shards[/{index}], _cat/count
|
Text or JSON; h= picks columns. |
| Cluster |
GET _cluster/health[/{index}], GET _cluster/stats, GET/PUT _cluster/settings, GET _cluster/state[/metadata[/{pattern}]]
|
Single node. Cluster health is yellow when indices exist but hold no documents at all, otherwise green. PUT _cluster/settings acts on action.auto_create_index (persistent or transient). |
| Nodes |
GET _nodes, _nodes/_all, _nodes/stats
|
One synthetic node. |
| Stats |
GET _stats, {index}/_stats, _stats/{metric}, {index}/_stats/{metric}
|
Document counts and sizes from memory. |
| Search |
GET/POST {index}/_search
|
See Search. |
| Scroll |
GET/POST _search/scroll; DELETE _search/scroll; DELETE _search/scroll/_all
|
|
| Multi |
GET/POST _msearch, {index}/_msearch; GET/POST _mget, {index}/_mget
|
_msearch honours a per-search index. |
| Bulk |
POST/PUT _bulk, {index}/_bulk
|
Actions index, create, delete, update. |
| Documents |
PUT/POST {index}/_doc/{id}; POST {index}/_doc (generated id); PUT/POST {index}/_create/{id}; GET, HEAD, DELETE {index}/_doc/{id}
|
op_type, if_seq_no, if_primary_term, _source read. |
| Update |
POST {index}/_update/{id}; POST {index}/_update_by_query; POST {index}/_delete_by_query
|
doc, upsert, doc_as_upsert, script (expression subset). |
| Count |
GET/POST {index}/_count
|
|
| Indices |
PUT, GET, HEAD, DELETE {index}
|
DELETE honours ignore_unavailable. |
| Index ops |
POST {index}/_refresh, POST _refresh, POST {index}/_flush, {index}/_forcemerge, {index}/_open, {index}/_close
|
No-ops that return shard counts; data is searchable at once. |
| Mappings |
PUT/GET {index}/_mapping
|
|
| Settings |
GET _settings, {index}/_settings, {index}/_settings/{keys}; PUT {index}/_settings
|
|
| Aliases |
POST _aliases; GET _aliases, GET _alias, GET {index}/_alias, GET _alias/{alias}; PUT {index}/_alias/{alias}; HEAD _alias/{alias}, HEAD {index}/_alias/{alias}; DELETE {index}/_alias/{alias}
|
_aliases takes add and remove actions. |
| Legacy templates |
GET, HEAD, PUT, DELETE _template[/{name}]
|
|
| Composable templates |
GET, HEAD, PUT, POST, DELETE _index_template[/{name}]
|
Applied when an index is created. |
| Analysis |
GET/POST _analyze, {index}/_analyze
|
standard and keyword analyzers. |
| Reindex | POST _reindex |
Between local indices only. |
| Introspection |
GET/POST {index}/_field_caps, {index}/_explain/{id}, {index}/_validate/query
|
(source: route_request and the handler each arm calls; cluster_health, put_cluster_settings)
There is no arm for /_search, /_count or /_mget with no index in front of _search and _count: a one-segment _search path fails the "does not start with _" guard and is a 404. Use /_all/_search or /*/_search. (source: route_request) Not verified: no test sends GET /_search.
Search
Request body. SearchRequest reads query, from, size, sort, _source, aggs or aggregations, highlight, track_total_hits, search_after and knn; any other top-level key (post_filter, script_fields, suggest, collapse, rescore) is ignored. A body that does not fit the struct exactly is read field by field, so one odd field does not drop the query. min_score is read inside function_score and script_score. Query parameters read include scroll, typed_keys and _source. (source: src/protocol/elasticsearch/mod.rs, parse_search_request, SearchRequest, generate_highlights; query_dsl.rs)
Query types. The Query enum parses: match_all, match_none, match, match_phrase, multi_match, fuzzy, term, terms, range, prefix, wildcard, regexp, exists, ids, bool, constant_score, dis_max, nested, query_string, simple_query_string, function_score, script_score, knn, geo_distance, geo_bounding_box, geo_polygon and geo_shape. Any other query name is a parse error returned as a 400. (source: src/protocol/elasticsearch/query_dsl.rs, Query, parse_query)
Query string. query_string and simple_query_string parse Lucene syntax (fields, boolean operators, phrases, wildcards, ranges, boosts) and analyse each term with the target field's mapping, so a keyword field matches exactly and a text field is tokenised. (source: query_string.rs) Tested by the 6 unit tests in query_string.rs and test_query_string_uses_mapping in mod.rs.
Analysis. text fields use a standard-style analyzer (lower-case, split on non-alphanumerics); keyword fields are not analysed. There is no stemming and no language analyzer, so running does not match run. (source: field_types.rs) Tested by the 4 unit tests in field_types.rs.
Scoring. BM25 with k1 = 1.2 and b = 0.75, computed in f32 with Lucene's one-byte (SmallFloat) length norms so scores print as Elasticsearch prints them. (source: bm25.rs) Tested by the 2 unit tests in bm25.rs, one against an Elasticsearch 8.15 reference score.
Vectors. dense_vector mappings take dims up to 4096 (MAX_DIMS), element_type, similarity (l2_norm, cosine, dot_product, max_inner_product) and index_options (hnsw, int8_hnsw, int4_hnsw, bbq_hnsw, or a flat type; m default 16, ef_construction default 100). A dynamic float array of 128 to 4096 elements (DYNAMIC_MIN_DIMS) is mapped as a vector. Top-level knn (one clause or several) and the knn query take k, num_candidates (at most 10,000, MAX_NUM_CANDIDATES; default ceil(1.5 * k), capped), filter, similarity and boost; knn beside query unions the hit sets and sums scores. Every indexed vector field is one collection, named {index}/{field} in the __es__ namespace, in the storage engine's shared vector service, which builds an HNSW graph once the field is large and keeps it across restarts; hits are re-scored from the stored document with the Elasticsearch formulas in f32. Bit vectors are scored in place. On the first search of a field in a process the collection is checked against the index and rebuilt if they differ. (source: knn.rs, module comment, MAX_DIMS, MAX_NUM_CANDIDATES, DYNAMIC_MIN_DIMS, kind_of, uses_service, sync_document, ensure_synced) Tested by the 4 unit tests in knn.rs. Not verified: recall of the HNSW path against Elasticsearch on large fields.
Scripts. painless.rs is an expression evaluator for the forms clients send in script_score, script_fields, _update and bucket scripts (doc['f'].value, params, arithmetic, comparisons, Math calls, ctx._source assignment). It is not a Painless interpreter: loops, method definitions and most of the standard library fail with script_exception. (source: painless.rs) Tested by the 2 unit tests in painless.rs and test_script_terms_and_agg_errors in mod.rs.
Cross-wire collections. When POST /{name}/_search names no Elasticsearch index but a cross-wire vector collection, the request is answered from that collection: knn with query_vector or query_vector_builder.text_embedding.model_text (embedded with the collection's embedder), k, num_candidates, a filter of term, terms, range, exists, match or bool, size, from and _source: false. Hits carry _wire, _source and _id naming where the record lives. (source: crosswire.rs, module comment, search, to_mongo_filter) Tested by query_dsl_filters_translate in crosswire.rs and test_crosswire_vectors_follow_es_documents in mod.rs.
Aggregations
| Kind | Types |
|---|---|
| Bucket |
terms, multi_terms, filter, filters, missing, nested, histogram, date_histogram, range, date_range
|
| Metric |
avg, sum, min, max, value_count, cardinality, stats, extended_stats, percentiles, top_hits
|
| Pipeline |
bucket_selector, bucket_script, bucket_sort
|
An unknown type is 400 parsing_exception "aggregation type [x] … is not supported by this server". More than 65,535 buckets (MAX_BUCKETS) is too_many_buckets_exception. cardinality is exact, not HyperLogLog. (source: src/protocol/elasticsearch/aggs.rs, MAX_BUCKETS) aggs.rs has no unit tests; aggregations are tested by test_filters_ranges_and_metric_aggs, test_nested_pivot_aggs_and_key_types, test_graylog_count_histogram_and_size_zero and test_script_terms_and_agg_errors in mod.rs, and parser tests in tests/protocol_elasticsearch.rs.
Paging
-
fromandsize, andsearch_afterwith asort. (source:search) Tested bytest_search_after_pages_through_every_hit. - Scroll: at most 500 open contexts (
MAX_OPEN_SCROLL_CONTEXTS; the 501st is a 500-class error namingsearch.max_open_scroll_context), default keep-alive 5 minutes, expired contexts dropped. An unknown scroll id issearch_context_missing_exception. Scroll contexts live in memory and do not survive a restart. (source:MAX_OPEN_SCROLL_CONTEXTS,DEFAULT_SCROLL_KEEP_ALIVE,sweep_expired_scrolls,scroll_search,clear_scroll) Tested bytest_scroll_returns_each_document_onceandtest_scroll_contexts_expire_and_are_capped. - There is no point-in-time API (
_pit). (source:route_request)
Documents, versions and concurrency
- Each document has a
_versionand a_seq_no;_primary_termis always 1.if_seq_nowithif_primary_termthat do not match is409 version_conflict_engine_exception; so is_createorop_type=createon an existing id. (source:src/protocol/elasticsearch/mod.rs,DocVersion,WriteOpts;doc_write.rs) Tested by the 3 unit tests indoc_write.rs. - A document posted without an id gets a random UUID v4, not Elasticsearch's 20-character base64 id. (source:
index_document_opts) - Writes to one document id are ordered by a striped per-id lock, then take the index's write lock.
_bulkapplies items one at a time and reports each item's status; a failed item does not undo earlier ones. (source:index_document_opts,doc_write_stripe;handle_bulk) -
dynamic: strictmappings refuse unknown fields withstrict_dynamic_mapping_exception. Writing to a missing index creates it unless auto-create is off (index_not_found_exception). (source:doc_write.rs;load_auto_create_index) - Refresh is immediate: a document is searchable as soon as the write returns.
refresh=wait_forhas nothing to wait for. (source:refresh_index)
Storage and durability
All index data is held in memory in indices: RwLock<HashMap<String, IndexData>> (settings, mappings, documents, aliases, versions, sequence numbers). Three on-disk structures back it. (source: src/protocol/elasticsearch/mod.rs, IndexData)
| Structure | Key or table | Written | Read |
|---|---|---|---|
| Write journal |
__es__:doc: + index + 0x00 + id, JSON {s: source or absent, v: version, q: seq_no}
|
One record per document change, appended under the index write lock with write_batch_unsynced
|
Replayed over the snapshot at startup (journal::replay). |
| Metadata snapshot |
__es__:indices (serde_json) |
After every PUT, DELETE or POST except paths containing _search, _count, _refresh or _msearch; skipped if its hash has not changed |
Loaded at startup. Holds settings, mappings, aliases and counters, not documents. |
| SQL table | _es_documents(index_name, doc_id, source) |
Upsert per document write; delete on document or index delete |
GET _doc falls back to it; readable over the SQL wires. |
Before a non-GET, non-HEAD request is answered, Journal::sync joins one shared group_sync, so an acknowledged document write is on disk. The journal exists because a crash used to lose documents that the old whole-store snapshot had not caught. (source: src/protocol/elasticsearch/journal.rs, module comment, PREFIX, record, sync, replay; mod.rs, persist_all_indices, ES_STORE_KEY, persist_document) Tested by test_journal_restores_writes_missing_from_snapshot and test_snapshot_holds_metadata_only_and_old_snapshots_migrate in mod.rs and the persistence_tests module of tests/protocol_elasticsearch.rs. Not verified: whether the metadata snapshot put, which runs after the sync, is itself synced before the reply; an index created just before a crash may depend on the next sync.
The auto-create setting is stored at __es__:auto_create_index; when never set it comes from SYNERGYDB_ES_AUTO_CREATE_INDEX (default true). (source: ES_AUTO_CREATE_KEY, load_auto_create_index) Tested by test_persistent_auto_create_index_survives_restart.
The whole index set is in memory, so the data set must fit in RAM. (source: IndexData)
Error replies
Errors use the Elasticsearch shape {"error": {"root_cause": [...], "type": ..., "reason": ...}, "status": N}. (source: HttpResponse::error)
| Type | Status | When |
|---|---|---|
security_exception |
401 | Authentication. |
index_not_found_exception |
404 | Missing index or alias. |
resource_not_found_exception, document_missing_exception, aliases_not_found_exception, index_template_missing_exception
|
404 | Missing scroll target, document on update, alias, template. |
not_found |
404 | No route. |
version_conflict_engine_exception |
409 | Sequence-number mismatch, create on existing id. |
parsing_exception, parse_exception, x_content_parse_exception
|
400 | Bad JSON, unknown query or aggregation. |
illegal_argument_exception, action_request_validation_exception
|
400 | Bad parameter values, missing required fields. |
mapper_parsing_exception or document_parsing_exception
|
400 | Value does not fit the mapping (name depends on the reported product). |
strict_dynamic_mapping_exception |
400 | Unknown field under dynamic: strict. |
query_shard_exception, search_phase_execution_exception
|
400 | Query fails on a field. |
script_exception |
400 | Script outside the supported subset. |
too_many_buckets_exception |
400-class | More than 65,535 buckets. |
search_context_missing_exception |
404 | Unknown or expired scroll id. |
(source: src/protocol/elasticsearch/mod.rs, call sites of HttpResponse::error; aggs.rs; knn.rs, decode_error) Error shapes are tested by the error_handling module of tests/protocol_elasticsearch.rs and test_script_terms_and_agg_errors.
Limits and configuration
| Item | Value | Source |
|---|---|---|
| Port | 9200 |
src/config.rs, elasticsearch_port
|
| Max request body | 256 MB | MAX_HTTP_BODY |
| Pre-auth body | 1 MB | PREAUTH_BODY_LIMIT |
| Open scroll contexts | 500 | MAX_OPEN_SCROLL_CONTEXTS |
| Scroll keep-alive default | 5 minutes | DEFAULT_SCROLL_KEEP_ALIVE |
| Aggregation buckets | 65,535 |
aggs.rs, MAX_BUCKETS
|
| Vector dims | 4096; dynamic mapping from 128 |
knn.rs, MAX_DIMS, DYNAMIC_MIN_DIMS
|
num_candidates |
10,000 |
knn.rs, MAX_NUM_CANDIDATES
|
SYNERGYDB_ES_DISTRIBUTION |
elasticsearch or opensearch
|
answer_as_elasticsearch |
SYNERGYDB_ES_AUTO_CREATE_INDEX |
Default true
|
load_auto_create_index |
SYNERGYDB_DEV_INSECURE_AUTH |
Allows requests with no credentials | authenticate |
Test coverage
| Suite | Count | What it covers |
|---|---|---|
src/protocol/elasticsearch/mod.rs unit tests |
24 | Handler-level: journal and snapshot restart, auto-create persistence, scroll, search_after, Graylog and Mastodon request shapes, _msearch per-search index, templates, query string with mappings, aggregations, scripts, cross-wire vectors. They call handler methods directly, not over TCP. |
query_dsl.rs / query_string.rs / field_types.rs / knn.rs / doc_write.rs / bm25.rs / painless.rs / crosswire.rs
|
10 / 6 / 4 / 4 / 3 / 2 / 2 / 1 | Module units. aggs.rs, function_score.rs and journal.rs have none. |
tests/protocol_elasticsearch.rs |
89 | Parser-level modules (query_parsing, aggregation_parsing, search_request, query_types, sort_options, error_handling) and persistence_tests (_es_documents across a restart). No TCP requests. |
(source: the files named)
Proof pack (docs/proof/2026-11-30/proof-pack-a3232c9/logs/):
-
elasticsearch-search-diff.txt: "ELASTICSEARCH DIFFERENTIAL PASS RATE: 74/74", SynergyDB against real Elasticsearch 8. -
elasticsearch-feature-matrix.txt: "TOTAL: 29 probesPARITY=26 DIVERGE=0 UNSUPPORTED=0 BOTH-ERR=0". The category rows add up to 26, and the catrow shows 0 probes, so 3 probes are in no category; the log does not say which they are.
Both suites run under the harness's default profile, which sets SYNERGYDB_DEV_INSECURE_AUTH=1, so Basic authentication is not exercised by the proof pack. The operator page's OpenSearch 2.19 client result has no log in this proof pack. (source: prove/wires.py; prove/sdb.sh; the logs named) Not verified: chunked bodies, TLS, pipelined requests beyond keep-alive, multi-connection concurrency (the proof harness notes "Thin suite, single connection only").
Not implemented
- Authentication other than HTTP Basic: API keys, bearer tokens, service accounts, the
_securityAPI. (source:authenticate,route_request) -
/_search,/_countand/_mgetstyle paths with no index in front of_searchor_count. (source:route_request) - Chunked request bodies. (source:
parse_request) - Stemming and language analyzers. (source:
field_types.rs) - Real Painless. (source:
painless.rs) - Point in time (
_pit),_termvectors,_mtermvectors,_rank_eval, ingest pipelines, snapshots, ILM, data streams,_tasks, async search. These names appear only in the audit classifier, not in routing. (source:audit_es_request,route_request) - Shards, replicas and cluster mode. (source:
IndexData,route_request)