Repository navigation
Description
Is your feature request related to a problem?
OpenSearch SQL is currently fragmented across two repositories and four engines. This fragmentation creates the same class of problems identified in the PPL unification effort (opensearch-project/opensearch-spark#1136): semantic divergence, engineering duplication, feature lag, and missed optimization opportunities.
| Repository | Engine | Scope |
|---|---|---|
opensearch-project/sql |
Legacy (NLPchina) | JOINs, UNIONs, subqueries |
opensearch-project/sql |
V2 | Simple queries, improved correctness |
opensearch-project/sql |
Calcite-based ANSI SQL (new) | Analytics engine integration, ANSI SQL compliance |
opensearch-project/opensearch-spark |
Spark SQL + Flint SQL | Spark queries, secondary index DDL |
A gap analysis that runs the full V2 + Legacy integration test suite (807 queries) against the new Calcite engine shows a 67.9% pass rate, with 259 failures across 13 categories. This quantifies the distance between the current engines and a unified SQL baseline. See #5346 (comment) below for the full breakdown.
What solution would you like?
Define a Unified SQL Language specification — an ANSI SQL core with internal language extensions that model capabilities such as custom identifier/parsing rules, relevance search and Flint DDL — and implement it once in the Calcite-based engine for reuse across both the OpenSearch and Spark.
Unified SQL Language
├── ANSI SQL Core
├── Search Extension (full-text search, vector search, identifier rules)
└── Secondary Index Extension (Flint DDL)
Phase 1: Analytics engine integration
- Core DQL — SELECT, subqueries, CTEs, window functions
- Explain support
- Full-text search functions
Phase 2: Full language unification
- V2/Legacy backward compatibility (identifier rules, type mappings, syntax gaps)
- Vector search ([Feature] Add vector search execution pipeline for vectorSearch() table function #5320)
- Flint DDL (skipping index, covering index, materialized view)
- Spark SQL alignment (via ANSI mode)
- Others: prepared statement, cursor/pagination
See #5346 (comment) below for the full design and roadmap.
What alternatives have you considered?
- Keep all engines permanently: Maintenance burden of 4 code paths, inconsistent behavior, no convergence.
- Strict ANSI SQL only: Breaks existing users who depend on full-text search functions, backtick quoting, and OpenSearch identifier conventions
- Enable V2 SQL: Since SQL V2 and PPL V3 share the same AST abstraction, it could be routed through the existing
CalciteRelNodeVisitoras PPL V3. However, this bypasses Calcite built-in logical optimizations, ANSI SQL features like CTEs etc.
Do you have any additional context?
- Related issue: [FEATURE] SQL query support for Analytics engine integration #5248 (SQL query support for Analytics engine integration)
Activity
dai-chen commentedon Apr 14, 2026
Unified Query API — SQL Gap Analysis Report (Consolidated)
Date: 2026-03-30
Branch: https://github.com/dai-chen/sql-1/tree/poc/gap-analysis-on-formal
Scope: All SQL IT tests — V2 (
org.opensearch.sql.sql.*IT, 50 classes) + Legacy (org.opensearch.sql.legacy.*IT, 39 classes) — 807 queriesPipeline:
UnifiedQueryPlanner(Calcite native SQL parser) →UnifiedQueryCompiler→PreparedStatement.executeQuery()Summary
All Failure Categories
ALLOW_HYPHEN_IN_IDENTIFIER+ custom lexer ruleswildcard_query,queryoperatorsEXPR_TIMESTAMP/EXPR_TIMEconverters in result set readerkey=valuenamed parameter syntax in function callsQuoting.BACK_TICKinSqlParser.Config. Or enable MySQL conformance*in nested()*wildcard expansion inside function arguments during schema resolution[field]Syntax[field1, field2]array literal syntax in function argsmatch()Reserved WordMATCHkeyword in parser config. Or enable MySQL conformanceCategory 0: Table Identifier Compatibility (~750 queries, masked by pre-processing)
V2/Legacy allows special characters in table identifiers without quoting. Calcite follows ANSI SQL where these require delimited identifiers (double quotes).
opensearch-sql_test).kibana)@prefix (@timestamp)index*)The gap analyzer applies a regex-based workaround (
quoteHyphenatedTableNames) that wraps hyphenated names afterFROM/JOINin double quotes. This is fragile — it does not cover subqueries, CTEs, or other table reference positions. In production, the unified engine needs a proper identifiercompatibility layer (either auto-quoting in the query pre-processor or extending the Calcite parser's identifier rules).
Note: See Identifier documentation for V2's full identifier rules including backtick and double-quote delimited identifiers.
Category 1: Missing Calcite Functions (86 queries)
Error:
No match found for function signature <name>(...)wildcard_query()/wildcardquery()WHERE wildcard_query(KeywordBody, 'test*')match_query()/matchquery()WHERE match_query(lastname, 'Bates')match_phrase()/matchphrase()WHERE match_phrase(phrase, 'quick fox')match_phrase_prefix()WHERE match_phrase_prefix(Title, 'champagne be')query()WHERE query('Tags:taste')multi_match()/multimatch()WHERE multi_match([Title, Body], 'IPA')matchphrasequery()WHERE matchphrasequery(phrase, 'quick fox')convert_tz()SELECT convert_tz('2021-05-12','+10:00','+11:00')DATETIME()SELECT DATETIME('2008-01-01 02:00:00+10:00', '-10:00')nested()SELECT nested(message.info)percentiles()SELECT percentiles(age, 25.0, 50.0, 75.0, 99.9)ISNULL()SELECT ISNULL(lastname)Log()(case-sensitive)SELECT Log(MAX(age) + MIN(age))Note: Core relevance functions (
match,match_phrase,match_bool_prefix,match_phrase_prefix,multi_match,simple_query_string,query_string) support are in progress (#5279)Category 2: EXPR_TIMESTAMP/TIME Type Conversion (22 queries)
Error:
class java.lang.String: need to implement EXPR_TIMESTAMP/EXPR_TIMEOpenSearch returns
EXPR_TIMESTAMP/EXPR_TIMEtyped values that the Calcite pipeline doesn't have a converter for. Affects datetime columns and functions likeDATE_FORMAT(). Includes 1 EXPR_TIME query (same root cause).Category 3: Comma-Join / Nested Table Syntax (26 queries)
Error:
Table '<name>' not found/no such index [<alias>]Legacy syntax
FROM t1 e, e.message mtreatse.messageas a nested field path. Calcite parses it as a table reference. This is an OpenSearch-specific semantic with no ANSI SQL equivalent. Includes 5 queries (previously "Index Not Found") where the table alias (e,tab) passes through to OpenSearch as a literal index name.Category 4: Relevance Function Named Parameters (13 queries)
Error:
Column 'slop' not found/Column 'boost' not found/Column 'analyzer' not found/Column 'query' not foundRelevance functions use
key=valuenamed parameter syntax (e.g.,match_phrase(phrase, 'quick fox', slop=2)). Calcite doesn't understand this convention and treatsslop,boost,analyzer,query,max_expansionsas column references.Category 5: String Literal vs Identifier (2 queries)
Error:
Column 'Hello' not found in any tableCalcite follows ANSI SQL: double-quoted strings are identifiers. V2 treats them as string literals (
SELECT "Hello").Fix: Configure
SqlParser.Configquoting behavior, or accept ANSI behavior and document the migration.Category 6: Backtick Identifiers (8 queries)
Error:
Lexical error: Encountered "\" (96)**Fix:** ConfigureQuoting.BACK_TICKinSqlParser.Config`.Category 7: GROUP BY Expression Issues (8 queries)
Error:
Expression 'lastname' is not being groupedCalcite enforces strict GROUP BY validation per ANSI SQL. V2 is more lenient. Includes 1 query where a SELECT alias used in GROUP BY is not resolved.
Category 8: Wildcard
*in nested() (6 queries)Error:
Unknown field '*'nested(message.*)wildcard expansion fails during schema resolution. Distinct from Cat 3 — thenested()function parses fine, but*expansion inside function arguments is unsupported.Category 9: Square Bracket
[field]Syntax (17 queries)Error:
Encountered "[" at line 1, column NCalcite's parser does not recognize
[field1, field2]array literal syntax used bymulti_match,query_string, andhighlightfunctions.Category 10:
match()Reserved Word (16 queries)Error:
Encountered "match" at line 1, column NMATCHis a SQL reserved keyword in Calcite (used forMATCH_RECOGNIZE). OpenSearch usesmatch()as a full-text search function in WHERE/HAVING clauses.Category 11: Other (28 queries)
;before Calcite parseCategory 12: Result Mismatch (27 queries)
Both pipelines execute successfully but return different data.
_id,_index, etc. fromSELECT *projection\escapedai-chen commentedon Apr 14, 2026
Unified SQL — Design & Roadmap [WIP]
1. Gap Analysis Interpretation
HYPHENATED_IDENTIFIERsupportPPLBuiltinOperatorsinto SQLFrameworkConfig.operatorTable(). Add missingwildcard_query,queryoperatorsEXPR_TIMESTAMP/EXPR_TIMEconverters in result set readerkey=valuenamed parameter syntax in function callsQuoting.BACK_TICKinSqlParser.Config. Or enable MySQL conformance*in nested()*wildcard expansion inside function arguments during schema resolution[field]Syntax[field1, field2]array literal syntax in function argsmatch()Reserved WordMATCHkeyword via Babel parser* Category 0 is not counted in the 259 total — masked by gap analyzer pre-processing.⚠️ Debatable · ❌ Not carrying forward (ANSI SQL is correct)
✅ Must support ·
2. Roadmap & Full Scope
Phase 1 covers what's required for the Analytics-engine integration — ANSI SQL with full-text search functions. Phase 2 items need explicit design decisions on how far to diverge from strict ANSI SQL for OpenSearch usability.
/_explain)vectorSearch()table function, #5320)?params via REST + JDBC driverfetch_size+ cursor ID (no agg/JOIN)3. Unified SQL Language [TBD]
The unified query library defines a single SQL language specification built on ANSI SQL with capability extensions:
The "extension" concept is an internal organizational model — it tracks what the Unified SQL Language adds beyond ANSI SQL. Externally, these are all first-class features of one coherent language specification. Extensions are organized by capability, not by engine, making them portable across Calcite, Spark, DataFusion, or any future execution engine.
Search Extension
match(),match_phrase(),wildcard_query(),query_string(),multi_match(),highlight(),score()key=valuesyntax in function callsmatch_phrase(field, text, slop=2, boost=1.0)multi_match([field1, field2], text)vectorSearch(table, field, vector, option)logs-2024), dot-prefixed (.kibana), backtick quotingSecondary Index Extension (Flint DDL)
CREATE/DROP/ALTER/REFRESH/VACUUM/ANALYZE SKIPPING INDEXCREATE/DROP/ALTER/REFRESH/VACUUM INDEXCREATE/DROP/ALTER/REFRESH/VACUUM MATERIALIZED VIEWSHOW FLINT INDEXES,RECOVER INDEX JOB4. Implementation Architecture (in Calcite)
The capability extensions map to Calcite's distinct extension seams. Each seam has a specific role — they should not be conflated:
config.fmpp,parserImpls.ftl)key=value), array literals ([field1, field2]), Flint DDL statements,SHOW/DESCRIBESqlParser.Config,Lex)SqlConformance)SqlOperatorTable)vectorSearch()table functionHow extensions compose
feat(api): Define unified SQL language spec with composable extensions (
feat(api): Define unified SQL language spec with composable extensions (
feat(api): Define unified SQL language spec with composable extensions (
feat(api): Define unified SQL language spec with composable extensions (
feat(api): Define unified SQL language spec with composable extensions (
feat(api): Define unified SQL language spec with composable extensions (
feat(api): Define unified SQL language spec with composable extensions (
feat(api): Define unified SQL language spec with composable extensions (
feat(api): Define unified SQL language spec with composable extensions (
feat(api): Define unified SQL language spec with composable extensions (
feat(api): Define unified SQL language spec with composable extensions (
Define unified SQL language spec with composable extensions (#5360)
Define unified SQL language spec with composable extensions (opensear…
dai-chen commentedon May 7, 2026
Function Registration Criteria
A function is registered in the unified SQL spec only when it has consistent semantics across all execution paths in our stack: OpenSearch SQL V2/legacy, PPL, SparkSQL, and DataFusion (Analytics Engine). Functions must either exist as exact matches in all engines or introduce no conflicting definition in any engine. This ensures the unified language surface remains portable. Functions with engine-specific semantics (e.g., MySQL-only behavior diverging from Spark) should be excluded to avoid creating unification debt.
Tier 1: Calcite Standard (
SqlStdOperatorTable) — Zero RiskAlready available in Calcite's standard operator table. Enable directly.
Math
ABS(expr)SqlStdOperatorTable.ABSACOS(expr)SqlStdOperatorTable.ACOSASIN(expr)SqlStdOperatorTable.ASINATAN(expr)SqlStdOperatorTable.ATANATAN2(y, x)SqlStdOperatorTable.ATAN2CEIL(expr)/CEILING(expr)SqlStdOperatorTable.CEILCOS(expr)SqlStdOperatorTable.COSCOT(expr)SqlStdOperatorTable.COTDEGREES(expr)SqlStdOperatorTable.DEGREESEXP(expr)SqlStdOperatorTable.EXPFLOOR(expr)SqlStdOperatorTable.FLOORLN(expr)SqlStdOperatorTable.LNLOG10(expr)SqlStdOperatorTable.LOG10MOD(expr1, expr2)SqlStdOperatorTable.MODPI()SqlStdOperatorTable.PIPOWER(expr1, expr2)SqlStdOperatorTable.POWERRADIANS(expr)SqlStdOperatorTable.RADIANSRAND([seed])SqlStdOperatorTable.RANDROUND(expr, d)SqlStdOperatorTable.ROUNDSIGN(expr)SqlStdOperatorTable.SIGNSIN(expr)SqlStdOperatorTable.SINSQRT(expr)SqlStdOperatorTable.SQRTTAN(expr)SqlStdOperatorTable.TANTRUNCATE(expr, d)SqlStdOperatorTable.TRUNCATEString
ASCII(str)SqlStdOperatorTable.ASCIILOWER(str)SqlStdOperatorTable.LOWERUPPER(str)SqlStdOperatorTable.UPPERSUBSTRING(str, pos[, len])SqlStdOperatorTable.SUBSTRINGTRIM([LEADING|TRAILING|BOTH] FROM str)SqlStdOperatorTable.TRIMREPLACE(str, search, repl)SqlStdOperatorTable.REPLACEPOSITION(sub IN str)SqlStdOperatorTable.POSITIONCHAR_LENGTH(str)SqlStdOperatorTable.CHAR_LENGTHDate/Time
CURRENT_DATESqlStdOperatorTable.CURRENT_DATECURRENT_TIMESTAMPSqlStdOperatorTable.CURRENT_TIMESTAMPCURRENT_TIMESqlStdOperatorTable.CURRENT_TIMEYEAR(date)SqlStdOperatorTable.YEARMONTH(date)SqlStdOperatorTable.MONTHDAYOFMONTH(date)SqlStdOperatorTable.DAYOFMONTHHOUR(ts)SqlStdOperatorTable.HOURMINUTE(ts)SqlStdOperatorTable.MINUTESECOND(ts)SqlStdOperatorTable.SECONDDAYOFWEEK(date)SqlStdOperatorTable.DAYOFWEEKDAYOFYEAR(date)SqlStdOperatorTable.DAYOFYEARQUARTER(date)SqlStdOperatorTable.QUARTERWEEK(date)SqlStdOperatorTable.WEEKTIMESTAMPADD(unit, n, ts)SqlStdOperatorTable.TIMESTAMP_ADDTIMESTAMPDIFF(unit, a, b)SqlStdOperatorTable.TIMESTAMP_DIFFConditional
CASE WHEN ... THEN ... ENDSqlStdOperatorTable.CASECOALESCE(expr1, expr2, ...)SqlStdOperatorTable.COALESCENULLIF(expr1, expr2)SqlStdOperatorTable.NULLIFAggregate
AVG(expr)SqlStdOperatorTable.AVGCOUNT(expr)SqlStdOperatorTable.COUNTMAX(expr)SqlStdOperatorTable.MAXMIN(expr)SqlStdOperatorTable.MINSUM(expr)SqlStdOperatorTable.SUMVAR_POP(expr)SqlStdOperatorTable.VAR_POPVAR_SAMP(expr)SqlStdOperatorTable.VAR_SAMPSTDDEV_POP(expr)SqlStdOperatorTable.STDDEV_POPSTDDEV_SAMP(expr)SqlStdOperatorTable.STDDEV_SAMPTier 1 Total: ~41 functions
Tier 2: Calcite Library (
SqlLibrary.SPARK) — Low RiskRequire enabling the SPARK library tag. All have exact SparkSQL semantics.
POW(x, y)SqlLibraryOperators.POW(SPARK)LEFT(str, n)SqlLibraryOperators.LEFT(SPARK)RIGHT(str, n)SqlLibraryOperators.RIGHT(SPARK)CONCAT_WS(sep, str1, ...)SqlLibraryOperators.CONCAT_WS_SPARK(SPARK)REVERSE(str)SqlLibraryOperators.REVERSE_SPARK(SPARK)LTRIM(str)SqlLibraryOperators.LTRIM(SPARK)RTRIM(str)SqlLibraryOperators.RTRIM(SPARK)CONCAT(str1, str2, ...)SqlLibraryOperators.CONCAT_FUNCTION(MYSQL, BIG_QUERY)LENGTH(str)SqlLibraryOperators.LENGTH(SPARK)IFNULL(x, y)SqlLibraryOperators.IFNULL(SPARK)NVL(x, y)SqlLibraryOperators.NVL(SPARK)DATE_ADD(date, numDays)SqlLibraryOperators.DATE_ADD_SPARK(SPARK, HIVE)DATE_SUB(date, numDays)SqlLibraryOperators.DATE_SUB_SPARK(SPARK, HIVE)REGEXP_REPLACE(str, pat, repl)SqlLibraryOperators.REGEXP_REPLACE_3(POSTGRESQL, BIG_QUERY)Tier 2 Total: ~14 functions
Implementation
For functions tagged under other libraries but Spark-compatible (e.g.,
REGEXP_REPLACE_3), cherry-pick individually rather than enabling the entire library.Tier 3: Custom Registration (Spark-Aligned) — Moderate Effort
Not in Calcite's standard/library tables but have exact SparkSQL equivalents. Implement as custom
SqlFunctionwith Spark-identical signatures.IF(cond, expr1, expr2)(BOOLEAN, ANY, ANY) → ANYISNULL(expr)(ANY) → BOOLEANLOG(x)/LOG(base, x)(NUMERIC[, NUMERIC]) → DOUBLELOG_MYSQLvariant (accepts 1 or 2 args)DATE_FORMAT(ts, fmt)(TIMESTAMP, VARCHAR) → VARCHARFROM_UNIXTIME(n[, fmt])(BIGINT[, VARCHAR]) → VARCHARUNIX_TIMESTAMP([ts[, fmt]])([TIMESTAMP[, VARCHAR]]) → BIGINTDATEDIFF(end, start)(DATE, DATE) → INTNOW()() → TIMESTAMPTier 3 Total: ~8 functions
Tier 4: DO NOT REGISTER — Unification Risk
These functions either don't exist in SparkSQL, have different semantics, or are MySQL/OpenSearch-specific.
MySQL-isms (different or absent in Spark)
TRUNCATE(x, d)STRCMP(a, b)ADDDATE(date, ...)DATE_ADDSUBDATE(date, ...)DATE_SUBDATE(expr)to_date()TIME(expr)TIMESTAMP(expr)to_timestamp()TO_DAYS(date)MAKEDATE(year, doy)make_date(y,m,d)MAKETIME(h, m, s)CURDATE(),CURTIME()NOW(),SYSDATE()NOWis Tier 3 (Spark has it);SYSDATEis MySQL-specificDAYNAME(x),MONTHNAME(x)WEEK(date, mode)STR_TO_DATE,GET_FORMAT,CONVERT_TZFROM_DAYS,TO_SECONDS,YEARWEEKSEC_TO_TIME,TIME_TO_SECUTC_DATE,UTC_TIME,UTC_TIMESTAMPPERIOD_ADD,PERIOD_DIFFTIMEDIFF,ADDTIME,SUBTIMEBigQuery-specific (no Spark equivalent)
SAFE_DIVIDEREGEXP_CONTAINSRLIKEJava Math / Non-standard
SINH,COSH,EXPM1RINT,SIGNUME()2.718...STD(x)CONV(x, from, to)CRC32(s)Operator function-call forms
ADD(a, b),SUBTRACT(a, b),MULTIPLY(a, b),DIVIDE(a, b),MODULUS(a, b)+,-,*,/,MODOpenSearch-specific
NESTED,REVERSE_NESTEDGEO_INTERSECTS,GEO_BOUNDING_BOXTERMS,HIGHLIGHT,SCORETYPEOF,TYPE,FIELDPERCENTILE,PERCENTILE_APPROXpercentile_approxMATCH,MATCH_PHRASE, etc.)UnifiedFunctionSpec.RELEVANCEDefine unified SQL language spec with composable extensions (opensear…