Skip to content

WIP: Projection Index Text - #93114

Closed
amosbird wants to merge 93 commits into
ClickHouse:masterfrom
amosbird:projection-index-text-squash
Closed

amosbird wants to merge 93 commits into
ClickHouse:masterfrom
amosbird:projection-index-text-squash

Conversation

@amosbird

@amosbird amosbird commented Dec 29, 2025 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Improvement

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

Added an experimental projection-based text index for MergeTree tables, which stores the index as a first-class projection with posting-list columns and supports direct reads from the index. Enable it with the setting allow_experimental_projection_text_index.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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

@clickhouse-gh

clickhouse-gh Bot commented Dec 29, 2025 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [addba28]

Summary: ❌

job_name test_name status info comment
Fast test FAIL
03800_projection_text_index_hint_map FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL
Code Review DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_debug) DROPPED
Build (arm_asan_ubsan) DROPPED

@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements submodule changed At least one submodule changed in this PR. labels Dec 29, 2025
@amosbird
amosbird force-pushed the projection-index-text-squash branch 6 times, most recently from bf78dd7 to 52bb372 Compare December 30, 2025 07:41
@rschu1ze

Copy link
Copy Markdown
Member

Hi @amosbird

I know you put in a lot of work into this, that this is a draft, and I might not have all background information.

Users have a common expectation that full-text search is backed by a inverted text index. Implementing it differently as projection index will mean a lot explaining - projections are actually an unusual feature for databases. Funtionality- and performance-wise, the inverted index and the projection index will be similar but of course, we'll need to maintain both. Also, a lot of tweaking and tuning went into the existing inverted index (different format versions, tokenizers, functions). A projection index means re-engineering a lot of this.

I'm of course happy to hear some good reasons why ClickHouse should offer also a projection index, but for now I would vote for not merging this one.

@amosbird

amosbird commented Dec 30, 2025 •

Copy link
Copy Markdown
Collaborator Author

Hi @rschu1ze, thanks for the feedback. Let me try to clarify a few points regarding the projection index text PR and its motivation.

Projection index turns index structures into first-class, typed columns.
The core innovation is not a new indexing algorithm, but a change in abstraction: index data is modeled as regular columns that the engine can natively understand and operate on.

This enables cross-layer reuse between the engine and indexes. Engine-level optimizations (e.g. ColumnString FSST encoding, primary key layout improvements, string serialization) automatically apply to index data, while optimizations introduced for index-specific column types (such as PostingList) become available to the engine once expressed through the column and type system.

It also allows index structures to act as reusable analytical primitives, not just lookup accelerators. For example, a PostingList column introduced for text projections can also support union-heavy analytical workloads more efficiently than bitmap-based approaches (see e.g. https://dl.acm.org/doi/10.1145/3035918.3064007), achieving benefits for both indexing and query execution.

Finally, because projection index data is stored as regular columns, it is directly observable via SQL, making index behavior transparent and enabling easier introspection, debugging, and iteration of future index designs.

Regarding the concern that functionality- and performance-wise the inverted index and the projection index would be similar and both would need to be maintained:

First, while this PR could serve as a foundation for a production-ready text index in the future, its primary goal is to demonstrate the projection-based indexing concept and its value. Similar to my earlier performance-focused PR #81944, this work should be viewed as a conceptual and architectural demo. The implementation in this PR will be split into smaller, meaningful components and submitted incrementally.

From a maintenance perspective, a projection-based implementation is in fact well aligned with text indexing needs in several ways. It is naturally part-level (unlike skip indices which are granule-level), it already benefits from projection merge and mutation support (which the current text index merge logic partially relies on as well), and it can be easily extended to support Lucene-like payloads, i.e. attaching additional data to index entries. In this sense, some recent optimizations in the text index—such as direct-read behavior—are closer to materialized expression semantics, which are a natural fit for projections.

The intent here is not to introduce long-term maintenance overhead. Implementing text-index-related capabilities on top of projections requires only minimal adaptation, rather than maintaining a parallel indexing subsystem. In parallel, our team continues to actively optimize the existing text index implementation (e.g. #92871), and this work is orthogonal to the projection-based approach. At the same time, we are also investing in additional index types, such as key–value, vector, and spatial indexes.

@rschu1ze

Copy link
Copy Markdown
Member

@amosbird Ah, it makes more sense to me now, thanks.

@amosbird
amosbird force-pushed the projection-index-text-squash branch 2 times, most recently from 99e8b67 to cc56347 Compare January 5, 2026 01:50
@UnamedRus

Copy link
Copy Markdown
Contributor

Users have a common expectation that full-text search is backed by a inverted text index.

There is somewhat common feature called covering index. (basically, when you can specify extra columns for index column, so just reading index will be sufficient for answering query)

I can imagine, that projection index can have "simpler" expansion to cover this feature.
How hard to implement with current inverted index implementation, if it will be required?

@amosbird
amosbird force-pushed the projection-index-text-squash branch 4 times, most recently from 069a41a to a75bcec Compare January 10, 2026 22:17
@amosbird
amosbird force-pushed the projection-index-text-squash branch 2 times, most recently from 52098a9 to b470cbb Compare January 14, 2026 14:41
@amosbird
amosbird force-pushed the projection-index-text-squash branch 6 times, most recently from 0643c1e to 760931a Compare February 4, 2026 15:11
@amosbird
amosbird marked this pull request as ready for review February 5, 2026 00:55
@amosbird
amosbird marked this pull request as draft February 9, 2026 09:39
@amosbird
amosbird force-pushed the projection-index-text-squash branch from db1abde to a0245d4 Compare April 2, 2026 11:15
alexey-milovidov and others added 10 commits October 21, 2026 13:04
…ken projection subparts

After merging `master`, `IMergeTreeReader::readRows` takes an extra `shared_columns`
argument (columns shared with the columns cache). Update the override in
`MergeTreeReaderTextProjectionIndex` and the call in `MergeTreeProjectionIndexGranuleText`.

Address review: a broken `<projection>.proj` subpart keeps its checksum entry in the parent
part, so the projection text index was considered materialized and reads were routed into the
broken subpart. Add a virtual `IMergeTreeIndex::isUsableInPart` consulted by
`getDeserializedFormat`; `MergeTreeProjectionIndexText` reports itself unusable when
`hasBrokenProjection` is true, so the query evaluates the original predicate instead. The
reader now uses `getDeserializedFormat`, and the granule skips broken projection parts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Compute the next absolute position in `UInt64` and throw `INCORRECT_DATA` when it is not
below `PositionCursor::NO_MORE_POSITIONS` (also for the first position of a document), so
corrupted `.pos` data cannot be mistaken for the end-of-document sentinel.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…t-read entries

`collectTextIndexInjectInfos` only enumerated secondary text indexes, so for a table with
only `PROJECTION ... INDEX ... TYPE text(...)` the tokenizer / preprocessor rewrite was skipped
when skip-index analysis produced no direct-read entry (the function in the `SELECT` list, or
`use_skip_indexes = 0`), and the function used raw semantics. Enumerate projection text
indexes as well.

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

After merging `master`, the `LIKE` condition is moved to `PREWHERE` (the same happens for a
regular text index), and the placement also depends on randomized settings. Print both
`Filter column` and `Prewhere filter column` as `Filter column`.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=93114&sha=7450e650314cbcee77f41be06b11e48dde1e0fe5&name_0=PR
PR: ClickHouse#93114

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…d existing text projection indexes

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	src/Storages/MergeTree/MergeTreeDataPartWriterCompact.cpp
#	src/Storages/MergeTree/MergeTreeDataPartWriterWide.cpp
#	src/Storages/StorageFactory.cpp
…e settings history

Fixes the `settings_changes_history` style check after the version bump.

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

The overload is only called with an lvalue part, so the returned reference cannot dangle.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master and pushed 3bcadf92fee.

  • Conflicts: MergeTreeDataPartWriterCompact.cpp and MergeTreeDataPartWriterWide.cpp (master dropped the effective_codec_desc argument from addStreams and moved codec resolution into getSubstreamCodec(name_and_type, substream_path); I took master's version and kept the PR's posting-list stream setup). StorageFactory.cpp: kept both sets of includes.
  • Fixed settings_changes_history: allow_experimental_projection_text_index is now recorded under 26.11.
  • Fixed the various style check: 03800_projection_text_index_materialization.sh now starts with #!/usr/bin/env bash.
  • Fixed the arm_tidy build: added a NOLINT(bugprone-return-const-ref-from-parameter) to the identity getPart overload in MergeTreeIndices.cpp.

clickhouse builds locally. I ran the PR's projection text and projection index stateless tests against a local server: everything that does not need ZooKeeper, test clusters or system.query_log passes. The open thread about inheriting table-level text_index_* settings is a design question and is waiting on the author or reviewers.

alexey-milovidov and others added 7 commits October 31, 2026 10:27
…xt-squash

Conflicts resolved:
- `MergeTreeIndexConditionText`: master replaced `NameSet columns_shadowing_map_subcolumns` with an
  `IsShadowingColumn` callback; kept the PR's `is_projection_index` flag on top, and the projection
  text index passes a callback that reports nothing as shadowing.
- `MergeTreeReaderCompact`: kept both the PR's projection-index stream getters and master's columns cache.
- `MergeTreeReaderCompactSingleBuffer`: master moved the per-granule loop into `readGranule`; moved the
  PR's `posting_filter_callback` invocation there.
Master now forbids formatting pointers with `fmt` (`FMT_DISALLOW_POINTERS`), which broke the build after the merge.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ection is broken

`isVirtualColumnMaterializedInPart` considered the virtual column of a projection text index
materialized whenever the part had the projection, even a broken one. The read task then
declined the broken index, but the source column was not injected, so the predicate was
evaluated on default values and matching rows were lost.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ts own token cursors

The cursors of the tokens were shared between the virtual columns of different predicates. A
cursor has a mutable position, so filling the column of `hasAllTokens(s, ['a', 'b'])` advanced
the cursor of `b`, and the column of `hasAllTokens(s, ['c', 'b'])` then missed rows before it.
Now the first virtual column takes the cursor from the shared map, and the others build their own.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ction text index

`multiSearchAny` with `use_text_index_like_evaluation_by_dictionary_scan` produced a pattern-only
query in `Exact` mode. The projection text index reader cannot evaluate it and fills the virtual
column with ones, while the optimizer dropped the original predicate, so all rows matched.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rted arguments of a projection text index

- `IProjectionIndex::getIndex` takes the metadata of the parent table, so the condition of a projection
  text index knows which columns of the parent table shadow Map subcolumns, like a regular text index.
- `ProjectionIndexText::calculate` uses its own copy of a stateful tokenizer (`sparseGrams`): the
  index belongs to the shared table metadata, and concurrent inserts and merges calculate it at once.
- Reject what the projection cannot handle when the table is created, instead of failing every insert
  or writing parts that cannot be read back: the `postprocessor` argument (stored tokens are not
  postprocessed), `enable_phrase_query_support` without `has_block_index`, `Map` columns
  (`keyValuePairs`), and posting list parameters that `PostingListParams::validate` rejects on load.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master (conflicts in MergeTreeIndexConditionText and the compact readers: the posting_filter_callback call moved into the new readGranule), fixed the build after master forbade formatting pointers, pinned merge_max_block_size in 03800_projection_text_index_replacingmergetree2 (flaky-check timeout with a randomized block size of 6), and addressed the review threads with two new tests (05473, 05474).

Remaining for a human:

  • Relocation headroom (Build (amd_msan)): the feature adds ~15.6 MiB of code; if acceptable, the ci-relocation-headroom-ok label needs to be added.
  • The thread about inheriting table-level text_index_* settings into the projection is a design question; it is left open.
  • contrib/abpfor points to https://github.com/amosbird/abpfor; it likely needs a ClickHouse-org fork before merging.


if ((header_byte & 0xC0u) == 0xC0u)
{
unsigned b = header_byte & 0x3Fu;

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.

[P1] Exclude the raw abpfor marker from the arithmetic probe

In the pinned abpfor codec, 0xFF is kSpecial | kRaw: it contains an uncompressed array, not one repeated constant. This test accepts it as a constant block and reads its first value as the delta for every document.

A valid posting list {0, 2147483649, 3221225474} has tail delta-minus-one values {2147483648, 1073741824}. The codec selects the raw 0xFF encoding for that two-element tail, but this probe returns constant 2147483648. The arithmetic path therefore emits a progression with step 2147483649, dropping the actual document 3221225474 during mark filtering/direct reads. All these IDs are within the supported UInt32 range; no corrupted input is required.

Exclude kRaw from this shortcut and let the normal decoder handle it. A codec/cursor regression using these IDs can cover the case without constructing billions of table rows.

if (!isPartTypeCompatibleImpl(skip_index, part))
return {0 /*unknown*/, {}};

if (!skip_index.isUsableInPart(getPart(part)))

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.

[P1] Preserve the nullable concrete-part contract for ordinary indexes

This now obtains a concrete part for every materialized skip index, including ordinary indexes whose default isUsableInPart always returns true. However, IMergeTreeDataPartInfoForReader::getDataPart explicitly returns null for borrowed stateless-worker parts and forbids using it in shared read paths. The new getPart overload unconditionally dereferences that null pointer to bind this reference.

Both filterMarksUsingIndex and MergeTreeIndexReader::initStreamIfNeeded call this overload for ordinary indexes, without a concrete-part guard. Thus a valid borrowed-part input now invokes undefined behavior even when projection text indexes are disabled. The private worker setup is unavailable here, so I could not execute that end-to-end path; the nullable interface contract and unguarded callers are present in this checkout.

Keep this projection-only check out of ordinary-index reads, or make the hook work through the part-info abstraction without dereferencing an absent concrete part. Cover ordinary skip-index reads with a borrowed part.

static_cast<ProjectionIndexText &>(*result.index).effective_settings = std::make_shared<const MergeTreeSettings>(projection_settings);

result.required_columns = index_description.expression->getRequiredColumns();
result.with_parent_part_offset = true;

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.

[P1] Reject conflicting physical columns when adding a text projection

Unlike the query-projection path, this unconditionally enables parent offsets even if the parent has a physical _part_offset, _part_index, or _parent_part_offset column. MergeTreeData::checkProperties checks these collisions only for projections in old_metadata, so it misses a newly added text projection.

For example, an existing MergeTree table with id UInt64, s String, _parent_part_offset UInt64 can accept ALTER TABLE t ADD PROJECTION p INDEX s TYPE text(tokenizer = splitByNonAlpha). The stored definition then cannot pass ATTACH/startup validation: there old_metadata includes p, and the same collision check rejects it. Subsequent unrelated ALTERs encounter the invalid combination too.

Validate these reserved physical names before setting with_parent_part_offset, or validate newly added projections against the effective parent columns in checkProperties. Add an ADD PROJECTION regression for an existing table with a conflicting column.

alexey-milovidov and others added 4 commits November 8, 2026 09:44
…xt-squash

Conflict resolutions:
- `MergeTreeIndexConditionText`: keep both the new `is_projection_index_` and master's
  `automaton_budget_` constructor arguments; the projection text index shares the
  automaton budget of its underlying `MergeTreeIndexText`.
- `optimizeUseAggregateProjection`: master moved collection of aggregate projections
  to a single place; keep excluding projection indexes there.
- `InterpreterCreateQuery`: take master's `enable_database_materialized_postgresql` rename.
- `MergeTreeIndices`, `StorageFactory`: keep both sides.

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

When a projection text index is materialized or rebuilt from a large part, it is
calculated in several batches. The calculated blocks were squashed together and
aggregated in `writeTempProjectionPart`, which merged in-memory `PostingListWriter`
states of the same term by concatenating their chunk chains: this lost the first
document of the right-hand side and broke block boundaries. The empty placeholder of
a tokenless batch (a `PostingListStream`) was also mixed with `PostingListWriter`
states in one column, and the serialization assumed a homogeneous range, which
caused a segmentation fault.

Each calculated block has unique terms, so it is now written to its own temporary
part, and the parts are merged from their on-disk form. `mergeImpl` handles empty
states of either representation and throws instead of producing a corrupted posting
list, and the serialization dispatches on the state of each row.

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

`calculate` assigns document ids to the rows of the parent part, but an expression with
`arrayJoin` changes the number of rows, which led to out-of-bounds accesses or invalid
postings on insert. The projection-level `arrayJoin` check does not apply to the
`INDEX` syntax, which has no projection query, so check the analyzed index expression,
which also covers SQL UDFs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…umn changes its type

`isPartTypeCompatible` accepted every projection index on the premise that an ALTER of a
column a projection reads is rejected. That does not hold for a projection text index:
its output schema (`term`, `posting`) is fixed, so a metadata-only `MODIFY COLUMN`, e.g.
`UInt32` to `DateTime` or `UInt8` to `Bool`, is accepted without rebuilding the index while
the values of the indexed expression change, and the stale index pruned matching rows.

A projection index obtained for a query carries the parent metadata and is checked against
the parent part, so apply the same type and meaning check as for skip indexes. Only an
index built for writing, which has no metadata, skips it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master and addressed the open review findings: squashing of calculated projection-index blocks (segmentation fault on multi-batch MATERIALIZE PROJECTION), arrayJoin in the index expression, and a stale index after a metadata-only source-column type change. Each has a regression test (05569–05571).

The only red check on the previous head was Relocation headroom in Build (amd_msan): the PR adds about 15.6 MiB of code (abpfor contrib + projection text index). If that growth is accepted, the ci-relocation-headroom-ok label is needed. That is a maintainer decision, so I have not added it.

The thread on inheriting table-level text_index_* settings in ProjectionIndexText::getDefaultSettings remains open as a design question for the author and reviewers.

@rschu1ze

rschu1ze commented Nov 9, 2026 •

Copy link
Copy Markdown
Member

There was some discussion about this PR after #93114 (comment) but the text index in ClickHouse is GA since 26.2 and there has been no non-agentic activity in this PR since 9 months. Chances that we'll migrate to an entirely different data storage for text indexes soon are very low. Thanks anyways for working on this.

@amosbird

Copy link
Copy Markdown
Collaborator Author

Thanks for clarifying the decision. I am sorry to see this direction discontinued.

I spent two years working on Elasticsearch, and one of my motivations for this work was the hope that ClickHouse could eventually go beyond its indexing ability. This PR represents a substantial result of that effort: first-class typed index data, natural integration with projection merges and mutations, direct SQL observability, a path toward covering indexes, and significant performance improvements.

I'll try to reuse the work in this PR, but rethink and retitle it around a broader concept from a different angle, potentially as a foundation for multi-model indexing or other use cases that benefit from first-class index data, so that it complements the existing text index rather than directly competing with or replacing it.

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... external Author is not a member of the ClickHouse organization pr-improvement Pull request with some product improvements submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants