Elasticsearch Query DSL

The Elasticsearch wire parses the JSON Query DSL into a Query value and evaluates it itself, document by document, over its in-memory indices. It does not produce a LogicalPlan. The module comment of query_dsl.rs says it parses "into SynergyDB query plans", and the file imports LogicalPlan, but no function in it builds one (source: src/protocol/elasticsearch/query_dsl.rs, module comment, QueryDslParser::parse_query; src/protocol/elasticsearch/mod.rs, matches_query_meta).

Operator status and client coverage are on the Elasticsearch wire page.

Translation path

flowchart LR B["_search body"] --> SR["parse_search_request"] SR --> PQ["QueryDslParser::parse_query"] PQ -->|"error"| E400["400 parsing_exception"] PQ --> M["matches_query_meta per document"] M --> SC["Scoring: BM25, function_score, kNN"] SC --> SO["sort, from, size, search_after, _source, highlight"] M --> AG["aggs::run_aggs"] IDX["In-memory indices"] --> M IDX -->|"writes"| J["KV journal __es__:doc:"] IDX -->|"writes"| T["SQL table _es_documents"]

(source: src/protocol/elasticsearch/mod.rs, search, parse_search_request, parse_query_checked, matches_query_meta; src/protocol/elasticsearch/aggs.rs, run_aggs; src/protocol/elasticsearch/journal.rs; src/protocol/elasticsearch/bm25.rs)

  1. Request. parse_search_request reads query, from, size (default 10), sort, _source, aggs or aggregations, highlight, track_total_hits, search_after and knn. Other top-level keys, such as post_filter, collapse, suggest, rescore and min_score, are not fields of SearchRequest and are ignored. A body that does not parse as a JSON object is treated as an empty request (source: src/protocol/elasticsearch/mod.rs, parse_search_request, search; src/protocol/elasticsearch/query_dsl.rs, SearchRequest).
  2. Query parse. parse_query_checked turns a parse error into HTTP 400 parsing_exception (or query_shard_exception for "Cannot parse" errors); its comment records that an unparseable query used to match every document (source: src/protocol/elasticsearch/mod.rs, parse_query_checked).
  3. Evaluation. Every document of each target index is tested with the parsed query, using the field types of the index mapping; there is no inverted index that narrows the candidates (source: src/protocol/elasticsearch/mod.rs, search, matches_query_meta, field_types_for).
  4. Scoring and output. Full-text clauses are scored with BM25; function_score and script_score modify scores; knn adds a vector score (source: src/protocol/elasticsearch/bm25.rs; src/protocol/elasticsearch/function_score.rs; src/protocol/elasticsearch/knn.rs).

_explain parses the body's query with .ok() and treats a missing or unparseable query as a match, unlike _search (source: src/protocol/elasticsearch/mod.rs, explain).

Query types

parse_query checks keys in this order; a null or empty query is match_all, and any other key is "Unknown query type" (source: src/protocol/elasticsearch/query_dsl.rs, QueryDslParser::parse_query):

Group Types
Vector knn
All or none match_all (with boost), match_none
Full text match, match_phrase, multi_match, query_string, simple_query_string
Term level term, terms, range, prefix, wildcard, regexp, fuzzy, exists, ids
Compound bool, constant_score (filter required), function_score, script_score (query required), dis_max (queries required)
Joining nested
Geo geo_distance, geo_bounding_box, geo_polygon, geo_shape

Not accepted, so a request using them gets 400: match_phrase_prefix, match_bool_prefix, more_like_this, terms_set, has_child, has_parent, the span_* family, intervals and percolate (source: src/protocol/elasticsearch/query_dsl.rs, QueryDslParser::parse_query).

query_string and simple_query_string

query_string.rs parses Lucene classic syntax once and evaluates it against the mapping: text fields are analyzed with a standard analyzer, keyword fields compare whole values case-sensitively, numeric and date fields compare as numbers or instants with date math, and booleans as true/false. Supported syntax: field:term, bare terms, phrases with ~slop, * and ? wildcards, /regex/, term~N, ^boost (accepted and ignored), inclusive, exclusive and open ranges, >, >=, <, <=, _exists_:field, field:*, AND/&&, OR/||, NOT/!, +/-, parentheses and field:(a OR b) (source: src/protocol/elasticsearch/query_string.rs, module comment, compile). Tested by the 6 unit tests in src/protocol/elasticsearch/query_string.rs.

Scoring

  • BM25. k1 1.2 and b 0.75, scores computed in f32, field lengths encoded in one byte with int_to_byte4 and decoded with byte4_to_int, and statistics taken from the searched index (source: src/protocol/elasticsearch/bm25.rs, K1, B, FieldStats, score, int_to_byte4, byte4_to_int). Tested by norms_round_trip_like_lucene and matches_elasticsearch_bm25 in bm25.rs.
  • Hybrid. A request with both query and knn scores each document as the sum of the query score and the kNN score, and a document found by kNN is a hit even when it does not match the query (source: src/protocol/elasticsearch/mod.rs, search). Not verified: no unit test checks a hybrid score.
  • function_score. Functions weight, field_value_factor (modifiers log, log1p, log2p, ln, ln1p, ln2p, square, sqrt, reciprocal; an illegal modifier is an error), script_score, random_score and the decay functions gauss, exp, linear; score_mode multiply, sum, avg, first, max, min; boost_mode multiply, replace, sum, avg, max, min. A failing score script, or one that returns a non-number, scores 0 (source: src/protocol/elasticsearch/query_dsl.rs, function_score parsing; src/protocol/elasticsearch/function_score.rs, run_score_script). Not verified: function_score.rs has no unit tests.

Painless

Scripts in script_score, function_score and scripted aggregations are run by painless.rs, whose own comment says it "is not a Painless implementation". According to that comment it evaluates single expressions: doc['f'] and doc.f accessors, params, literals, arithmetic, comparisons, &&, ||, !, the ternary operator, String.valueOf, Integer.parseInt, Long.parseLong, Double.parseDouble, Math.*, common string methods and date accessors. Statements, loops, declarations and lambdas are rejected with a compile error (source: src/protocol/elasticsearch/painless.rs, module comment). Tested by the 2 tests in painless.rs.

Aggregations

aggs.rs runs the request's aggs over the matched documents (source: src/protocol/elasticsearch/aggs.rs, run_aggs, run_agg):

Kind Types
Bucket terms, multi_terms, filter, filters, missing, nested, histogram, date_histogram (calendar intervals from second to year), range, date_range
Metric avg, sum, min, max, value_count, cardinality, stats, extended_stats, percentiles, top_hits
Bucket pipeline bucket_selector, bucket_script, bucket_sort

Any other type is a parsing_exception: "aggregation type [x] (in [name]) is not supported by this server". This includes composite, significant_terms, geo_* aggregations and the sibling pipelines such as avg_bucket and derivative (source: src/protocol/elasticsearch/aggs.rs, run_agg, BUCKET_PIPELINES).

Not wired: QueryDslParser::parse_aggregations and parse_single_aggregation exist in query_dsl.rs but the search path does not call them; aggregations are read directly by aggs.rs (source: src/protocol/elasticsearch/query_dsl.rs, parse_aggregations; src/protocol/elasticsearch/aggs.rs, run_aggs).

Not verified: aggs.rs has no unit tests; aggregation behaviour is covered only by tests/protocol_elasticsearch.rs and the differential runs recorded on the wire page.

Endpoints that take a query

_search, _count, _msearch, _delete_by_query, _update_by_query, _explain, _validate/query, and scroll continuations (_search/scroll) all use the same parser and evaluator; _mget and _bulk do not take a query (source: src/protocol/elasticsearch/mod.rs, route table, search, explain).

A _search whose target is not an Elasticsearch index but a cross-wire vector collection is answered by crosswire.rs with a reduced DSL: knn with query_vector or a text embedding, k, num_candidates, and filter using term, terms, range, exists, match and bool (source: src/protocol/elasticsearch/crosswire.rs, module comment). Tested by the 1 test in crosswire.rs.

Storage and reachability from SQL

Indices are held in memory. Each document change is written to a key-value journal under __es__:doc:, the index metadata to a snapshot key __es__:indices, and documents are also mirrored to the SQL table _es_documents (index_name, doc_id, source) (source: src/protocol/elasticsearch/journal.rs, module comment; src/protocol/elasticsearch/mod.rs, ES_STORE_KEY, _es_documents). SQL can read _es_documents, where source is the JSON text of each document; the _es_ prefix makes it a wire-internal table, so a role that is not a superuser needs a GRANT (source: src/query/engine.rs, is_wire_internal_relation).

Tests

  • src/protocol/elasticsearch/query_dsl.rs (10): test_parse_match_all, test_parse_match_query, test_parse_term_query, test_parse_bool_query, test_parse_range_query, test_parse_geo_distance_query, test_parse_geo_bounding_box_query, test_parse_geo_polygon_query, test_geo_point_formats, test_parse_distance.
  • Other unit tests: query_string.rs 6, knn.rs 4, field_types.rs 4, doc_write.rs 3, mod.rs 3, bm25.rs 2, painless.rs 2, crosswire.rs 1. aggs.rs, function_score.rs and journal.rs have none.
  • tests/protocol_elasticsearch.rs: 89 tests.
  • Differential runs against Elasticsearch and OpenSearch are listed on the wire page.