Skip to content

Map kv tokenizer minimal - #115579

Merged
Ergus merged 28 commits into
ClickHouse:masterfrom
Ergus:map-kv-tokenizer-minimal
Sep 14, 2026
Merged

Ergus merged 28 commits into
ClickHouse:masterfrom
Ergus:map-kv-tokenizer-minimal

Conversation

@Ergus

@Ergus Ergus commented Aug 20, 2026 •

Copy link
Copy Markdown
Member

Related: #110757
Related: #110454

Adds a keyValuePairs text-index tokenizer for Map(String, String) columns. Every (key, value) pair of a row becomes one token, so WHERE m['key'] = 'value' is answered by a single exact token lookup with direct read, instead of reading the map column. An index on mapKeys(m) or mapValues(m) cannot do this: it knows that some key exists and that some value exists, but not that they belong to the same pair.

This is a minimal first increment of #110757 by @UnamedRus, split up as discussed in the review of that pull request. Only the tokenizer and
m['key'] = 'value' are here; m['key'] IN (...), mapContainsKey, mapContainsValue, the LIKE and prefix/suffix forms, and the new mapContainsKeyValue / mapContainsKeyValueLike functions are left for follow-ups. As a result nothing outside the tokenizer, the index aggregator and the index condition needs to change: TextIndexAnalyzer, MergeTreeReaderTextIndex and optimizeDirectReadFromTextIndex are untouched.

The token layout is varint((length(key) << 1) | is_rest) ‖ key ‖ value. The length prefix keeps the key/value boundary unambiguous, so keys and values may contain arbitrary bytes, and it makes the tokens of one key a contiguous range of the sorted dictionary, which a later range scan can use. is_rest marks a key's non-first occurrence in a row, so the lookup matches the same occurrence as m['key'] when a row contains duplicate keys.

Restrictions, all rejected at table creation: keys and values must be String or
LowCardinality(String) (FixedString would store padding bytes that a searched constant does not have, silently missing rows), and preprocessor, postprocessor and support_phrase_search are not accepted. m['key'] = '' is also true for rows that do not contain the key at all, so that predicate falls back to a scan.

This doesn't close issue #110454, because it asks for Map text-index support broadly and this only covers exact element equality.

Changelog category (leave one):

  • New Feature

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

New text index tokenizer keyValuePairs, which indexes a Map(String, String) column directly and answers map['key'] = 'value' from the index without reading the map column.


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

Version info

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

@Ergus
Ergus requested review from ahmadov and rschu1ze August 20, 2026 10:22
@Ergus
Ergus force-pushed the map-kv-tokenizer-minimal branch from a601623 to 21857d9 Compare August 20, 2026 10:32
@clickhouse-gh

clickhouse-gh Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2f73ee4]

Summary: ✅


AI Review

Summary

This PR adds the keyValuePairs text-index tokenizer for Map(String, String) and wires exact direct reads for map['key'] = 'value'. The core lookup path is close, but two blocker-level gaps remain: empty-input string tokenization still bypasses the promised NOT_IMPLEMENTED exception, and fresh full-definition ATTACH can bypass all of the new keyValuePairs validation.

Findings
❌ Blockers
  • [src/Storages/MergeTree/MergeTreeIndexText.cpp:2210-2266] keyValuePairs promises that only Map(String, String) / Map(LowCardinality(String), LowCardinality(String))-style inputs without preprocessor, postprocessor, or support_phrase_search are allowed, but those checks exist only in textIndexValidator. MergeTreeIndexFactory::validate intentionally skips validator enforcement on attach = true, so a fresh full-definition ATTACH TABLE ... UUID ... (...) can still create a keyValuePairs index on Map(String, UInt64) or with support_phrase_search = 1. The build path then tokenizes non-string values via raw IColumn::getDataAt bytes or goes through unsupported preprocessing/positions paths instead of rejecting the definition.
    Suggested fix: enforce the same keyValuePairs invariants in textIndexCreator (or make full-definition ATTACH take the fresh-definition validation path) and add a focused ATTACH TABLE ... UUID ... regression.
  • [src/Interpreters/ITokenizer.h:666-719] keyValuePairs is supposed to reject string tokenization, but forEachToken returns on length == 0 before it reaches the throwing nextInString dispatch. As a result, tokens('', 'keyValuePairs') and any other empty-input forEachToken caller silently return an empty result instead of the advertised NOT_IMPLEMENTED exception.
    Suggested fix: move the KeyValuePairs rejection ahead of the zero-length fast path, or special-case that branch so empty strings still throw.
Final Verdict
  • Status: ❌ Block
  • Minimum required actions:
    1. Enforce the keyValuePairs type/option restrictions on the full-definition ATTACH path as well as CREATE.
    2. Restore the promised exception behavior for empty-input string tokenization with keyValuePairs.

LLVM Coverage Report

Measured on commit 2f73ee4.

Metric Baseline Current Δ
Lines 89.00% 89.00% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.40% 81.40% +0.00%

Changed lines: Changed C/C++ lines covered: 146/158 (92.41%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Aug 20, 2026
@rschu1ze

rschu1ze commented Aug 20, 2026 •

Copy link
Copy Markdown
Member

There is an alternative "minimal" PR here: #115363

@Ergus 's PR looks more minimal and therefore preferred.

@UnamedRus

Copy link
Copy Markdown
Contributor

The token layout is varint((length(key) << 1) | is_rest) ‖ key ‖ value.

My biggest reasoning for not putting len at beginning of token was that it will harm across key sorting. (key frequently share the same prefix)

@CurtizJ

CurtizJ commented Aug 20, 2026

Copy link
Copy Markdown
Member

My biggest reasoning for not putting len at beginning of token was that it will harm across key sorting. (key frequently share the same prefix)

That's true, we should use key value len layout to support prefix searches.

@UnamedRus

Copy link
Copy Markdown
Contributor

TLDR, i don't care which pr is merged(may be slight edge towards @Ergus, bc in that case, it will be his responsibility ;) )
But, i'll ask few things to consider

  1. use trailer layout for token. (or think/bench which is actually better)
  2. think if approach with "namespaces" are better. (is it a good fit for layout of token dictionaries, may be it useful for future expansions)
  3. for is_rest detection versioned (per chunk) hashmap of key -> last row it was seen, seems like a good perf improvement idea, if we assume that keys highly repetitive in chunk.
  4. May be take random generator .sh. (accidentally, i've caught 1-2 bugs in CH with it)

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

Looks pretty neat.

out.reserve(getLengthOfVarUInt(packed) + key.size() + value.size());

/// Keys under 64 bytes pack into one varint byte; skip the writeVarUInt buffer.
if (packed < 0x80)

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.

Let's put the length tie-breaker to the end of the token as discussed in the PR.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This makes sense for mapContainsKeyLike-style pattern scans. In a gross estimation I think that it adds some extra storage cost to the dictionary (~10-20%)... But that's ok?

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.

that it adds some extra storage cost to the dictionary (~10-20%).

But why?

This makes sense for mapContainsKeyLike-style pattern scans

That may be useful.

There was also an initial feature request in #110454 to support queries like

SELECT ...
FROM mergeTreeTextIndex('default', 'table', 'idx_key_value_pairs')
WHERE startsWith(token, 'prefix=')

It will be problematically to do this if we put tie-breaker to the beginning of the key.

@UnamedRus UnamedRus Aug 20, 2026 •

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.

There is, one certain advantage of having len at beginning.

If we know key, but don't know which value we are looking.
In that case, (if/when range scan of dictionary will be implemented), it would allow us to read only range of tokens for that key.

With len at end, we can only read all tokens which start from that key prefix. (but filter them by their trailer len after decompression/deserialization)

It's not a best/most representative datasets, but what i have at hand:

┌─────────┬─────────────┬─────────────┬─────────────┬───────────────────┐
│ dataset │ avg key len │ avg val len │ val numeric │ # distinct tokens │
├─────────┼─────────────┼─────────────┼─────────────┼───────────────────┤
│ PE      │        24.6 │        2.87 │        100% │         5,463,164 │
├─────────┼─────────────┼─────────────┼─────────────┼───────────────────┤
│ OTEL    │        11.7 │        26.3 │       11.9% │           435,188 │
└─────────┴─────────────┴─────────────┴─────────────┴───────────────────┘



OTEL LogAttributes — 2M rows, 435,188 tokens

┌────────┬────────────┬───────────┬────────────┬─────────┐
│   PR   │    dict    │ postings  │   total    │ vs best │
├────────┼────────────┼───────────┼────────────┼─────────┤
│ 115579 │ 11,250,568 │ 6,400,274 │ 17,675,266 │    best │
├────────┼────────────┼───────────┼────────────┼─────────┤
│ 110757 │ 11,320,878 │ 6,400,274 │ 17,745,567 │  +0.40% │
├────────┼────────────┼───────────┼────────────┼─────────┤
│ 115363 │ 11,322,670 │ 6,400,274 │ 17,747,380 │  +0.41% │
└────────┴────────────┴───────────┴────────────┴─────────┘

ProfileEvents part_log — 2M rows, 5,463,164 tokens

┌────────┬────────────┬────────────┬─────────────┬─────────┐
│   PR   │    dict    │  postings  │    total    │ vs best │
├────────┼────────────┼────────────┼─────────────┼─────────┤
│ 115579 │ 47,654,489 │ 99,767,791 │ 147,561,868 │    best │
├────────┼────────────┼────────────┼─────────────┼─────────┤
│ 110757 │ 50,427,402 │ 99,767,791 │ 150,335,091 │  +1.88% │
├────────┼────────────┼────────────┼─────────────┼─────────┤
│ 115363 │ 50,941,720 │ 99,767,791 │ 150,849,609 │  +2.23% │
└────────┴────────────┴────────────┴─────────────┴─────────┘

Pure index-read cost per tokenizer

┌──────────────┬────────────┬──────────────────┬──────────────────┬──────────────────┐
│    query     │  granules  │      110757      │      115363      │      115579      │
├──────────────┼────────────┼──────────────────┼──────────────────┼──────────────────┤
│ pe eq_rare   │ 4/261      │ 699 KB / 16 ms   │ 699 KB / 14 ms   │ 694 KB / 14 ms   │
├──────────────┼────────────┼──────────────────┼──────────────────┼──────────────────┤
│ pe eq_med    │ 261/261    │ 8.826 MB / 19 ms │ 8.827 MB / 19 ms │ 8.825 MB / 19 ms │
├──────────────┼────────────┼──────────────────┼──────────────────┼──────────────────┤
│ pe valonly   │ 30 vs 261  │ 9.92 MB / 655 ms │ 8.58 MB / 20 ms  │ 8.58 MB / 17 ms  │
├──────────────┼────────────┼──────────────────┼──────────────────┼──────────────────┤
│ otel eq_rare │ 1/245      │ 188 KB / 14 ms   │ 188 KB / 12 ms   │ 183 KB / 14 ms   │
├──────────────┼────────────┼──────────────────┼──────────────────┼──────────────────┤
│ otel eq_med  │ 122/245    │ 7.166 MB / 16 ms │ 7.166 MB / 20 ms │ 7.183 MB / 19 ms │
├──────────────┼────────────┼──────────────────┼──────────────────┼──────────────────┤
│ otel valonly │ 122 vs 245 │ 7.59 MB / 94 ms  │ 9.23 MB / 17 ms  │ 8.96 MB / 19 ms  │
├──────────────┼────────────┼──────────────────┼──────────────────┼──────────────────┤
│ otel eq_low  │ 211/245    │ 8.75 MB / 22 ms  │ 8.75 MB / 21 ms  │ 8.77 MB / 25 ms  │
└──────────────┴────────────┴──────────────────┴──────────────────┴──────────────────┘

@clickhouse-gh

clickhouse-gh Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 2f73ee4d7 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 (+189.98 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/FillingStep.cpp.o 158.83 KiB 270.11 KiB +111.29 KiB (+70.07%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeIndexText.cpp.o 749.73 KiB 774.90 KiB +25.18 KiB (+3.36%)
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

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

Job report

@EmeraldShift

EmeraldShift commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

What are folks' opinions on key-first vs. value-first in the token? Seems that key-first is great for prefix search when you know the key, while value-first can also serve generic mapValues() or "all keys" searches more efficiently.

@rschu1ze

Copy link
Copy Markdown
Member

Maps are expected to be searched by key, not by value. I'd vote for key first

@EmeraldShift

Copy link
Copy Markdown
Contributor

For exact key and value, I suppose both ordering work well since there's an exact needle in either haystack. Agreed that things like map['key'] LIKE ... having the key first enables more co-located data for range scans :)

case ITokenizer::Type::KeyValuePairs:
{
/// This tokenizer does not split strings: `nextInString` throws.
detail::forEachTokenImpl(tokenizer, data, length, callback);

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.

keyValuePairs is supposed to reject string tokenization, but this new forEachToken path only reaches the throwing nextInString when length > 0. With the generic empty-input fast path above, tokens('', 'keyValuePairs') now quietly returns [] instead of the NOT_IMPLEMENTED you test for, and the same hole affects other empty-input forEachToken callers. Please move the KeyValuePairs rejection ahead of the zero-length fast path, or special-case this branch so empty strings still throw.

@clickhouse-gh clickhouse-gh Bot added the comp-text-index Full-text search: inverted/text index in MergeTree (tokenizers, posting lists, GIN-style index bu... label Sep 4, 2026
/// The `text_index_serialization_version` setting is not validated against the index features:
/// it is a preference, and `textIndexCreator` raises it to a version that can represent them.
/// The keyValuePairs tokenizer cannot be combined with a preprocessor, a postprocessor or positions.
if (tokenizer->getType() == ITokenizer::Type::KeyValuePairs)

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.

These keyValuePairs restrictions only run in the validator, but full-definition ATTACH TABLE ... UUID ... (...) does not actually get protected by them: MergeTreeIndexFactory::validate intentionally skips attach-time checks, and textIndexCreator still accepts whatever metadata made it this far. That means a user can bypass the new CREATE-time contract with ATTACH, for example by attaching TYPE text(tokenizer = 'keyValuePairs', support_phrase_search = 1) or even Map(String, UInt64). The build path then treats non-string values as raw bytes via IColumn::getDataAt() or runs through unsupported pre/postprocessor/positions code instead of rejecting the definition. Please enforce the same keyValuePairs invariants in textIndexCreator as well (or make full-definition ATTACH validate like fresh CREATE) and add an ATTACH TABLE ... UUID ... regression.

@Ergus
Ergus added this pull request to the merge queue Sep 14, 2026
Merged via the queue into ClickHouse:master with commit 7e8e3cb Sep 14, 2026
177 checks passed
@Ergus
Ergus deleted the map-kv-tokenizer-minimal branch September 14, 2026 09:21
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 14, 2026
vitlibar pushed a commit that referenced this pull request Sep 15, 2026
Use `keyValuePairs` to index label pairs in the `tags` map for new schema
version 4 tables. Preserve explicit indexes and earlier schema versions,
and carry index declarations through inner-table creation and attachment.

Related: #115579
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-text-index Full-text search: inverted/text index in MergeTree (tokenizers, posting lists, GIN-style index bu... 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