Skip to content

Add keyValuePairs text-index tokenizer for Map columns - #110757

Closed
UnamedRus wants to merge 47 commits into
ClickHouse:masterfrom
UnamedRus:feature/map-kv-tokenizer
Closed

UnamedRus wants to merge 47 commits into
ClickHouse:masterfrom
UnamedRus:feature/map-kv-tokenizer

Conversation

@UnamedRus

@UnamedRus UnamedRus commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Resolves #110454

keyValuePairs tokenizer, stored as key+value+reverse(varint_len(key)), which allows to keep good sorting of tokens in dictionary and reliable detect "border" between key and value

Changelog category (leave one):

  • New Feature

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

New tokenizer keyValuePairs enables native text-index support for Map(String, String), with exact direct-read support for m['k'] = 'v', mapContains* functions family, m['k'] LIKE ..., startsWith, and endsWith, plus index-based granule pruning for m['k'] IN ('v', 'v2').
Added two new map functions: mapContainsKeyValue and mapContainsKeyValueLike.


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

@UnamedRus
UnamedRus force-pushed the feature/map-kv-tokenizer branch from 1759e67 to a5e9fe5 Compare July 16, 2026 23:16
Introduce a `keyValuePairs` tokenizer that packs each map (key, value) pair into
a single text-index token `key || value || revvarint(len(key))`, storing the key
length in a reverse-decodable trailer. Unlike concatenating with a separator
(`key=value`), the encoding is unambiguous: a key or value containing the
separator character cannot cause a false match.

Works on a `Map` column with `String` or `LowCardinality(String)` keys and values.
It lets the text index answer map searches directly, with exact direct read (the
map column is not read):
- exact element equality: `m['k'] = 'v'`
- value search across keys: `mapContainsValue`, `mapContainsValueLike` (including substrings)
- element value prefix/suffix/LIKE: `m['k'] LIKE ...`, `startsWith`, `endsWith`
- key search: `mapContainsKey`, `mapContainsKeyLike`

Value and key searches are resolved by a decode-aware dictionary scan
(`TokenValueMatcher`) that reuses the existing text-index scan and reader
lifecycle. Because each token is decoded and matched exactly, posting-list
membership is both necessary and sufficient, so the predicate is dropped (exact
direct read) and only recomputed as a fallback if the dictionary scan is
truncated by the posting-read budget.

Map-element predicates that are satisfied by the empty string (e.g. `m['k'] = ''`,
`m['k'] LIKE '%'`) are answered by a full scan, because `m['absent']` yields the
map's default value `''` for rows that have no token.

Closes: ClickHouse#110454

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@UnamedRus
UnamedRus force-pushed the feature/map-kv-tokenizer branch from a5e9fe5 to 18b92fe Compare July 16, 2026 23:38
@CurtizJ CurtizJ added the can be tested Allows running workflows for external contributors label Jul 17, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8240497]

Summary: ❌

job_name test_name status info comment
Docs check (Mintlify) FAIL
Check internal links and anchors FAIL cidb
Integration tests (amd_tsan, 3/6) FAIL
test_refreshable_mv_no_multi_read/test.py::test_refreshable_mv_unavailable_view_refuses_replicated_start FAIL cidb

AI Review

Summary

This PR adds the keyValuePairs text-index tokenizer for Map columns, wires direct-read rewrites for m['key'] = value, m['key'] IN (...), LIKE / prefix / suffix predicates, and mapContains*, and introduces mapContainsKeyValue plus mapContainsKeyValueLike. Current head fixes the earlier correctness bugs around FixedString, value-matcher clipping, subcolumn key deserialization, and the m['key'] IN (...) fallback, but I still see one live coverage gap, two user-facing documentation-contract mismatches, and two performance concerns in the encoding/build path.

Findings

⚠️ Majors

  • [docs/reference/engines/table-engines/mergetree-family/textindexes.mdx:1022] The docs claim that the trailer "keeps the dictionary sorted by key and then by value", but the key || value || trailer layout does not preserve an exact-key prefix order when one key is a prefix of another. A concrete counterexample is encode("a", ""), which sorts after encode("a\x01", ""), so exact-key tokens are interleaved with longer keys sharing the prefix. Key-only searches therefore still go through a full dictionary scan in analyzeDictionaryForPatterns, so the docs currently promise stronger ordering/selectivity than the implementation provides.
  • [src/Storages/MergeTree/MergeTreeIndexText.cpp:1790] The duplicate-key is_rest marking is quadratic in row width: each map entry linearly scans all previously seen keys in the row. Wide maps / JSON-like attribute bags will make keyValuePairs materialization much slower than the existing mapKeys / mapValues O(n) build path.

💡 Nits

  • [src/Functions/array/FunctionsMapMiscellaneous.cpp:1310-1318] The structured docs for mapContainsKeyValueLike are still narrower than MapKeyValueLikeAdapter::checkTypes: the public metadata publishes only const String patterns and omits the accepted LowCardinality(...) wrappers, so the generated function reference will describe supported calls as invalid.
  • [docs/reference/engines/table-engines/mergetree-family/textindexes.mdx:82,120,177,549] The top-level tokenizer = ... grammar still omits keyValuePairs, and the supported-type wording around the tokenizer is inconsistent with validateTextIndexColumnType, which removes LowCardinality independently from key and value. Users copying the syntax block or reading only the support note can infer that supported DDL is invalid.
Tests
  • ⚠️ Add a focused direct-read regression for m['key'] IN (...) with optimize_functions_to_subcolumns = 1. 04546_map_element_duplicate_keys_first_match.sql now makes subcolumn and arrayElement semantics agree, and the new fallback in optimizeDirectReadFromTextIndex is specifically meant to cover the analyzed m.key_<...> form, but the current PR only asserts exact direct read for optimize_functions_to_subcolumns = 0.
Final Verdict

Needs follow-up before merge: the current head looks much better on correctness, but the docs still promise stronger behavior than the implementation, the new subcolumn direct-read path lacks focused coverage, and the remaining key-ordering / O(n^2) build costs should be explicitly addressed or documented.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.80% 86.80% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.20% 79.20% +0.00%

Changed lines: Changed C/C++ lines covered: 605/677 (89.36%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Jul 17, 2026
UnamedRus and others added 2 commits July 17, 2026 15:20
Adding the `key_pattern` field to `TokenValueMatcher` broke the build
under `-Werror` because the subset designated-initializers in
`MergeTreeIndexConditionText.cpp` no longer listed every field, tripping
clang's `-Wmissing-designated-field-initializers`. Give all fields
default member initializers; clang suppresses the warning for members
that have one.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
UnamedRus and others added 2 commits July 17, 2026 16:32
`tryGetMapElementKeyForKeyValueIndex` returns `std::optional<String>` and
the `key` field of `TokenValueMatcher` is also `std::optional<String>`, so
`.key = std::move(*key)` dereferenced and re-wrapped the optional, which
clang-tidy flags as `bugprone-optional-value-conversion`. Move the whole
optional instead.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110757&sha=ee2740cc2f79a4dc10202629da0764cb0a8dae34&name_0=PR&name_1=Build%20%28arm_tidy%29
PR: ClickHouse#110757

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The `keyValuePairs` tokenizer builds its tokens from the decoded
`(key, value)` pairs of a `Map` column in the `isMap` branch of
`MergeTreeIndexAggregatorText::update`, so it has no String
tokenization step for `preprocessor` / `postprocessor` to hook into.

Previously both options were silently accepted and then failed at
materialization: a `preprocessor` (e.g. `toString(m)`) passes the
loose result-type check but makes `update` `assert_cast` the
non-`Map` result to `ColumnMap`, and any `postprocessor` feeds the
`ColumnMap` into `tokenizeToArray`, reaching `ColumnMap::getDataAt`
which throws `NOT_IMPLEMENTED`.

Reject both options for `keyValuePairs` in `textIndexValidator` with a
clear `BAD_ARGUMENTS` message until pairwise transformation semantics
(including the mirrored query-side constant transform) are designed
end-to-end. Add negative tests to `04326_map_kv_tokenizer`.

PR: ClickHouse#110757

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
UnamedRus and others added 2 commits July 17, 2026 18:05
…ng, tidy

Three fixes for the `keyValuePairs` text-index tokenizer, addressing the
`arm_tidy` build failure and two review findings on PR ClickHouse#110757:

1. Fix a false negative in `TextIndexAnalyzer::QueryBuilder::addMissingToken`.
   Value-matcher queries (e.g. `mapContainsValue`) discover their tokens
   dynamically and start with no declared tokens, exactly like pattern
   queries. The `Any`-mode pure-token failure path only checked
   `getPatterns().empty()`, so once PK or an earlier skip index narrowed the
   readable rows and clipped a discovered matcher token, the whole query was
   marked failed before the rest of the dictionary was scanned. This wrongly
   pruned all granules. Exempt value-matcher queries too, so their
   contribution is tracked through readable postings.

2. Reject `FixedString` keys/values for the `keyValuePairs` tokenizer in
   `validateTextIndexColumnType`. The query-side fast path receives the
   unpadded key (e.g. `"a"`) while `MergeTreeIndexAggregatorText::update`
   indexes the padded `ColumnFixedString` bytes (e.g. `"a\0\0"` for
   `FixedString(3)`), so lookups would silently miss rows. Only `String`
   (optionally `LowCardinality`) is supported; the error message already
   documented this.

3. Fix `performance-for-range-copy` in `gtest_map_key_value_token`: iterate
   the pair vector by const reference.

Add regression tests to `04326_map_kv_tokenizer`: the value-matcher clipping
case (verified to return an empty result before fix 1 and the correct row
after) and the two `FixedString` rejections.

PR: ClickHouse#110757

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
ASan reported a `stack-buffer-overflow` in
`StringHashTable::dispatch<...PostingListBuilder...>` while building a
`keyValuePairs` text index, which crashed the server and cascaded into
`ATTEMPT_TO_READ_AFTER_EOF` / connection-refused failures across every
other text-index test in the stateless suite.

`MergeTreeIndexTextGranuleBuilder::addToken` inserts each token into the
dictionary via `ArenaKeyHolder`. `StringHashTable::dispatch` reads a full
8-byte machine word around the key from its *source* memory (the view
returned by `keyHolderGetKey`), before `keyHolderPersistKey` copies it
into the arena. For the normal path the source is a view into padded
`ColumnString` memory, so the wide read is in bounds. The `keyValuePairs`
build path, however, encoded each token into a local `String`
(`encodeMapKeyValueToken`) and passed it straight to `addDocument`, so
the token views pointed at a transient (often SSO/stack) buffer and the
wide read ran off the end — undefined behaviour that ASan flags as a
stack-buffer-overflow.

Add `MergeTreeIndexTextGranuleBuilder::addTransientDocument`, which copies
the document into the arena (the same padded storage all keys are
persisted to) before tokenizing, and use it for the `Map` branch of
`MergeTreeIndexAggregatorText::update`. The dictionary keys are now always
read from arena memory that tolerates the wide dispatch reads.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110757&sha=143b181f1afd8352de42526069f572a31bbcd9a0&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20targeted%29
PR: ClickHouse#110757

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
UnamedRus and others added 4 commits July 20, 2026 14:40
…ring

ASan reported a `heap-buffer-overflow` in
`StringHashTable::dispatch<...PostingListBuilder...>` while building a
`keyValuePairs` text index, crashing the server and cascading into
failures across every other text-index test in the stateless suite.

The previous fix (`addTransientDocument`) persisted the encoded token into
the `Arena` before tokenizing. That cured the forward (right-side) over-read
but not the backward one: `StringHashTable::dispatch` reads a full 8-byte
machine word around each key, and its second-half-page branch reads the word
*ending* at the key end (`x.data() + x.size() - 8`). For a token shorter than
8 bytes that starts before the key, and `Arena` pads only on the right
(`pad_right`), so a short encoded token (e.g. `encodeMapKeyValueToken("a", "b")`
is 3 bytes) under-reads before its `Arena` allocation.

Encode each `(key, value)` pair into a `ColumnString` and index the tokens from
there, mirroring the plain-`String` and `Array` paths. `ColumnString`'s
`PaddedPODArray` pads on both sides (`pad_left` and `pad_right`), so the wide
dispatch reads stay in bounds. This also gives each map entry its own token
position (`0, 1, 2, ...`) like the `Array` path, instead of collapsing every
entry in a row to position `0`.

Remove the now-unused `addTransientDocument`.

CI report: ClickHouse#110757 (comment)
Related: ClickHouse#110757

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The `mapContainsValue` direct-read assertion checks that a `__text_index_`
virtual column appears in the plan, but the flaky check randomizes
`query_plan_direct_read_from_text_index`. With it off the virtual column is
not emitted, so `count() > 0` returns `0` and the test diffs. Pin
`query_plan_direct_read_from_text_index = 1` on that query so the plan-shape
assertion is independent of the randomized session setting; the row-result
queries are unaffected because the index only prunes granules.

CI report: ClickHouse#110757 (comment)
Related: ClickHouse#110757

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Under ParallelReplicas the `EXPLAIN indexes = 1` output prints the index node
with a box-drawing prefix (`│         Name: idx`), which `trimLeft` does not
strip (it removes leading whitespace, not the `│`), so the three
`Name: idx` assertions diffed against the reference.

Use `extract(explain, 'Name: idx')` instead of `trimLeft(explain)`: it returns
`Name: idx` regardless of any leading indentation or tree-drawing characters,
so the assertion no longer depends on the plan's rendering.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110757&sha=latest&name_0=PR&name_1=Stateless+tests+%28amd_llvm_coverage%2C+ParallelReplicas%2C+s3+storage%2C+parallel%29
Related: ClickHouse#110757

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The new `keyValuePairs` section described indexing a `Map` column directly,
but the earlier per-function sections still told users the index is used only
when built on `mapKeys` / `mapValues`, advertised preprocessor / postprocessor
support for the `mapContains*` functions, and omitted the tokenizer's
direct-read behaviour — giving contradictory guidance across the page.

- Note in the function-support matrix that `keyValuePairs` rejects a
  preprocessor and postprocessor, and operates on the `Map` column directly.
- Update the `mapContainsKey`, `mapContainsValue`, and `operator[]` sections to
  mention the `keyValuePairs` tokenizer alongside `mapKeys` / `mapValues`.
- Add `keyValuePairs` to the direct-read supported-functions list.
- State the preprocessor / postprocessor rejection in the `keyValuePairs`
  section itself.

Related: ClickHouse#110757

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
UnamedRus and others added 2 commits July 20, 2026 21:34
Resolve conflicts with `9e073117ac0` ("Optimize per-mark analysis of text
index"), which moved the per-mark granule checks from `MergeTreeIndexGranuleText`
into free functions in `MergeTreeIndexConditionText` and cached the per-column
`search_queries` in `MergeTreeReaderTextIndex`:

- `MergeTreeIndexText.cpp` / `.h`: take master's removal of the granule
  `hasAnyQueryTokens` / `hasAllQueryTokensOrEmpty` methods; the keyValuePairs
  value-matcher additions they carried are ported to master's new location.
- `MergeTreeIndexConditionText.cpp`: extend the moved bypass checks
  (`queryMayBeTrueInRange`, `hasAnyPatternsInRange`) to treat a non-empty
  `getValueMatchers()` like a non-empty `getPatterns()`, preserving the
  keyValuePairs value-matcher behaviour.
- `MergeTreeReaderTextIndex.cpp`: keep master's cached `search_queries[i]` and
  add the `getValueMatchers().empty()` clause the PR needs.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`mapContainsValueLike`, `mapContainsKeyLike`, and `m['key'] LIKE ...` on a
`keyValuePairs` text index built their value matchers from a raw LIKE regex
unconditionally, bypassing the dictionary-scan contract the non-map LIKE path
enforces. As a result they scanned the index dictionary even with
`use_text_index_like_evaluation_by_dictionary_scan = 0`, and ignored
`text_index_like_min_pattern_length` for short needles (e.g. `%ab%`).

Route the three LIKE rewrites through the same gate as the non-map LIKE path:
only build the matcher when `use_text_index_like_evaluation_by_dictionary_scan`
is set and `stringLikeToPatterns` returns a single `%token%` pattern (which
also enforces `text_index_like_min_pattern_length`); otherwise bail to a
full scan. The matcher now reuses that normalized pattern. Exact lookups
(`m['key'] = 'value'`, `mapContainsValue`, `mapContainsKey`) are precise and
stay eligible regardless of the setting.

Add `04613_map_kv_tokenizer_like_gate` covering the settings contract: results
are identical with the dictionary scan on and off, and the `__text_index_`
direct-read column appears only when the scan is enabled and the needle is at
least `text_index_like_min_pattern_length` long.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Interpreters/MapKeyValueToken.cpp Resolved
@rschu1ze

Copy link
Copy Markdown
Member

Allow me to set @Ergus as assignee, who is adding tokenizers at the moment anyways.

…n settings

The previous gate restricted the keyValuePairs `mapContainsValueLike`,
`mapContainsKeyLike`, and `m['key'] LIKE ...` rewrites to the `%token%` substring
form (via `stringLikeToPatterns`), so prefix (`v%`), suffix (`%v`), and
wildcard-free LIKEs fell back to a full scan — narrower than the acceleration the
docs and tests describe.

Match the decoded key/value against the full LIKE pattern regex again, so any
shape (prefix, suffix, substring, literal, or complex) is answered from the index.
Keep the settings contract: the rewrite is used only when
`use_text_index_like_evaluation_by_dictionary_scan` is enabled and the pattern's
longest literal run is at least `text_index_like_min_pattern_length` (new helper
`likePatternMaxLiteralRun`); otherwise it bails to a full scan. Exact
`m['key'] = 'value'`, `mapContainsValue`, and `mapContainsKey` stay precise and
always eligible.

Extend `04613_map_kv_tokenizer_like_gate` to cover prefix/literal/substring shapes
plus the setting-off and short-literal fallbacks.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Interpreters/MapKeyValueToken.cpp Resolved
…ains functions

Duplicate keys in a `Map` are unspecified, but a text index must not change query
results versus a plain scan. Previously the keyValuePairs index answered
`m['key'] = value` by pair existence, so for a map with a repeated key it could
return rows a plain scan (first-value `arrayElement`) does not.

Encode a per-key occurrence flag into the token trailer: it now stores
`(key.size() << 1) | is_rest`, where `is_rest` is 0 for the first occurrence of a
key within a row and 1 for later ones. The varint codec is unchanged; the flag
rides in the LSB, so keys shorter than 64 bytes still use a single trailer byte.
`m['key']` predicates now pin the first occurrence (`is_rest = 0`), matching a
plain scan; the `mapContains*` existence forms ignore the flag.

Add `mapContainsKeyValue(map, key, value)` and
`mapContainsKeyValueLike(map, key_pattern, value_pattern)` — pair-existence
predicates (match any occurrence) that the keyValuePairs index answers exactly
(a two-token union for the exact form, a decode scan for the LIKE form).

Also:
- Reuse one buffer in `encodeMapKeyValueToken` on the index-build hot path instead
  of allocating a `String` per pair.
- Docs: integrate the keyValuePairs description into the `Indexing Map columns`
  section, update the supported-column-types list and the function-support matrix,
  and document the token format.
- Tests: cover duplicate keys (`04614`), long keys that hit the multi-byte trailer
  (`04615`), and the pair-contains functions (`04616`); update `04326` for the new
  trailer bytes.

Related: ClickHouse#110757

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@Ergus
Ergus requested a review from a team as a code owner July 31, 2026 15:42
@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.80% +0.10%

Changed lines: Changed C/C++ lines covered: 600/676 (88.76%) · Uncovered code

Full report · Diff report

UnamedRus and others added 2 commits August 3, 2026 13:39
- mapContainsKeyValueLike doc: keys/values may be String or FixedString
  (matches checkTypes, which accepts isStringOrFixedString), drop stale
  LowCardinality-only wording.
- Trim over-detailed comments in MapKeyValueToken.h and MergeTreeIndexText.cpp
  per review.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…nizer

# Conflicts:
#	docs/en/engines/table-engines/mergetree-family/textindexes.md
#	src/Interpreters/ITokenizer.h
#	tests/queries/0_stateless/02346_system_tokenizers.reference
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Aug 4, 2026

@Ergus Ergus left a comment

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.

As a suggestion:

In order to avoid delaying too much the CI, is it possible to groups some of the tests is less files?

Not all because there is a walltime ot 180 seconds per test, but so many fine grained tests could take longer to execute.

/// `startsWith(m['key'], prefix)` / `endsWith(m['key'], suffix)`: key-scoped value
/// prefix/suffix search. `m['key'] LIKE 'p%'` is rewritten to `startsWith` by the optimizer.
else if (function_name == "startsWith" || function_name == "endsWith")
{

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.

The startsWith/endsWith rewrite skips both the use_text_index_like_evaluation_by_dictionary_scan opt-in and text_index_like_min_pattern_length, so In this case I think that m['k'] LIKE 'pre%' will force a full dictionary scan under default settings.

Is this intended? Or I am missing something here?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

so In this case I think that m['k'] LIKE 'pre%' will force a full dictionary scan under default settings.

Is this intended? Or I am missing something here?

Yes.
I think Map is special type of data being indexed, and it's token dict size will be much more modest compared to arbitrary text.

m['k'] LIKE 'pre%

Technically, this is at least 4 bytes (key + value prefix) for dict scan, (well, even 5, if we include LEB trailer)

/// prefix/suffix search. `m['key'] LIKE 'p%'` is rewritten to `startsWith` by the optimizer.
else if (function_name == "startsWith" || function_name == "endsWith")
{
if (auto key = tryGetMapElementKeyForKeyValueIndex(index_column_node))

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.

IIUC the previous comment is reachable on the default path, not just when the user writes startsWith by hand.

{
const std::string_view key_view = keys.getDataAt(j);
bool is_rest = false;
for (const auto & prev_key : row_keys)

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.

IIUC this first-occurrence detection is a linear scan over row_keys, making index build O(entries^2) per row. That could very strongly impact performance of index construction right?

Comment thread src/Interpreters/MapKeyValueToken.cpp Resolved
///
/// Key first so tokens sort by key then value (key-prefix scans like `mapContainsKey` work). The key
/// length sits in the trailer, so the leading bytes stay exactly `key ‖ value`; the varint is reversed
/// so decoding scans backward from the end. Length-delimited, so values may hold arbitrary bytes.

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.

I have a question here. I don't see that this implementation exploits the commented "key-first ordering". What I am missing?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Plan was, that token dictionary encoding/compression/machinery(dictionary like scan and etc) around it is smart enough to exploit that we sort data in better way.

UnamedRus and others added 3 commits August 17, 2026 16:02
Review fixes:
- `MergeTreeIndexConditionText`: remove the dead `keyValuePairs` branch in
  `getDirectReadMode`. It was computed but never read - the `keyValuePairs`
  rewrites set their `TextSearchQuery` direct-read mode explicitly (always
  `Exact`, as each constructed query is precise), and the computed value only
  feeds the generic `mapKeys`/`mapValues` fall-through builders a
  `keyValuePairs` index never reaches. Added clarifying comments.
- Gate the `m['key'] LIKE` / `startsWith` / `endsWith` dictionary-scan rewrites
  behind `use_text_index_like_evaluation_by_dictionary_scan` and
  `text_index_like_min_pattern_length`, like the other LIKE forms. The key is a
  fully specified prefix of every matched token (`key || value || trailer`), so
  the selectivity bound is `len(key) + len(prefix/suffix)`, not the value alone.
- `MapKeyValueToken`: reserve the exact token size (trailer width via
  `getLengthOfVarUInt`) instead of `+ 1`, which under-reserved a multi-byte
  trailer.
- `FunctionsMapMiscellaneous`: `mapContainsKeyValue` and
  `mapContainsKeyValueLike` are introduced in 26.8, not 25.8.

Tests reorganized into fewer, categorized files (contiguous 04726-04730):
- `04726_map_kv_tokenizer_basic`: static single-predicate feature completeness.
- `04727_map_kv_tokenizer_compound`: static AND/OR/NOT combinations, index result
  equals a brute-force scan.
- `04728_map_kv_tokenizer_bugfixes`: regression tests for bugs found in
  development.
- `04729_map_kv_tokenizer_random_consistency` / `04730_..._random_compound`:
  the two randomized `.sh` checks (renamed from 04617/04620).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…nizer

# Conflicts:
#	src/Interpreters/ITokenizer.h
#	src/Storages/MergeTree/MergeTreeIndexConditionText.h
…e references

Master advanced past 04725, so the 04726-04730 block collided with new
upstream tests. Renumber the five map-kv tests to the next free contiguous
block 04926-04930 and update their cross-references.

Regenerate the `04926_map_kv_tokenizer_basic` reference against the rebuilt
binary: it now also covers `m['key'] LIKE 'p%'` / `LIKE '%s'` (rewritten to
`startsWith` / `endsWith`) and the key-inclusive dictionary-scan gate, where the
selectivity bound is `len(key) + len(prefix/suffix)`. The compound and bugfixes
references are unchanged by the merge.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@UnamedRus
UnamedRus force-pushed the feature/map-kv-tokenizer branch from a1aef07 to 8240497 Compare August 18, 2026 12:43
```

For every map entry it stores a single token encoding both the key and the value, so a pair is matched precisely: unlike concatenating with a separator (for example `key=value`), a key or value that itself contains the separator character cannot produce a false match.
The key length is kept in a trailer, which also keeps the dictionary sorted by key and then by value.

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.

The ordering claim here is stronger than what the encoding actually gives. A concrete counterexample is encodeMapKeyValueToken("a", "", false) = 61 02, which sorts after encodeMapKeyValueToken("a\x01", "", false) = 61 01 04, so exact-key tokens are interleaved with longer keys sharing the prefix.

In the current implementation mapContainsKey/mapContainsKeyLike therefore fall back to analyzeDictionaryForPatterns and scan the full distinct-pair dictionary, not a bounded key range. Please either change this sentence (and the matching claim in MapKeyValueToken.h) or add the bounded key-range lookup that the docs currently promise.

Requires the map keys and values to be `String` or `FixedString`.
)";
FunctionDocumentation::Syntax syntax_mapContainsKeyValueLike = "mapContainsKeyValueLike(map, key_pattern, value_pattern)";
FunctionDocumentation::Arguments arguments_mapContainsKeyValueLike = {

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.

MapKeyValueLikeAdapter::checkTypes accepts FixedString needles and LowCardinality(...) wrappers on the map key/value types via removeLowCardinality, but the structured docs here still publish only const String patterns and plain String / FixedString map types.

Because this source generates the public function reference, supported calls are currently documented as invalid. Please broaden the argument/type metadata to match the actual accepted signature.

SELECT id FROM t_idx WHERE m['lvl'] IN ('err', 'warn') ORDER BY id SETTINGS use_skip_indexes = 1, optimize_functions_to_subcolumns = 1;

SELECT '-- direct read IS used for the literal IN set form (1) --';
SELECT 'direct read', count() > 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_idx WHERE m['lvl'] IN ('err', 'warn') SETTINGS query_plan_direct_read_from_text_index = 1, optimize_functions_to_subcolumns = 0) WHERE explain LIKE '%__text_index_%';

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.

04546_map_element_duplicate_keys_first_match.sql now locks first-occurrence parity across optimize_functions_to_subcolumns = 0/1, so the old “subcolumns=1 returns the last duplicate” assumption no longer applies.

The new exact-direct-read fallback in optimizeDirectReadFromTextIndex is specifically for the analyzed m.key_<...> form, but this block only asserts direct-read behavior for optimize_functions_to_subcolumns = 0. Please add the same direct-read / non-materialized-part check with optimize_functions_to_subcolumns = 1 so the default path is actually covered.

@Ergus

Ergus commented Aug 18, 2026 •

Copy link
Copy Markdown
Member

Hi @UnamedRus

After a few reviews of the changes in this PR I started wondering if it is possible that it is becoming a bit complex/overengineered for the change it is intended to implement.
What about if we stop for a moment and reconsider either the full new feature set or the current implementation?

Maybe we could instead try to simplify/select the new set of features or supported use cases and that could dramatically reduce and simplify the contribution changes.
Or maybe rethink the implementation to take advantage of the existing infrastructure more directly. Even if we need to redefine the expected behavior.
WDYT?

@UnamedRus

UnamedRus commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor Author

@Ergus

We could at least split it in prs i think.

  1. new MapContains functions are completely separate.
  2. Support for first/rest looks bit hacky, but currently it's unseparatable from tokenizer itself. ( if we plan to keep promise that use of index doesn't change result)
  3. Direct read probably can be made simpler, if only plain map[key] = value.
  4. AFAIK there is some extra hacking for map[xxx] IN (...) direct read support (in order to avoid bit worse hint mode). Support for IN i think is important, but may be direct read not so.
  5. Support for LIKE via dictionary scan i think useful, but will not shine until we have ranged text dictionary scan. (well, at least we have reason to defer until text index infrastructure will be ready)

The ordering claim here is stronger than what the encoding actually gives. A concrete counterexample is encodeMapKeyValueToken("a", "", false) = 61 02, which sorts after encodeMapKeyValueToken("a\x01", "", false) = 61 01 04, so exact-key tokens are interleaved with longer keys sharing the prefix.

Kinda valid, but not sure what will be worse if we will have ranged dictionary scan:

  1. Having len between key-value and slightly better/correct sorting
  2. Having len as trailer, and accept interleaving of key-value pairs

Or maybe rethink the implementation to take advantage of the existing infrastructure more directly. Even if we need to redefine the expected behavior.

Do you concrete ideas in mind?

@Ergus

Ergus commented Aug 18, 2026

Copy link
Copy Markdown
Member

Let's KISS it.

@Ergus

We could at least split it in prs i think.

1. new MapContains functions are completely separate.

2. Support for first/rest looks bit hacky, but currently it's unseparatable from tokenizer itself. ( if we plan to keep promise that use of index doesn't change result)

What about add only these two for now in an initial PR fully tested and documented.

3. Direct read probably can be made simpler, if only plain map[key] = value.

4. AFAIK there is some extra hacking for map[xxx] IN (...) direct read support (in order to avoid bit worse hint mode). Support for IN i think is important, but may be direct read not so.

And then one with this, departing from the previous change maybe it becomes more obvious how to implement it easily (even if we decide to add certain restriction)

5. Support for LIKE via dictionary scan i think useful, but will not shine until we have ranged text dictionary scan. (well, at least we have reason to defer until text index infrastructure will be ready)

This sounds correct and an important simplification.

Do you concrete ideas in mind?

  1. I was thinking in something like checking some already existing functions instead of creating a new one
  2. Identify if some specific corner case or some specific (potentially not very critical) use case is adding disproportionate complexity to the PR.
  3. Specifically there is a lot of new code in ‎src/Functions/array/FunctionsMapMiscellaneous.cpp Are we sure that we need all that for this feature?

@UnamedRus

UnamedRus commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor Author

Specifically there is a lot of new code in ‎src/Functions/array/FunctionsMapMiscellaneous.cpp Are we sure that we need all that for this feature?

Well, it's mostly should be very stupid code (translation from user facing map* to underlying lambda expression), (and documentation for it).
As for those functions, i think they are somewhat "important" because we currently have no way (or alternative with similar level of UX) for people to actually do check of all key values in map, not only first. (There is another question is how frequent it or do we really wanted such maps to be supported in first place, but as for now it's clear feature gap)

So, only reason why i added them:
All current access patterns (and text index in order to match current behavior) do check only first element.
So, we need something, which would allow to check all elements (and wire in text index)

two for now in an initial PR fully tested and documented.

But, wired in text index you mean?

@Ergus

Ergus commented Aug 18, 2026 •

Copy link
Copy Markdown
Member

But, wired in text index you mean?

Not necessarily. Just needs to be simpler, smaller and tested. Don't need to be conceptually different to their current implementation in this PR.

The idea is to support the baseline use case and then we can test, profile and improve it.

@UnamedRus

Copy link
Copy Markdown
Contributor Author

Sure, map* functions are completely separate and can be tested as is. (and if we split in PRs, don't thing it necessary to tie them to init pr of tokenizer)
But, tokenizer use is tied to text indexes. (and infra to support seach by it)
We can keep it as separate pr of only tokenizer, but there ain't that much to test or use (after it got merged) i feel.

I'm still bit "on the fence" about how first/rest is implemented (as part of tokenizer layout), but if you also don't see any better way, we can probably go ahead with it.

@Ergus

Ergus commented Aug 18, 2026

Copy link
Copy Markdown
Member

I'm still bit "on the fence" about how first/rest is implemented (as part of tokenizer layout), but if you also don't see any better way, we can probably go ahead with it.

@rschu1ze and @CurtizJ any proposal on this? Some better idea than current implementation?

@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 8240497d8 with master 5bd006cd2 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 5cd15f81f; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 702.05 MiB 699.16 MiB -2.89 MiB (-0.41%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes ⚠️

17 object files changed (+653.06 KiB total), 1 added.

Object file Master PR Δ
src/Functions/array/CMakeFiles/clickhouse_functions_array.dir/FunctionsMapMiscellaneous.cpp.o 4.34 MiB 4.83 MiB +507.21 KiB (+11.42%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeIndexConditionText.cpp.o 807.39 KiB 894.06 KiB +86.68 KiB (+10.74%)
src/CMakeFiles/dbms.dir/Interpreters/MapKeyValueToken.cpp.o new 17.17 KiB +17.17 KiB

737 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

43 translation units recompiled, 348 s compile time in total, 42 of them have a recent master baseline.

Job report

@rschu1ze rschu1ze changed the title Add keyValuePairs text-index tokenizer for Map columns [RFC] Add keyValuePairs text-index tokenizer for Map columns Aug 20, 2026
@rschu1ze rschu1ze changed the title [RFC] Add keyValuePairs text-index tokenizer for Map columns Add keyValuePairs text-index tokenizer for Map columns Aug 20, 2026
@rschu1ze

Copy link
Copy Markdown
Member

Allow me to close this PR. It will be split and pushed as multiple smaller PRs (@Ergus did that locally already as he told me last week), starting with #115579

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 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.

New Tokenizer for Map Key Value pairs

6 participants