Skip to content

Add JSONValues function to extract values at specific JSON paths - #104580

Closed
mneedham wants to merge 11 commits into
ClickHouse:masterfrom
mneedham:json-value
Closed

mneedham wants to merge 11 commits into
ClickHouse:masterfrom
mneedham:json-value

Conversation

@mneedham

@mneedham mneedham commented May 11, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • New Feature

Changelog entry:

Add JSONValues(json, 'path1', 'path2', ...) function that returns an Array(String) of values at the specified paths from a JSON column, in argument order. Absent or null paths are omitted. Supports text indexes for efficient filtering on specific subcolumns.

Why is this needed?

When working with a JSON column, there are two existing options for building a text index:

  1. Separate indexes per subcolumn — works but creates multiple index structures and per-path maintenance overhead:

    INDEX idx_type   json.type.name::String   TYPE text(tokenizer = 'ngrams') GRANULARITY 100000000,
    INDEX idx_player json.player.name::String TYPE text(tokenizer = 'ngrams') GRANULARITY 100000000
  2. JSONAllValues(json) — a single index covering all paths. This is simpler but the index is larger (covers every path in every row) and produces more false positives at granule-skip time when you only care about a few specific paths.

There is no way to get a single index covering only a chosen subset of paths - the ClickHouse docs AI says the following:

"if you want a single index covering both paths, you'd need to use JSONAllValues (which covers all paths) — there's no built-in way to pass a subset of paths to it"

So this function would solve the problem. We would use it like this:

CREATE TABLE events
(
    match_id UInt32,
    json JSON(id String, index UInt32),
    INDEX vals JSONValues(json, ['type.name', 'player.name'])
        TYPE text(tokenizer = 'ngrams') GRANULARITY 100000000
)
ENGINE = MergeTree
ORDER BY (match_id, json.index)

Queries on the listed subcolumns use the index; queries on unlisted paths (e.g., json.score) would ignore it.

What changed

  • src/Functions/JSONAllValues.cpp — added FunctionJSONValues. Shared helpers (serializeValueIntoResult, emitSharedDataValue) are extracted as free functions used by both JSONAllValues and JSONValues. Per-path lookup uses typed/dynamic column maps (O(1)) and ColumnObject::findPathLowerBoundInSharedData for binary search in shared data.

  • src/Storages/MergeTree/MergeTreeIndexJSONSubcolumnHelper — added tryMatchNodeToJSONValuesIndex which parses JSONValues(col, 'path1', 'path2', ...) index expression names and checks whether the queried subcolumn path is one of the listed paths.

  • src/Storages/MergeTree/MergeTreeIndexConditionText.cpp — wired tryMatchNodeToJSONValuesIndex into the two call sites that currently check for JSONAllValues.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Motivation: Users building text indexes on JSON columns currently have no way to target specific paths with a single index. JSONValues enables a smaller, more precise index that avoids false positives from unrelated paths.

Parameters:

  • json — a column of type JSON
  • path1, path2, ... — one or more constant string path names (dot-separated, e.g. 'type.name')

Example:

-- Function usage
SELECT JSONValues(json, 'type.name', 'player.name') FROM events;
-- ['goal', 'Salah']

-- As a text index expression
INDEX idx JSONValues(json, ['type.name', 'player.name']) TYPE text(tokenizer = 'ngrams') GRANULARITY 100000000

Extra notes:

I did also try to create an index like this:

CREATE TABLE events
(
    match_id UInt32,
    json JSON(id String, index UInt32),
    INDEX vals [json.type.name, json.player.name]
        TYPE text(tokenizer = 'ngrams') GRANULARITY 100000000
)
ENGINE = MergeTree
ORDER BY (match_id, json.index)

And it created the index (at least as far as system.parts told me!) but then didn't use it at query time.

mneedham and others added 2 commits May 11, 2026 12:30
`JSONValues(json, 'path1', 'path2', ...)` returns an `Array(String)` of
values at the specified paths, in argument order. Absent or null paths are
omitted from the row's array.

This complements `JSONAllValues` (which returns all paths) and enables
focused text indexes covering only the paths you care about:

    INDEX idx JSONValues(json, 'type.name', 'player.name')
        TYPE text(tokenizer = 'ngrams') GRANULARITY 100000000

The two free helper functions (`serializeValueIntoResult`,
`emitSharedDataValue`) are shared between both functions in the same file.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
`MergeTreeIndexConditionText` now recognises indexes built on
`JSONValues(col, 'path1', 'path2', ...)` when filtering on subcolumns
of `col`. A query like `WHERE json.player.name LIKE '%x%'` will use
the index if `player.name` is one of the listed paths.

The matching logic lives in `tryMatchNodeToJSONValuesIndex` /
`tryMatchColumnToJSONValuesIndex` (added to
`MergeTreeIndexJSONSubcolumnHelper`), which parses the index expression
string to extract the JSON column name and path list, then checks the
queried subcolumn path against that list.

Paths not listed in the index (e.g. `json.score`) correctly fall through
without triggering the index.

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

clickhouse-gh Bot commented May 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [71b296b]


AI Review

Summary

This PR adds JSONValues(json, paths) and wires it into text-index matching for JSON subcolumns. The current revision still has two correctness gaps in index matching/skipping that can produce false-negative granule pruning, so it should not be approved yet.

PR Metadata
  • Changelog category: New Feature is appropriate for this change.
  • Changelog entry: required and present, but currently inaccurate because it still documents the old varargs signature (JSONValues(json, 'path1', 'path2', ...)) while the implementation requires a constant Array(String).
  • Suggested replacement text:
    Add JSONValues(json, ['path1', 'path2', ...]) function that returns an Array(String) of values at specified JSON paths (in argument order), omitting absent/null paths and non-nullable typed defaults that are indistinguishable from absence; also enable text-index matching for listed JSON subcolumns.
Findings

❌ Blockers

  • [src/Storages/MergeTree/MergeTreeIndexJSONSubcolumnHelper.cpp:141] parseJSONValuesColumnName does not handle SQL-escaped quotes in string literals. Example: JSONValues(data, ['a''b']) is parsed as paths a and b, which violates the “only explicitly listed paths are indexable” contract and can make unrelated subcolumns match the index, leading to incorrect skipping decisions.
    Suggested fix: parse array elements with proper SQL string-literal escaping (or parse function arguments from AST instead of manual string slicing).

  • [src/Storages/MergeTree/MergeTreeIndexConditionText.cpp:1222] IN/globalIn now allows JSONValues index usage via has_index, but it does not apply the default-value safety check used for equals. For non-nullable typed paths where JSONValues omits defaults, set elements equal to the type default can still be semantically matching (including absent rows) while corresponding index tokens are missing, creating false-negative skip risk (e.g. FixedString with ngrams).
    Suggested fix: apply an isJSONPathFilterSafe-equivalent check to set elements before enabling JSONValues-based skipping.

Tests
  • ⚠️ Add a stateless regression for escaped path literals in JSONValues index definitions (e.g. ['a''b']) proving only the exact path is matched for index usage.
  • ⚠️ Add a stateless regression for IN with default values on non-nullable typed paths using a tokenizer that emits non-empty tokens for defaults (e.g. ngrams + FixedString), verifying no false-negative skipping.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
  1. Fix JSONValues path-list parsing to handle escaped SQL string literals correctly.
  2. Add default-value safety handling for IN/globalIn with JSONValues indexes.
  3. Update the PR changelog entry text to match the implemented function signature.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label May 11, 2026
Comment thread src/Functions/JSONAllValues.cpp Resolved
@CurtizJ

CurtizJ commented May 11, 2026

Copy link
Copy Markdown
Member

@mneedham

Maybe it's better to pass paths as an array?

@CurtizJ CurtizJ self-assigned this May 11, 2026
mneedham and others added 2 commits May 11, 2026 15:42
…typed path omission

- Change `JSONValues(json, 'p1', 'p2', ...)` to `JSONValues(json, ['p1', 'p2', ...])`
  so the paths are a single constant `Array(String)` argument, consistent with
  how other ClickHouse functions accept array-valued parameters
- Fix typed paths being emitted unconditionally: add `isDefaultAt` check so
  typed paths that were absent in the original JSON (stored as the type default)
  are omitted from the result, consistent with dynamic and shared-data paths
- Update `parseJSONValuesColumnName` in `MergeTreeIndexJSONSubcolumnHelper` to
  parse the new array literal format `JSONValues(col, ['path1', 'path2', ...])`
  instead of the old variadic format `JSONValues(col, 'path1', 'path2', ...)`
- Update test and documentation examples to use array syntax

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…and add regression test

For schema-declared non-nullable typed paths, `ColumnObject` stores the type
default (0 for UInt32, "" for String, false for Bool) for both absent rows and
rows explicitly set to that default value.  There is no null map, so the two
cases are indistinguishable at read time.

To avoid emitting spurious placeholder values for absent paths, both cases are
omitted (via the existing `isDefaultAt` check).  This is now documented in:
- the class-level comment on `FunctionJSONValues`
- the in-code comment on the typed-path branch
- the `FunctionDocumentation` description

A regression test is added that inserts `{"a":0}`, `{"a":1}`, and `{}` into
a `JSON(a UInt32)` column and asserts that `JSONValues(json, ['a'])` returns
`[]`, `['1']`, `[]` respectively — confirming the documented contract.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Update the `tryMatchNodeToJSONValuesIndex` doc comment from the old variadic
form `JSONValues(col, 'path1', 'path2', ...)` to the current array form
`JSONValues(col, ['path1', 'path2', ...])`.

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

Copy link
Copy Markdown
Contributor Author

@mneedham

Maybe it's better to pass paths as an array?

yeh good idea. Have updated

@alexey-milovidov

Copy link
Copy Markdown
Member

This was fixed by #105146. Let's update the branch.

@clickhouse-gh

clickhouse-gh Bot commented May 18, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.20% 84.20% +0.00%
Functions 91.40% 91.40% +0.00%
Branches 76.60% 76.60% +0.00%

Changed lines: 92.44% (220/238) | lost baseline coverage: 3 line(s) · Uncovered code

Full report · Diff report

mneedham and others added 4 commits May 21, 2026 14:20
…h defaults

`JSONValues` omits typed-path default values from the index (via `isDefaultAt`).
When comparing a subcolumn against its type default (e.g. `data.a = 0` for
`JSON(a UInt32)`), `FUNCTION_EQUALS` in `mayBeTrueOnGranule` calls
`hasAllQueryTokensOrEmpty`, which does not find the token `"0"` and incorrectly
skips the granule — a false negative.

The fix splits the `JSONAllValues` and `JSONValues` match paths in
`traverseFunctionNode`. For `JSONValues` with `equals`, it calls
`isJSONPathFilterSafe` (already used by the bloom-filter text index) to detect
when the comparison value equals the typed default. In that case the function
returns `false`, leaving the RPN element as `FUNCTION_UNKNOWN` (always may-be-true).
For non-default values the index is still used normally.

`JSONAllValues` is unaffected: it always indexes typed-path defaults, so no guard
is needed there.

A regression test is added to `04218_json_values` that inserts rows with
`a=0`, `a=1`, and absent `a` into a `JSON(a UInt32)` column with a `JSONValues`
text index (granularity 1) and asserts that `WHERE data.a = 0` returns both
the explicit-zero and absent rows.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
if (rest[0] != '\'')
break;
rest.remove_prefix(1);
auto end = rest.find('\'');

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

parseJSONValuesColumnName splits each array element at the first ' (rest.find('\'')), so it does not handle SQL-escaped quotes inside string literals.

For example, JSONValues(data, ['a''b']) is parsed here as two paths (a and b) instead of one path (a'b). That violates the contract that we match only explicitly listed paths, and can make tryMatchNodeToJSONValuesIndex treat an unlisted subcolumn as indexed, which risks incorrect granule skipping.

Please parse the array literal with proper SQL string escaping (or reuse an existing SQL literal parser) before path matching.

|| hasIndexForMapElementValue(node)
|| tryMatchNodeToJSONIndex(node, header, "JSONAllValues");
|| tryMatchNodeToJSONIndex(node, header, "JSONAllValues")
|| tryMatchNodeToJSONValuesIndex(node, header);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This IN path now treats JSONValues as indexable via has_index, but unlike the equals branch above it never applies isJSONPathFilterSafe.

JSONValues omits typed defaults, so IN against a default value is still unsafe for non-nullable typed paths. A concrete case is JSON(a FixedString(3)) with tokenizer='ngrams': data.a IN (toFixedString('', 3)) can tokenize to non-empty ngrams, while absent/default rows have no corresponding tokens in the JSONValues index, so matching granules can be skipped.

Please add the same default-value safety check for IN/globalIn set elements before enabling JSONValues-based skipping.

@mneedham mneedham closed this May 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants