[RFC] Vector search in PPL: k-NN / ANN queries on the Calcite engine

Đang mở
#5,875 1 bình luận 0 reaction 0 người được giao Xem trên GitHub

Maintainer thường phản hồi trong vòng 1 ngày

Chưa có ai nhận issue này.

Đánh giá

Độ khó
5/5
Thời gian dự kiến
Hơn một tuần
Mức phù hợp với người mới
8/100
Loại issue
Tính năng
Độ rõ ràng
Khá rõ ràng
Mức độ hoạt động
Sôi nổi
Công nghệ
java
Lĩnh vực
search

Hướng nghiên cứu

This is an RFC for a design that spans the PPL grammar, the Calcite planner and the k-NN query path, not a task with a defined change. Start by reading how knn_vector is mapped to ExprCoreType.ARRAY in OpenSearchDataType.java and the 'Ignored' entry in docs/user/ppl/limitations/limitations.md. Done means the design is agreed and split into the sub-tasks listed in section 7, so a newcomer should comment on the RFC rather than open a pull request.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

PPL RFC

Problem Statement

PPL cannot use vector search. A user who wants "the 10 products most similar to this embedding, among those with category = 'shoes', then counted by brand" has to leave PPL, hand-write _search DSL with a knn query, and post-process the hits elsewhere. Concretely, in this repository:

  • The PPL grammar has no knn, vector or similarity construct.
  • knn_vector fields are mapped to ExprCoreType.ARRAY — the same core type as nested (OpenSearchDataType.java: Nested("nested", ExprCoreType.ARRAY), KnnVector("knn_vector", ExprCoreType.ARRAY)) — which the Calcite engine turns into ARRAY<ANY>. The mapping's dimension, data_type and space_type are dropped, and docs/user/ppl/limitations/limitations.md still lists knn_vector as "Ignored".
  • The only vector feature in the plugin, the experimental SQL vectorSearch() table function (3.7.0), runs only on the V2 engine; the Calcite visitor rejects table functions ("Table function is unsupported in Calcite"). This RFC does not change vectorSearch().

Among observability and log query languages, only Elasticsearch ES|QL reaches an ANN index from inside the language (WHERE KNN(...), GA in 9.4). Splunk SPL/SPL2, Datadog, Sumo Logic, New Relic NRQL, Grafana LogQL and CrowdStrike LogScale have no vector search; Kusto KQL and Dynatrace DQL have only brute-force distance functions.

User scenarios this RFC targets (syntax as proposed below; […] abbreviates a vector literal):

  1. Filtered semantic search / RAG retrieval — the most common vector workload in every system surveyed.
source=products
| where category = 'shoes' and in_stock = true and knn(embedding, […], k=50)
| sort - _score | head 10
| fields name, price, _score
  1. Retrieve, then analyse — aggregate over the semantic neighbourhood. Vector databases cannot do this exactly (Pinecone and Qdrant have no aggregation over search hits; Milvus and Vespa compute facets approximately over candidates; Cassandra rejects aggregation after ANN OF). PPL already has the commands.
source=support_tickets
| where product = 'payments' and knn(embedding, […], k=200)
| stats count() as tickets, avg(resolution_hours) as mttr by root_cause
| sort - tickets
  1. Similar events in observability and security — past alerts or incidents similar to the current one, then grouped. BigQuery documents "triage anomalies in logs" and "most closely matching audit log entries" as vector-search use cases; Splunk's Data Science and Deep Learning app ships a similar-notable-events collection.
source=alert_embeddings
| where severity = 'high' and service = 'checkout'
| knn field=embedding vector=[…] k=20
| stats count() by rule_name, host
  1. Vectors in a separate index, joined back — keep docs(doc_id, title, category, …) and doc_vectors_v2(doc_id, embedding) apart, so that re-embedding with a new model rebuilds only the vector index and never re-indexes the business fields. This requires PPL to read knn_vector as a typed column.
source=doc_vectors_v2
| knn field=embedding vector=[…] k=10
| join left=v right=d on v.doc_id = d.doc_id docs
| fields d.title, d.category, v._score

Later sub-tasks cover hybrid lexical + semantic search with rank fusion, query by text through an ML Commons model, "more like this document", cross-index pre-filters, and batch kNN for deduplication and entity resolution.

Current State

In OpenSearch. The knn query (k-NN plugin) takes a raw vector with k, filter (efficient pre-filtering on the faiss and lucene engines), method_parameters (ef_search, nprobes), rescore, max_distance / min_score and expand_nested_docs; k is bounded by 10,000 and collected per shard before the coordinator merges. The neural query (neural-search plugin) requires query_text or query_image — it does not accept a raw vector — runs model inference during query rewrite, and then issues a knn query; neural-search also owns the semantic field type, neural_sparse, and the hybrid query with normalization / RRF search pipelines. In this plugin, Calcite is the default PPL engine (plugins.calcite.enabled=true); SQL on ordinary indices still runs on V2 (QueryService.shouldUseCalcite accepts PPL only, #3457). Queries on composite (Parquet-backed) indices are routed to the analytics engine in OpenSearch core (sandbox/plugins/analytics-engine, Calcite + DataFusion) through QueryPlanExecutor; that engine has no score concept and composite indices cannot hold knn_vector today.

In Apache Calcite. main (1.43.0-SNAPSHOT, 2026-10-12) has no vector type and no distance functions. RelDataTypeFactory.createArrayType(type, maxCardinality) exists, but SqlTypeFactoryImpl asserts maxCardinality == -1 and ArraySqlType stores only the element type, so an array cannot carry a dimension. The only vector-related work upstream is a proposed Milvus adapter (CALCITE-7353, open).

In other databases. A survey of about 45 systems (October 2026) finds six ways kNN enters a query language:

Pattern Example Systems
Distance function + ORDER BY … LIMIT k, rewritten to an index scan ORDER BY embedding <=> $q LIMIT 10 pgvector, MariaDB, SingleStore, TiDB, DuckDB, ClickHouse, Doris, Oracle, SAP HANA, Spanner, Couchbase; brute force only in Spark 4.2, Kusto, Snowflake SQL
Table-valued function FROM VECTOR_SEARCH(TABLE t, 'emb', query_value => q, top_k => 10) BigQuery, SQL Server 2025, Databricks, Flink 2.2
Predicate in WHERE, score as metadata WHERE KNN(v, q) | SORT _score DESC | LIMIT 10 Elasticsearch ES|QL, Vespa, Pinot
Pipeline stage {$vectorSearch: {…}} as the first stage MongoDB
Dedicated clause ORDER BY v ANN OF [..] LIMIT k, SELECT TOP (N) WITH APPROXIMATE, FETCH APPROX FIRST k ROWS Cassandra, SQL Server, Oracle, Neo4j
API only client.search(data=[q], limit=10) Milvus, Qdrant, Pinecone

Lessons that shape this proposal:

  • Where k lives decides whether filters work. SQL Server deprecated VECTOR_SEARCH(…, TOP_N = k) in favour of an outer SELECT TOP (N) WITH APPROXIMATE, so that WHERE is applied during the search and N rows come back when N rows qualify. Systems that bind k inside the call (BigQuery, Databricks, Flink) document results with fewer than k rows.
  • Candidate count and returned rows are separate everywhere (DSL k vs size, MongoDB numCandidates vs limit, Vespa totalTargetHits vs hits).
  • Implicit ORDER BY distance LIMIT k rewrites fail silently — a second sort key, a sort direction or metric that does not match the index, a non-constant query vector, OFFSET, or a large LIMIT turns the index off without an error in DuckDB, ClickHouse, StarRocks, pgvector, MariaDB and Oracle. Systems that make approximation explicit (Doris l2_distance_approximate, Spanner APPROX_*, Oracle FETCH APPROX, SQL Server WITH APPROXIMATE) avoid that.
  • Fusion is a language construct only in pipeline languages (ES|QL FORK … | FUSE, MongoDB $rankFusion, Redis FT.HYBRID); every SQL system makes users hand-write reciprocal rank fusion with CTEs and a full outer join.
  • Vector types: OLTP and vector-capable databases use a dedicated VECTOR(n) type (pgvector, SQL Server, Oracle, Snowflake, MariaDB, Cassandra); analytical engines reuse arrays (Spark, Trino, ClickHouse, Flink).

Long-Term Goals

  • One vector-search semantics for PPL and SQL: the same query means the same rows and the same _score, whichever language and whichever backend executes it.
  • A backend-neutral logical form, so that the OpenSearch DSL path (now), an exact brute-force path, and the analytics engine (later) are additive implementations rather than separate features.
  • Composability as the differentiator: after the kNN step, every PPL command (stats, sort, eval, join, lookup) works exactly over the top-k rows — something vector databases do not offer.
  • Sustainability: reuse the plugin's existing relevance-function and pushdown machinery; keep the vector type on the plugin's existing UDT mechanism until Calcite has a native type; no new dependency on k-NN or neural-search at compile time.
  • Confidence: the design follows patterns already shipped elsewhere (ES|QL's predicate form, SQL Server's k-from-row-limit, explicit approximation), and T1 maps onto an existing, mature DSL query; the main risks are the analytics-engine storage work and the Calcite type, both off the T1 critical path.

Proposal

Add k-NN search to PPL on the Calcite engine with two equivalent syntaxes — a knn(...) predicate in where and a knn command — backed by a new VECTOR type for knn_vector fields, and lower both to one canonical Calcite plan: a top-k Sort over a Project that computes _score := KNN_SCORE(field, vector, options) over the pre-filtered scan. The first sub-task, T1, executes that plan as a k-NN knn query with an efficient pre-filter. SQL reuses the same AST node and plan when SQL moves to Calcite; the analytics engine can implement the same plan once composite indices can hold vectors. Radial search, exact distance functions, query-by-text, hybrid fusion, cross-index pre-filters and SQL syntax follow as sub-tasks T2–T7 (section 7).

Approach

1. Syntax and semantics. Both forms mean the same: source=t | where p and knn(f, v, opts) ≡ source=t | where p | knn field=f vector=v opts.

source=products
| where category = 'shoes' and knn(embedding, [0.12, 0.40, …], k=50, ef_search=100)
| sort - _score | head 10

source=products
| where category = 'shoes'
| knn field=embedding vector=[0.12, 0.40, …] k=50 ef_search=100
| where price < 100
| head 10
Rule T1 definition
Arguments field: a knn_vector field of the source index (float, half_float or byte; binary follows in T2). vector: a constant […] or array(…) whose length equals the field's dimension (integers in [-128, 127] for byte vectors). Options: k, ef_search, nprobes; anything else is an error
k Explicit k= wins: the kNN step returns its top k, and a later head is a separate cut (knn … k=50 | sort - price | head 10 is the 10 cheapest of the 50 nearest). Otherwise k = N of the first downstream head N, derived only through fields, eval, rename and sort - _score; any other command in between — notably where or a sort on another key — stops derivation, because a derived k would silently search only N candidates before filtering or re-sorting. Otherwise the query fails ("knn requires k or a following head", naming the command that stopped derivation) — no silent default. k is resolved on the AST before lowering. Range [1, 10000]. k is global, not per shard
Pre-filter The other conjuncts of the same where as knn(...), and any where between source and the kNN step
Post-filter Any where after the kNN step; can return fewer than k rows, and needs an explicit k when a head follows. Documented as "at most k rows". Unlike ES|QL, adjacent wheres are not merged into the pre-filter: one positional rule serves both forms
Output Input columns plus _score (higher is nearer, equal to the k-NN plugin's score for the field's space_type), ordered by _score descending. Every later command sees at most k rows. In a branch with a kNN step, _score is a regular column: visible by default and kept across join, lookup, append and subsearch boundaries, which today strip metadata fields by name
Restrictions knn(...) must be a top-level conjunct; one kNN per query branch; only where and fields between source and the kNN step; all indices of the source share the vector mapping
No silent fallback A pre-filter that cannot be translated into a k-NN efficient filter, an unknown option, a dimension mismatch, or a missing k-NN plugin is a 400 error with a hint — never an exact scan. The V2 engine answers "knn requires the Calcite engine"

2. Vector type. Add ExprCoreType.VECTOR for knn_vector, keeping dimension, data_type and space_type from the mapping. On Calcite it is a new type, ExprVectorType, an ARRAY<REAL> (ARRAY<TINYINT> for byte and binary, whose mapping dimension counts bits) and carrying the dimension in its digest (VECTOR(768, FLOAT)), and integrated with the plugin's existing UDT handling (as for IP and binary). A dedicated type is needed because Calcite has no vector type and its ARRAY cannot carry a length; presenting it as ARRAY<REAL> (preferably as an ArraySqlType subclass, since parts of Calcite cast ARRAY types to ArraySqlType) keeps every array-aware consumer working. Set operations over vectors of different dimensions are an error. Values are read through _source. Note that k-NN enables derived source on every index created with index.knn: true, so vectors are usually not stored in _source but reconstructed from the vector data at fetch time — transparent, but a cost per returned row, so vectors are fetched only when referenced; a field excluded from _source reads as null. Vector columns can be projected and passed through join, lookup, append and union (scenario 4); comparing, sorting or grouping by a vector is an error. The reported column type changes from array to vector. In parallel we will propose a native VECTOR(n, type) type and distance functions to Apache Calcite, and switch to them once both this plugin and the analytics engine use a Calcite release that has them.

3. Canonical plan. Both forms, and later SQL, lower in CalciteRelNodeVisitor to:

LogicalSort(sort0=[$3], dir0=[DESC], fetch=[10])
  LogicalProject(name=[$0], price=[$1], category=[$2], _score=[KNN_SCORE($4, ARRAY(0.12E0:REAL, …), MAP('k', 50))])
    LogicalFilter(condition=[=($2, 'shoes')])
      CalciteLogicalIndexScan(table=[[OpenSearch, products]])
  • Meaning: among rows passing the pre-filter, the fetch rows with the highest KNN_SCORE. KNN_SCORE is defined as exact and equal to k-NN's per-space-type score (l2: 1/(1+d²); cosinesimil: (1+cos)/2; innerproduct: 1+⟨q,v⟩ when positive, 1/(1−⟨q,v⟩) otherwise); ANN is a permitted implementation of the top-k Sort for backends with a vector index.
  • With an explicit k the boundary is built with fetch = k, and k is also kept as MAP('k', k), because it is the ANN candidate count: knn … k=50 | head 10 searches with k = 50 and returns 10 rows even after RelBuilder merges the head into the boundary.
  • Post-filters can never be turned into pre-filters: the plugin's filter pushdown refuses to push into a scan once a LIMIT is pushed, and the kNN pushdown always pushes one; join rules cannot reach inside one side's top-k.
  • The plan uses only standard nodes plus one named function, so other consumers of a RelNode (the analytics engine, the Spark transpiler) need no plugin-specific classes.
  • KNN_SCORE is an ImplementorUDF registered once for both languages; like the relevance functions, it throws if it is not pushed down.
  • k derivation from head runs once per statement on the AST, before lowering, at both entry points (the PPL path in QueryService and the unified planner), so head / reverse lowering details cannot disturb it.

4. Pushdown to the knn query. A rule KnnIndexScanRule, placed with the relevance-function rule in OPEN_SEARCH_NON_PUSHDOWN_RULES and pruning the alternatives it replaces, matches the plan above over CalciteLogicalIndexScan — after the pre-filter has been pushed as FILTER, or, with plugins.calcite.pushdown.enabled=false (where filter pushdown is not registered), pushing the pre-filter itself — adds a new PushDownType.KNN, and builds:

{ "size": 10, "from": 0, "track_scores": true,
  "query": { "wrapper": { "query": "<base64 of>" } } }

{ "knn": { "embedding": { "vector": [0.12, 0.40, …], "k": 50,
    "filter": { "term": { "category": { "value": "shoes" } } },
    "method_parameters": { "ef_search": 100 } } } }
  • The knn query is the scoring query; pre-filters go inside knn.filter (not into bool.filter, which is where a second pushed filter goes today). track_scores is enabled; the Calcite request builder disables it by default.
  • WrapperQueryBuilder avoids a compile-time dependency on k-NN and survives cursor deserialization, which uses a core-only query registry.
  • After KNN, no aggregation, filter or other sort is pushed into the request. A DSL aggregation under a knn query would count up to k × shards documents; instead, stats, post-filters and joins run in Calcite over the global top k.
  • The existing sort-expression and script pushdowns must refuse KNN_SCORE; otherwise a competing plan would push it as a script sort that fails on the shards.
  • Explain shows a readable KNN->{field=embedding, k=50, ef_search=100} entry in PushDownContext.

Parameters of the knn and neural queries, and when PPL exposes them:

DSL parameter PPL Sub-task
field, vector, k, filter arguments, k= / head, pre-filter where T1
method_parameters.ef_search, method_parameters.nprobes ef_search=, nprobes= T1
max_distance, min_score (radial) same names; require a downstream head T2
rescore / oversample_factor rescore=false, oversample_factor= T2
binary vectors (Hamming) — T2
neural: query_text, query_image, model_id; semantic fields knn(f, query_text='…', model_id='…') T4
hybrid + normalization / RRF pipelines multisearch [ … ] [ … ] | fuse method=rrf|linear T5
rerank / MMR processors rerank, mmr commands T5
expand_nested_docs, ignore_unmapped, neural_sparse / sparse ANN — backlog

5. SQL compatibility. SQL gets the predicate form, SELECT … FROM products WHERE category = 'shoes' AND knn(embedding, [..], k=50) ORDER BY _score DESC LIMIT 10; the SQL AstBuilder emits the same Function("knn", …) node, so lowering, k resolution and pushdown are shared. Post-filters in SQL are outer queries. The command form is PPL-only. T1 ships the shared AST, plan and operator; the SQL grammar follows when SQL on ordinary indices moves to Calcite (#3457). The Spark transpiler reports KNN_SCORE as unsupported.

6. Analytics engine. T1 adds a guard — a query with a kNN step is rejected with a clear error on the analytics-engine route, detected on the AST before planning, because that route plans against the analytics engine's own schema, which drops knn_vector columns — and kNN on ordinary k-NN indices keeps using the DSL path. The plan shape above is published as the analytics engine's input contract: it needs its own vector column type (reported as ARRAY<REAL>) and a ScalarFunction.KNN_SCORE resolved by name, not plugin classes. Executing it there needs work outside this repository, sketched for discussion as analytics-engine work items the analytics-engine work items:

Work item What
Vector storage in composite indices Store knn_vector in composite indices through the Lucene secondary format with the k-NN codec (today the mapping is rejected, k-NN does not implement parseCreateFieldForPluggableFormat, the Lucene secondary has no field factory for it, and the k-NN codec is installed only with index.knn=true)
Vector type and KNN_SCORE in the analytics engine Vector FieldType and a vector column type in the engine's schema, ScalarFunction.KNN_SCORE, and a virtual _score column
ANN execution in the analytics engine A Lucene-driven per-shard vector top-k stage emitting (row id, _score), merged by score on the coordinator, with late materialization of the other columns from Parquet; then lift the guard for composite indices
Pre-filters on Parquet-only columns Pre-filters on Parquet-only columns (a Parquet-side bitset handed to Lucene as the k-NN filter)
Exact path in DataFusion An exact path in DataFusion (its built-in array_distance / cosine_distance / inner_product) and a cost-based choice between ANN and exact

The acceptance criterion for every work item is the same rows and _score as the DSL path.

7. Roadmap. T1–T7 are the sub-tasks of this RFC in this repository, one pull request each; T1 is the foundation and T2–T7 build on it independently. Work outside this repository — the analytics-engine work items of section 6 and the proposals to Apache Calcite — is listed in the second table and does not block T1.

ID Sub-task Scope Depends on
T1 Vector search foundation VECTOR type; knn() and knn command; canonical plan shared with SQL; k derivation on the AST; efficient pre-filter (also with pushdown disabled); ef_search / nprobes; _score as a regular column; explain; analytics-engine guard —
T2 Radial search, rescore, binary vectors max_distance / min_score; rescore / oversampling; Hamming on binary vectors T1
T3 Exact distance functions vector_l2_distance, vector_cosine_similarity, vector_inner_product; exact KNN_SCORE with a row-count guardrail; vector aggregates T1
T4 Query by text query_text / model_id through the neural query and ML Commons; semantic field type T1
T5 Hybrid search fuse over multisearch branches (DSL hybrid or RRF in Calcite, decided then); rerank, mmr T1
T6 Cross-index pre-filter and batch kNN where doc_id in [ source=docs | … ] | knn … executed as terms inside knn.filter, bounded by index.max_terms_count; query vector from a stored document; batch kNN / vector joins T1
T7 SQL knn() syntax SQL grammar for the predicate form, reusing T1's plan T1, #3457
Work outside this repository What Depends on
Analytics-engine work items Vector storage in composite indices, vector type and KNN_SCORE, ANN execution, pre-filters on Parquet-only columns, exact path in DataFusion (section 6) T1's plan contract
Calcite native VECTOR type proposal Propose a native VECTOR(n, type) type to Apache Calcite —
Calcite distance-function proposal Propose distance functions to Apache Calcite Calcite native VECTOR type proposal
Switch to the native Calcite type Replace the plugin's vector type with the native one Calcite native VECTOR type proposal released; both this plugin and the analytics engine upgraded

8. Testing. Unit tests assert that both forms produce identical logical plans and cover k derivation, _score across joins and subsearches, and every error; explain tests pin the request (knn.filter, k, size, track_scores, method_parameters) and that no aggregation is pushed after KNN; integration tests on a cluster with the k-NN plugin cover faiss HNSW, faiss IVF and Lucene HNSW, float and byte vectors, _score equality with the DSL knn query for each space type, post-filters, stats after kNN, joins with a second index, and the no-pushdown suite.

Alternative

  • Table function (source=knn(index=…, field=…, vector=…)), the shape of the SQL vectorSearch(). Calcite would need table-function support first, filters must go inside the call, and in vectorSearch() almost no operator can be applied around it. Rejected for PPL.
  • Recognise eval d = distance(…) | sort d | head k and rewrite it to ANN. No new syntax, but the rewrite is the most failure-prone surface among the systems surveyed above (silent fallback on a second sort key, direction, metric, offset or large limit) and makes the same query approximate or exact depending on whether an index exists. Kept only for the exact functions of T3, without an ANN rewrite.
  • Only the predicate, or only the command. The predicate alone matches ES|QL and SQL; the command alone states k and the filter boundary more clearly. Both lower to one plan, so supporting both costs grammar and tests, not semantics.
  • ES|QL-style merging of adjacent wheres into the pre-filter. Avoids some "fewer than k" surprises but would make knn … | where … a pre-filter in the command form, contradicting its position.
  • Keep knn(...) as a boolean predicate inside LogicalFilter. Simplest lowering, but a set-dependent predicate inside a Filter is treated as row-local by Calcite rules (filter transposition, join pushdown); the Sort(fetch) boundary avoids that.
  • Use the neural query for everything. It does not accept raw vectors.
  • Wait for a native Calcite vector type. Blocks T1 on an upstream release and two Calcite upgrades.

Implementation Discussion

  1. Names: knn for both the function and the command, or a distinct command name (vectorsearch, knnsearch)?
  2. With neither k nor a downstream head: error (proposed) or a default k?
  3. Pre-filter boundary by position (proposed) or by merging adjacent wheres as ES|QL does?
  4. A pre-filter that cannot be pushed into knn.filter: fail with a hint (proposed) or fall back to exact search over the filtered set?
  5. Explain: is the readable KNN->{…} digest enough, or should explain also decode the wrapped query?
  6. T5 fusion: emit DSL hybrid with an in-request pipeline, or compute RRF in Calcite?
  7. Who owns knn_vector support in composite indices (OpenSearch core, k-NN, or both)?
  8. Should we open the Calcite proposals for a native vector type and distance functions now?
  9. Security: PPL issues ordinary _search requests, so document- and field-level security apply as for a hand-written knn query; reviewers from the security plugin should confirm there is no gap for vector fields.
Ngôn ngữ chính
Java
Star
176
Fork
237
Merge trung bình
2 ngày 12 giờ
Pull request đã merge (30 ngày)
34

Chuẩn bị môi trường

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của opensearch-project/sql

Tất cả issue của opensearch-project/sql

Issue tương tự

Thêm issue về Java

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.