Skip to content

Add jsonPathValues tokenizer for JSON text indexes - #114613

Open
rorylshanks wants to merge 127 commits into
ClickHouse:masterfrom
rorylshanks:json-path-values-tokenizer
Open

rorylshanks wants to merge 127 commits into
ClickHouse:masterfrom
rorylshanks:json-path-values-tokenizer

Conversation

@rorylshanks

@rorylshanks rorylshanks commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Related: #113376
Related: #110757

I first tried to fix the edge cases between JSONAllValues and the text index. I kept finding more cases where the index could return an incorrect result. I therefore needed to disable more useful index paths to keep queries correct. The main problem is that JSONAllValues stores plain text. It does not retain the path or type of values from Dynamic JSON columns. PR #113376 documents several examples.

A tokenizer made specifically for JSON seemed like a better fit. The new jsonPathValues tokenizer stores the JSON path, type, and value in each token. This gives the index enough information for safe typed comparisons.

+-------------------+-------+---------------------+-------+--------+------------------+
| escaped JSON path | 00 00 | binary-encoded type | 00 00 | 1-byte | payload          |
|                   |       |                     |       | kind   |                  |
+-------------------+-------+---------------------+-------+--------+------------------+

Payload:
  complete value  : | full value                                      |
  truncated value : | value prefix | SipHash-2-4 (8 bytes, LE)        |
  map entry       : | escaped key | 00 00 | complete/truncated value  |
  validation      : | empty                                           |

Kinds: 1/2 = scalar, 3/4 = array element, 5/6 = map entry
       (complete/truncated), 7 = dynamic validation

Escaping: 00 -> 00 01    Component terminator: 00 00

The path-value format also enables direct reads. This part was inspired by ClickStack's use of text-index direct reads for dynamic map attributes.

jsonPathValues brings this model directly to JSON columns. It does not require user-defined alias columns or query rewrites. Long values use a bounded prefix and a hash. ClickHouse validates candidate rows when a token is truncated or a runtime type is unsafe. This prevents false-negative results.

The tokenizer supports declared and dynamic paths, arrays, scalar leaves in Array(JSON), and declared Map(String, String) paths. It supports equality, IN on declared String subcolumns, has, map lookups, prefix and suffix searches, LIKE, ILIKE, regular expressions, and multi-search functions.

Named include_paths, include_paths_regexp, skip_paths, and skip_paths_regexp arguments can restrict indexing to useful JSON paths; named max_token_bytes is also supported. Every part stores its own tokenizer configuration, so parts built with different filters are evaluated independently and incompatible parts fall back to source-row reads. Structural [] from Array(JSON) is distinct from escaped literal square brackets in a JSON path.\n\nstartsWith uses an ordered dictionary lookup, so it does not require a full dictionary scan. Substring searches still scan the dictionary.

Benchmark

We tested jsonPathValues(1024) with 99,999,984 distinct events from 100 JSONBench files. Both target tables had the same 192-part layout. Each indexed query returned the same result as the query without an index.

Metric No index jsonPathValues(1024)
Build time 214 s 863 s
Total storage 9.29 GiB 23.48 GiB
Exact cid lookup 1,926 ms 13 ms
Exact long-value lookup 637 ms 8 ms
startsWith 29 ms 16 ms
Substring LIKE 145 ms 93 ms

The index used 14.19 GiB, or approximately 152 bytes per JSON object. It made the table 2.53 times larger and made index construction 4.03 times slower.

The exact lookups were 80 to 148 times faster. startsWith was 1.81 times faster. Query times are medians from ten warm runs.

The jsonPathValues tokenizer is experimental: creating a text index with it requires the MergeTree setting allow_experimental_text_index_json_path_values = 1.

Changelog category (leave one):

  • New Feature

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

Add the jsonPathValues tokenizer for bounded, type-safe, selectively filtered text indexes on JSON paths, arrays, and maps.


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

Correctness:
- Evaluate `FUNCTION_EQUALS` text search queries with their own fold mode in
  `mayBeTrueOnGranule`: an Any-mode query (e.g. float 0/-0 equality) folds
  postings by union, and intersecting a partially-read union as All-mode
  could prune granules whose matching token postings were not read yet.
- Do not build exact-match tokens from FixedString values: their zero
  padding participates in zero-pad-aware string comparison but not in the
  tokens a String or Dynamic path stores. Declared FixedString paths keep
  using the index since both sides pad consistently.

Performance:
- Check whether any (possibly wrapped) IN argument is covered by the index
  before materializing the subquery set in `tryPrepareSetForTextSearch`.
- Resolve each shared-data value's type name once in `enumerateJSONValues`
  and reuse the per-path discriminator cache in both traversal orders.
- Precompute pattern prefix ranges in `TextIndexAnalyzer` instead of
  rebuilding prefix-end strings per dictionary block in
  `mayMatchPatternsInRange`.

Cleanup:
- Deduplicate the `toString`/`ifNull`/`coalesce`/`nullIf` wrapper-unwrapping
  loop (three divergent copies) into `tryUnwrapIndexArgument`.
- Define the order-preserving zero-byte escaping in a single helper
  `appendEscapedComponentBounded` used by all token encoders.
- Fold the lazy-mode range derivation in `readRows` into
  `buildPostingsForMark`.
- Remove the never-populated `JSONTextQueryPayload` fields
  `pattern_token_excluded_prefixes`, `pattern_token_kinds`, and
  `validation_pattern_kinds` together with their sorting, hashing, and
  matching logic, and the now test-only `tryGetKind`.
…20260825

# Conflicts:
#	src/Interpreters/ITokenizer.cpp
#	src/Interpreters/ITokenizer.h
#	src/Processors/QueryPlan/Optimizations/optimizeDirectReadFromTextIndex.cpp
#	src/Storages/MergeTree/MergeTreeIndexJSONSubcolumnHelper.cpp
#	tests/queries/0_stateless/02346_system_tokenizers.reference
@george-larionov george-larionov added the can be tested Allows running workflows for external contributors label Aug 25, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5d27497]

Summary: ❌

job_name test_name status info comment
Fast test FAIL
Build ClickHouse FAIL
Build (arm_tidy, 1/4) FAIL
Build ClickHouse FAIL cidb
Code Review DROPPED
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_asan_ubsan) DROPPED

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Aug 25, 2026
…3-20260825

# Conflicts:
#	src/Storages/MergeTree/MergeTreeIndexText.cpp
Use memory-tracking containers for tokenizer state, declare `TOO_LARGE_STRING_SIZE`, and sequence component parsing for `clang-tidy`.
Disable `query_plan_optimize_count_from_text_index` only where tests assert the virtual-column direct-read plan.
Give `FunctionsMultiStringSearch` a fixed return type under the default `Dynamic` adaptor, then normalize raw dynamic JSON haystacks to `String` for multi-needle text-index analysis.
Comment thread src/Interpreters/convertFieldToType.cpp Resolved
Initialize analyzer-visible state, use the preferred string-view API, and make strict field conversion compare the complete type tree.

ClickHouse#114613
Read and discard a partial-mark prefix before continuing with fallback columns after the upstream removal of the offset parameter.

ClickHouse#114613
rorylshanks and others added 2 commits September 27, 2026 16:27
…actor::preparePath`

The `jsonPathValues` tokenizer of a text index looked up every path of every row in a hash map, although with a few include paths almost none of them are visited. With only literal include paths, a path is visited only if it starts with an include path or an include path starts with it, which is cheaper to check. The index does not change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Functions/hasAnyAllTokens.cpp Resolved
rorylshanks and others added 6 commits October 8, 2026 11:02
…tokenizer

Port the `jsonPathValues` text index onto the refactored text index reader:
one map of postings streams, `range_posting` kept local to `buildPostingsForMark`,
`fillColumnLazy` without the range posting, and the fallback reader called with
`current_range_last_mark`. Keep the lossless-conversion unwrapping and the
`JSON` index argument types from master next to the `jsonPathValues` matching.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nctions

`IN` uses a `jsonPathValues` index only for `String`/`FixedString` paths,
paths inside a typed non-`JSON` ancestor are not indexed, and
`hasAnyTokens`/`hasAllTokens` do not use a `jsonPathValues` index.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…`createRegexp` with `similar_to`

Master replaced `IDataType::forEachChild` with `getChildren` and the walkers in `DataTypes/TypeTree.h`, and added the `similar_to` parameter to `Regexps::createRegexp`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… `jsonPathValues` checks

Master removed `MergeTreeIndexReader::patchSettings`, and `makeTextIndexInputStream` now takes the substream and applies its settings itself.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tokenizer

# Conflicts:
#	docs/reference/engines/table-engines/mergetree-family/textindexes.mdx
#	src/Core/Settings.cpp
#	src/Functions/hasAnyAllTokens.cpp
#	src/Interpreters/convertFieldToType.cpp
#	src/Processors/QueryPlan/Optimizations/optimizeDirectReadFromTextIndex.cpp
#	src/Storages/MergeTree/MergeTreeIndexConditionText.cpp
#	src/Storages/MergeTree/MergeTreeIndexText.cpp
rorylshanks and others added 2 commits November 3, 2026 22:23
…tokenizer

Conflicts:
- `textindexes.mdx`: kept master's rewritten posting list codec upgrade notes and the `jsonPathValues` serialization note.
- `Settings.cpp`: kept master's link to `use_text_index_like_evaluation_by_dictionary_scan` in the `jsonPathValues` wording.
- `MergeTreeIndexConditionText.h`/`.cpp`: kept both `JSONTextQueryPayload` and master's `TextIndexAutomatonBudget`; the `TextSearchQuery` constructor takes both, and JSON queries build no dictionary automata because their patterns match decoded values, not raw tokens.
- `TextIndexAnalyzer.h`/`.cpp`: kept `queries_by_prefix` next to master's `pattern_cursors`; JSON queries disable dictionary DFA intersection so that prefix and decoded-value lookups are never skipped by a seek.
- `MergeTreeIndexText.cpp`: pass `IndexDescription` (PR) together with master's `getMapSubcolumnShadowingCheck` and `automaton_budget`.
- `MergeTreeReaderTextIndex.cpp`: kept both the JSON dynamic validation branch and master's phrase fallback branch.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01E5v7QTSR65LdYnQEv9HJVu
@mintlify

mintlify Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit 5d27497.

Approve preview

@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Nov 3, 2026
rorylshanks and others added 5 commits November 4, 2026 00:14
The merge commit 1ebcf77 recorded the submodule pointers of the
branch from before the merge for 32 submodules (`llvm-project`, `boost`,
`aws`, `grpc`, ...), so the PR diff reverted their updates on `master`.
Set them back to the commits of the merged `master` (0a399a7).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01E5v7QTSR65LdYnQEv9HJVu
…n they need validation

`getFoldedPostings`, added on `master` by ClickHouse#122896, fills a virtual column
from the postings folded during index analysis. It did not know two
properties of `jsonPathValues` queries:

- A prefix lookup (`startsWith`, `LIKE 'abc%'`, key existence) has
  neither tokens nor patterns: its tokens are collected from the
  dictionary by `pattern_token_prefixes`. Such a query was answered with
  empty postings, so it matched no row.
- A query with dynamic fallback (e.g. `endsWith` over truncated values)
  has folded postings that also hold the candidate rows that still have
  to be validated on the column. They were taken as the result, so
  unvalidated rows matched.

Check `hasPatternLookup` as `classifyVirtualColumns` and
`buildPostingsForMark` already do, and do not use folded postings for
columns with dynamic fallback. Fixes the `Fast test` failures of
`04839_json_path_values_core`, `04840_json_path_values_dynamic`,
`04841_json_path_values_patterns`, `04842_json_path_values_collections`,
`04856_json_path_values_subcolumns` and
`04866_json_path_values_regressions`.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=114613&sha=df313397ce1ec1fa96b1c82f0ad3e87768aed83b&name_0=PR&name_1=Fast%20test
ClickHouse#114613

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01E5v7QTSR65LdYnQEv9HJVu
`IMergeTreeReader::readRows` takes a `shared_columns` argument since
ClickHouse#124449: a column served from
the columns cache comes back there instead of in `res_columns`. The per-mark
reads of the `jsonPathValues` dynamic fallback in `MergeTreeReaderTextIndex`
still used the old signature, so the build failed after merging `master`.
Pass the shared columns and take a column from them when the reader did not
fill the mutable one, as the whole-range fallback read above already does.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=114613&sha=e6b2c2eaa9444798c6f6f290531d55938446fd86&name_0=PR&name_1=Build%20(arm_tidy%2C%203%2F4)
PR: ClickHouse#114613

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01E5v7QTSR65LdYnQEv9HJVu
…ions

ClickHouse#122144 replaced the set of
column names shadowing Map key subcolumns with the `IsShadowingColumn`
callback `is_column_shadowing_map_subcolumn`, so `tryMatchJSONPathValuesNode`
no longer compiled after merging `master`.

The callback answers for any column or regular subcolumn of the table, while
the set held only names shaped like `<map>.key_<k>`. Asking it about every
predicate node would refuse typed JSON paths such as `j.a`, so restore
`looksLikeMapSubcolumnName` (removed from `master` as unused) and ask the
callback only about names of that shape, as `tryParseMapSubcolumnName` does.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=114613&sha=e6b2c2eaa9444798c6f6f290531d55938446fd86&name_0=PR&name_1=Fast%20test
PR: ClickHouse#114613

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01E5v7QTSR65LdYnQEv9HJVu
rorylshanks and others added 6 commits November 4, 2026 20:38
The dictionary scan matches tokens with a caseless `OptimizedRegularExpression`,
which folds ASCII case only, while `ilike` folds the whole of UTF-8. A row with
`Äpfel` was lost for `ILIKE '%äpf%'` and `ILIKE 'äpf%'`. Apply the same guard
as `stringLikeToPatterns` and leave such patterns to the predicate.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01E5v7QTSR65LdYnQEv9HJVu
`IDataType::equals` treats `UInt8` and `Bool` as equal, so `CAST(data.u, 'Bool')`
over `LowCardinality(UInt8)` was treated as transparent and `= true` looked up only
the stored value `1`, losing rows with `2`. Require the same type name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01E5v7QTSR65LdYnQEv9HJVu
The token of a `Variant` value holds only its text, so the numeric `42` and the
string `'42'` give the same token, and an empty string element gives none. Exact
reads of `has` over `Array(Variant(...))` returned rows of the wrong alternative
and lost rows with empty strings. Treat `Variant` as having no stable
serialization, which declines scalar equality and `has` over such paths.

The fallback expression of an exact direct read rebuilt constants as
`CAST(<Field>, '<type>')`. A `Field` does not keep the alternative of a `Variant`
or the type of a `Dynamic` value, so `CAST(42, 'Variant(String, UInt64)')` threw
`CANNOT_CONVERT_TYPE`. Skip the direct read when such a constant is involved.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01E5v7QTSR65LdYnQEv9HJVu
Compares results with and without the index for non-ASCII `ilike`, `CAST` to
`Bool`, `Variant` constants, and `has` over `Array(Variant(...))`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01E5v7QTSR65LdYnQEv9HJVu
…he weight

Each cached header keeps its own source type name, path filters and compiled
regexps, but `TextIndexHeaderWeightFunction` charged only the sparse index.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01E5v7QTSR65LdYnQEv9HJVu
…tting

The `jsonPathValues` tokenizer introduces a new persisted token encoding and
text index header version together with exact reads, so creating such an index
now requires the MergeTree setting `allow_experimental_text_index_json_path_values`,
like `support_phrase_search` requires `allow_experimental_text_index_phrase_search`.
The check is skipped on attach so that existing tables still load.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01E5v7QTSR65LdYnQEv9HJVu

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-text-index Full-text search: inverted/text index in MergeTree (tokenizers, posting lists, GIN-style index bu... external Author is not a member of the ClickHouse organization manual approve Manual approve required to run CI pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants