Skip to content

Support bracket syntax json['key'] for JSON type - #107039

Merged
alexey-milovidov merged 26 commits into
masterfrom
json-array-element-syntax
Sep 13, 2026
Merged

alexey-milovidov merged 26 commits into
masterfrom
json-array-element-syntax

Conversation

@Avogar

@Avogar Avogar commented Jun 10, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • New Feature

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Add support for accessing JSON subcolumns using bracket syntax, e.g. json['key1']['key2'], which the parser translates to nested arrayElement calls.


Workflow [PR]
Sync PR [sync-upstream/pr/107039]

Version info

  • Merged into: 26.9.1.1413 (included in 26.9 and later)

Add support for accessing JSON subcolumns using bracket syntax,
e.g. `json['key1']['key2']`, which the parser translates to nested
`arrayElement` calls.

Changes:

- `arrayElement` function: add `getReturnTypeImpl(ColumnsWithTypeAndName)`
  overload that resolves the exact return type for JSON typed paths
  (e.g. `UInt32` instead of `Dynamic`), and `executeJSON` that extracts
  the combined subcolumn via `IDataType::getSubcolumn`.

- `FunctionToSubcolumnsPass`: add a unified `optimizeJSONArrayElementChain`
  transformer registered in both `node_transformers` (single key) and
  `chained_node_transformers` (chains). Single `json['key']` is rewritten
  to a direct subcolumn read `json.@`key``. Chains like `json['a']['b']['c']`
  are collapsed into `json.@`a`.b.c`.

- Fix `chained_pattern_inner_nodes` check ordering in the first pass:
  move it before the single-level match to prevent double-counting when
  an inner function also matches a single-level transformer.

- Extract `DataTypeObject::getCombinedSubcolumnName` static method that
  uses `backQuote` for proper escaping of special characters in key names.
  Replace all manual combined subcolumn name formations in `tupleElement`,
  `FunctionsJSON`, `arrayElement`, and `FunctionToSubcolumnsPass`.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [23bb178]

Summary: ✅


AI Review

Summary

This PR adds json['key'] and chained bracket access for JSON by routing arrayElement through JSON subcolumns and by teaching FunctionToSubcolumnsPass to flatten chained lookups into combined @ subcolumns. The nullable-carrier and documentation follow-ups from the earlier review threads are now in place, but the chained rewrite is still incorrect for typed Map paths inside JSON, so the feature is not ready to merge.

Findings

❌ Blockers

  • [src/Analyzer/Passes/FunctionToSubcolumnsPass.cpp:877] The chained arrayElement rewrite assumes every string-key hop is still a JSON-path lookup, but JSON can contain typed Map paths that change the carrier mid-chain. On JSON(m Map(String, UInt32)), j['m']['k'] must behave like j.m['k']: the inner step returns a Map, and the outer step must use Map key lookup. The new flattening instead reads j.@`m`.k, which DataTypeObject resolves as a JSON path m.k; typed Map paths are stored atomically and expose keys via key_<serialized_key>, so the optimized form can no longer see values that live only inside the typed Map.
    Suggested fix: flatten only while each intermediate result type still has JSON-path semantics (Dynamic / JSON), and add a focused regression for JSON(m Map(String, UInt32), mj Map(String, JSON)) covering j['m']['k'] and j['mj']['k']['x'].
Final Verdict

Changes requested: the chained bracket optimization is not semantics-preserving once an intermediate hop yields a typed Map, so optimize_functions_to_subcolumns can make valid JSON queries return different results.

LLVM Coverage Report

⚠️ No coverage measurement for commit 23bb178: incomplete coverage measurement: 1 of 21 shard profiles are missing: LLVM_COVERAGE_FILE_it_7.profdata.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Jun 10, 2026
… JSON type

When `json_type_escape_dots_in_keys` is enabled, dots in JSON keys are
stored escaped as `%2E`. This commit makes `arrayElement` (bracket
syntax `json['key.with.dots']`) and the `FunctionToSubcolumnsPass`
rewrite aware of this setting, so that dotted keys are properly escaped
before subcolumn lookup.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Comment thread src/Functions/array/arrayElement.cpp Resolved
Avogar and others added 2 commits June 25, 2026 14:55
…:ClickHouse/ClickHouse into json-array-element-syntax
Document the `json['key']` bracket syntax in the JSON type documentation
page and in the `arrayElement` FunctionDocumentation.

Fix `arrayElement` for JSON when both arguments are constant:
`useDefaultImplementationForConstants` unwraps them into plain 1-row
columns, so `executeJSON` must also accept a non-const `ColumnString`
with 1 row.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Avogar and others added 2 commits July 9, 2026 14:11
…:ClickHouse/ClickHouse into json-array-element-syntax
…ntChain`

The `optimizeJSONArrayElementChain` function in `FunctionToSubcolumnsPass`
was missing the `sourceHasColumn` check that all neighbouring subcolumn
optimizers use.  Without it, if a table contains a physical column whose
name happens to equal the generated JSON subcolumn name (e.g. `json.@`a``
for `json['a']`), the optimizer would silently rewrite `json['a']` to a
`ColumnNode` pointing at that physical column instead of at the JSON
subcolumn, returning wrong results when `optimize_functions_to_subcolumns`
is enabled.

Fix: apply the same two-condition guard used everywhere else:

    if (sourceHasColumn(ctx.column_source, full_name) || !canOptimizeToSubcolumn(...))
        return;

A regression test is added that creates a table with a physical column
`\`json.@\`a\`\`` alongside a `json JSON` column, inserts rows with
`{"a": 42}` / `{"a": 100}`, and verifies that `json['a']` returns the
JSON values (not the physical column values 999/888) regardless of the
`optimize_functions_to_subcolumns` setting.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@mintlify

mintlify Bot commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated
ClickHouse-docs 🟢 Ready View Preview Sep 13, 2026, 9:25 AM

Comment thread src/Functions/array/arrayElement.cpp Resolved
`arrayElementOrNull` shares the same `FunctionArrayElement` template as
`arrayElement`, but the JSON code path ignores `is_null_mode` — a missing
typed key returns the default value (e.g. 0) instead of NULL. Rather than
adding Nullable wrapping to the JSON subcolumn accessor, reject JSON
arguments in `arrayElementOrNull` with a clear error pointing users to
`arrayElement`.

Guards are added in both `getReturnTypeImpl` and `executeImpl` so the
error is raised regardless of how the function is invoked.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.80% 85.80% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 77.90% 77.90% +0.00%

Changed lines: Changed C/C++ lines covered: 113/136 (83.09%) · Uncovered code

Full report · Diff report

Avogar and others added 3 commits August 11, 2026 19:29
Resolve conflicts:
- src/Functions/array/arrayElement.cpp: drop obsolete out-of-line
  create(); FunctionWithLowCardinalityFastPath now forwards context to
  the constructor. Keep both getReturnTypeImpl(ColumnsWithTypeAndName)
  and tryExecuteLowCardinality.
- docs: newjson.md was removed on master (docs are source-generated);
  move the json['key'] bracket-syntax section into the embedded
  documentation in src/DataTypes/DataTypeObject.cpp.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 23bb17888 with master c287fac2b (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

30 object files changed (+107.94 KiB total), 0 added.

Object file Master PR Δ
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/FunctionsJSON.cpp.o 4.17 MiB 4.06 MiB -112.33 KiB (-2.63%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/FillingStep.cpp.o 158.83 KiB 270.11 KiB +111.29 KiB (+70.07%)
src/Functions/array/CMakeFiles/clickhouse_functions_array.dir/arrayElement.cpp.o 10.10 MiB 10.17 MiB +66.16 KiB (+0.64%)
src/CMakeFiles/dbms.dir/Core/SortDescription.cpp.o 204.89 KiB 221.96 KiB +17.07 KiB (+8.33%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

940 translation units recompiled, 6909 s compile time in total, 940 of them have a recent master baseline.

Job report

@vdimir vdimir self-assigned this Aug 25, 2026
Comment thread src/Functions/array/arrayElement.cpp Outdated
FunctionDocumentation::Arguments arguments = {
{"arr", "The array to search. [`Array(T)`](/sql-reference/data-types/array)."},
{"n", "Position of the element to get. [`(U)Int*`](/sql-reference/data-types/int-uint)."}
{"arr", "The array to search. [`Array(T)`](/sql-reference/data-types/array). Or a [`JSON`](/sql-reference/data-types/newjson) column."},

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

By the way Map also already supported arrayElement, but not mentioned here

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🕵 Good catch — addressed: the arrayElement documentation now lists Map alongside Array, QBit and JSON in the description, the argument descriptions and the returned value, with a SELECT map('a', 1, 'b', 2)['b'] example. arrayElementOrNull documents the Map behaviour too (an absent key gives NULL instead of the value type's default).

Avogar and others added 2 commits August 25, 2026 20:49
The `QBit` and `JSON` first-argument forms were described in two
differently shaped paragraphs, and `Map` was not documented at all
even though `m['key']` is `arrayElement`. List all non-`Array` first
arguments in one parallel structure and extend the argument, returned
value and example sections accordingly, for both `arrayElement` and
`arrayElementOrNull`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Comment thread src/Functions/array/arrayElement.cpp Resolved
@Avogar
Avogar added this pull request to the merge queue Sep 9, 2026
@alexey-milovidov
alexey-milovidov removed this pull request from the merge queue due to a manual request Sep 9, 2026
@alexey-milovidov alexey-milovidov self-assigned this Sep 9, 2026
alexey-milovidov and others added 2 commits September 12, 2026 04:07
Master replaced `canOptimizeToSubcolumn` with `canOptimizeToExpectedSubcolumn`,
which additionally checks the substreams path of the resolved subcolumn, so the
JSON bracket rewrite in `FunctionToSubcolumnsPass` no longer compiled after the
merge.

The rewrite means the JSON combined (`@`) subcolumn of the accessed path, so it
now asks for exactly that substream via a new
`SerializationObjectCombinedPath::isCombinedPathSubcolumn` predicate. As a side
effect, a `Tuple` element or a typed path that happens to claim the same flat
subcolumn name no longer diverts the rewrite.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Address review: `arrayElement` recognized only a bare `DataTypeObject`, so `nullable_json['a']`
fell through to the legacy array path and failed with "First argument ... must be array", even
though `nullable_json.a` and `tupleElement(nullable_json, 'a')` already work. Schema inference and
existing tables commonly produce `Nullable(JSON)`, so the bracket syntax disappeared as soon as the
carrier became nullable.

`getReturnTypeImpl` now unwraps `Nullable(JSON)` and promotes the extracted path with
`makeExtractedSubcolumnsNullableOrLowCardinalityNullableSafe`, and `executeJSON` unwraps
`ColumnNullable(ColumnObject)` and folds the outer null map into the extracted path with the same
rules as `tupleElement`: a path that can represent NULL (`Dynamic`, `Variant`, `Nullable`,
`LowCardinality(Nullable)` or a type wrappable into `Nullable`) gets the mask OR-ed in, a typed
path that has no NULL representation (`Array`, `Map`) is default-filled. The result is identical in
value and in type to reading the subcolumn directly. `arrayElementOrNull` keeps rejecting JSON.

The analyzer rewrite needs no change: `FunctionToSubcolumnsPass` keys its transformers on the
column's type id, which is `Nullable` and not `Object` for such a column, so bracket access on a
`Nullable(JSON)` column is simply not rewritten and behaves the same with and without
`optimize_functions_to_subcolumns`.

The new test also pins the semantics of chained bracket access over a path that holds a scalar in
one row and an object in another, which a review raised as well: under
`optimize_functions_to_subcolumns` the chain is flattened into the JSON path and matches the dot
syntax `json.c.d` (`NULL` for the scalar row), and without it the outer access goes through the
`Dynamic` type mismatch rules. This divergence is the author's deliberate trade-off for the
subcolumn optimization; the test makes it explicit instead of leaving it undocumented.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Comment thread src/Functions/array/arrayElement.cpp Resolved
Comment thread src/DataTypes/DataTypeObject.cpp Resolved
alexey-milovidov and others added 3 commits September 13, 2026 07:57
…syntax

# Conflicts:
#	src/Analyzer/Passes/FunctionToSubcolumnsPass.cpp
…are the real subcolumn type for chained JSON bracket access

Master now passes the whole `ColumnContext` and the type the rewrite is declared to produce. The
`json['c']['d']` rewrite declared `Dynamic` for every chain, but a typed path such as `JSON(c.d UInt32)`
resolves in storage to `UInt32`, so the stricter check refused the rewrite. Declare the type storage
really produces and cast back to the type of the original expression, as the single-key case already does.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…`arrayElement`

The JSON-specific `getReturnTypeImpl` required a constant `String` key and rejected
`json[CAST('a', 'Nullable(String)')]` and `json[CAST(NULL, 'Nullable(String)')]` at analysis, while the
`Array` and `Map` overloads and `executeImpl` already follow the nullable-key convention. Resolve the key
through its nested column, return `Nullable(Nothing)` for a `NULL` key and promote the result for a nullable
key the way a `Nullable(JSON)` carrier does.

Also reword the `Nullable(JSON)` documentation: bracket access follows the nullability rules of `json.key`,
so a non-nullable typed path such as `Array` keeps its default value for a `NULL` row.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 13, 2026
Merged via the queue into master with commit cb26a48 Sep 13, 2026
177 checks passed
@alexey-milovidov
alexey-milovidov deleted the json-array-element-syntax branch September 13, 2026 17:30
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 13, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@Avogar @vdimir @alexey-milovidov — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

This branch was successfully deployed

1 active deployment
staging - docs — 23bb1788 Deployed Sep 13, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-json-datatype JSON/Dynamic/Object datatype: semi-structured column storage, typed and dynamic paths, sub-object... pr-feature Pull request with new product feature pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants