NewBeyond ClickHouseSee where ClickHouse breaks for observability at scale, with our benchmark.

What I wish I (and my agents) had known about ClickHouse #9: Text index

Originally published on LinkedIn

A green transit bus on a winding gravel road through green hills, seen from above
A bus on the Denali Park Road just before Igloo Canyon, July. Photo: NPS / Emily Mesner, via Wikimedia Commons.
On this pageA different kind of indexHow we added itDropping the old token filterFour searches, on and offWhen it costs more than it savesThe storage and compute billWhat about JSON columns?What I check nowWhat's next?

Episode 8 covered data skipping indexes for log search, and why our bloom filter indexes often let us down. Common words exist in almost every granule. Filters were the wrong size. For one customer, checking the 512 KiB token bloom filter took longer than reading the data. This episode is about what replaced it on our log messages: ClickHouse's text index, how it performed on real searches, what it cost in storage and compute, and where JSON columns stand now.

A different kind of index

A token bloom filter stores one summary per 8,192-row granule. ClickHouse checks every summary and gets only "no" or "maybe".

The text index is an inverted index: a dictionary of words paired with posting lists of matching rows. ClickHouse builds one per part (default granularity: 100 million), not per granule. It looks a word up once per part and gets the matching rows back. A missing word is a definite "no", with no per-granule filter scan.

Queries use it through hasToken, hasAllTokens, hasAnyTokens, hasPhrase, =, and IN. ClickHouse recommends hasAllTokens and hasAnyTokens for new queries; hasTokenCaseInsensitive does not use the text index at all. When a query filters only with supported token functions, ClickHouse answers directly from the index without reading the text column.

LIKE uses the index only for complete words bounded by spaces or punctuation, the same rule as in Episode 8. In message LIKE '%could not charge the card%', only "not", "charge", and "the" qualify; "could" and "card" touch % and could match inside longer words like "cards". Because those remaining words are common, LIKE alone skips little, so we send hasToken for each word and keep LIKE to verify the phrase.

Newer versions also support partial words: ClickHouse scans the index dictionary (the sorted distinct words in each part) instead of every row, then reads only matching posting lists:

  • ClickHouse 26.4 added substring patterns such as LIKE '%charg%'. Because splitByNonAlpha splits on everything that is not a letter or digit, an alphanumeric pattern only matches inside one word, so the dictionary lookup is exact (matching "charge" and "charged").
  • ClickHouse 26.9 added prefix and suffix patterns ('charg%', '%card') as a first filter, re-checked against the rows.
  • Limits: both work only with the splitByNonAlpha or array tokenizers, require at least 4 characters by default, and fall back to reading rows if too many words with long posting lists match. LIKE also needs an index without a preprocessor, so on our lowercased index only ILIKE would qualify. We have not tried either feature on our tables.

How we added it

As soon as the text index was available, we added it to the table template that every new log table is created from:

INDEX idx_message_fts_case_insensitive message
  TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = lower(message))

Two choices matter here. splitByNonAlpha splits on non-alphanumeric characters, turning "user_id=42" into "user", "id", and "42". lower(message) lowercases both indexed text and search terms, making our existing hasToken queries case-insensitive with no translator changes.

Template changes only cover new tables. On existing tables, ALTER TABLE ... ADD INDEX applies only to new parts. Backfilling old parts requires MATERIALIZE INDEX, a mutation across the whole table that competes with live searches.

Dropping the old token filter

Episode 8 ended with one slow search on a customer table that had both the new text index and the old 512 KiB token bloom filter on message. Here are the full cold-cache results, including the run with no indexes:

  • No data skipping indexes: 24.6 seconds.
  • Only the token bloom filter: 29.8 seconds.
  • All indexes together: 23.4 seconds.
  • Only the text index: 10.0 seconds.

Leaving the old token filter beside the text index erased most of the gain. We dropped it from that table and from our template. With a warm cache, that search dropped to 1.5 seconds.

Four searches, on and off

To test the text index across the customer's workload, we ran four typical searches with a cold cache, first with all data skipping indexes off, then with them on. The old token filter was already gone, so "on" means the text index plus small bloom filters on columns like log level and customer ID:

  • A rare word: 31.4 seconds off, 0.7 seconds on.
  • Words appearing in some logs, plus a few filters: 10.0 seconds off, 5.9 seconds on.
  • An error code and an account ID: 18.7 seconds off, 10.7 seconds on.
  • A phrase of five very common words: 13.0 seconds off, 18.5 seconds on (slower).

EXPLAIN indexes = 1 shows how many granules each index left. In all four searches, the primary index first narrowed the search to the time range. Then the text index ruled out most of what was left: every granule for the rare word, and 91.5% for the common-word phrase. With nothing left to read, the rare-word search never touched the message column, which is why it took 0.7 seconds. The common-word search also skipped most granules, yet it got slower. The next section explains why.

When it costs more than it saves

The fourth search counted logs by level for five common words ("Successfully processed message from offset") and one customer ID over 17 hours:

SELECT level, count()
FROM logs
WHERE hasToken(message, 'Successfully')
  AND hasToken(message, 'processed')
  AND hasToken(message, 'message')
  AND hasToken(message, 'from')
  AND hasToken(message, 'offset')
  AND message LIKE '%Successfully processed message from offset%'
  AND customer_id = '...'
  AND timestamp >= ... AND timestamp < ...
GROUP BY level

On ClickHouse 26.4 or later, hasPhrase can replace the five hasToken calls and the LIKE. It uses the text index for every word and checks that they appear in this order:

WHERE hasPhrase(message, 'Successfully processed message from offset')
  AND customer_id = '...'
  AND timestamp >= ... AND timestamp < ...

EXPLAIN indexes = 1 shows each index in the order ClickHouse checked it:

  • Primary index (time range): 106,932 granules left (a timestamp minmax index trimmed 19 more, to 106,913).
  • Text index on message: 9,062 left. Working per part, it ruled out 5 of 8 parts, but all five words appeared in the other 3.
  • Bloom filter on log level: 7,901 left.
  • Bloom filter on customer ID: 0 left.

The customer ID bloom filter alone would have skipped every granule. The 18.5 seconds went into index overhead. hasToken needs the full posting list of each word, and these five words were in most rows of the three parts that were left. So with a cold cache, ClickHouse first fetched five long posting lists from object storage, and only then could it skip anything. With no indexes, the search took 13.0 seconds. Disabling only the text index was worse (20.6 seconds), because the customer ID filter then had to check all 106,913 granules instead of 9,062. We did not record how many bytes those posting lists were.

ClickHouse engineers describe the same cost in their post on how they designed the text index for object storage. Reading posting lists "is not free; it requires seeks and decompression". If a word is in 80% of rows, the index removes few rows "while still paying the I/O cost for all the rows". The same post says that on object storage, latency, not bandwidth, is the real bottleneck. That is why newer versions estimate, for LIKE patterns, how many rows match before reading any posting list, and skip the index when the estimate is above 20% of the rows in a part. ClickHouse also caches text index headers, tokens, and posting lists to reduce reads.

With a warm cache, the same search took 1.3 seconds with indexes and 6.3 seconds without. We accepted that trade-off. With a cold cache, the indexes made three of the four searches faster. With a warm cache, they made this one faster too.

The storage and compute bill

The text index has two costs: storage, and the work to rebuild it again and again.

On the table above, the text index is about a third of the whole table's compressed size (34% in June, and about the same when I checked again months later). That is twice the size of the compressed message column it indexes. Before compression, the message text is more than six times larger than its index. But log text compresses about 13 times, while the index hardly compresses at all. The other 18 data skipping indexes on that table add up to less than 0.1%.

An inverted index stores every distinct token and every row it appears in, and logs are full of unique IDs, timestamps, hostnames, and numbers. Newer ClickHouse versions add postprocessors to drop stop words or long hashes, and preprocessors can strip timestamps or UUIDs before tokenization, though we have not tuned ours that way.

The compute cost is easy to miss because ClickHouse pays it in the background, and the index is not built just once. ClickHouse builds a text index for every new part on insert, and builds it again every time parts merge into a bigger one. On the ClickHouse service where the table resides, each row we insert is merged 12 to 16 times on average before it settles in its final part. Every one of those merges rebuilds the text index for that row.

On the table above, the text index is about a third of the table's bytes. So roughly a third of what merges write back to object storage, a dozen or more times per row, is the text index. The CPU share is smaller: building the text index took about 8% of all merge time over the same windows. ClickHouse merges the sorted dictionaries of the source parts in one sequential pass and remaps the posting lists, without reading the text column again, which keeps the CPU cost down.

Even with those costs, we kept it: it made most free-text searches fast and replaced a token filter that made them slower.

What about JSON columns?

Since ClickHouse 26.4, the text index also works on JSON columns. A text index on JSONAllValues(log) covers the values of every field, without knowing the paths ahead of time. On ClickHouse 26.12, I checked which searches use it:

  • Words in one field: hasToken(log.title, 'timeout') or log.message LIKE '%charg%'.
  • Words or a phrase in any field: hasAnyTokens(JSONAllValues(log), ['timeout']) or hasPhrase(JSONAllValues(log), 'could not charge').
  • Not covered: part of a word in any field. toString(log) LIKE '%charg%' still reads every row.

Before 26.4, we added a String copy of the JSON column (log_str) on one customer's table to avoid toString(log). Today I would start with a text index on JSONAllValues(log), and add a String copy only if users need partial-word search across all fields.

What I check now

Before adding a text index to log tables, I check seven things:

  • Start with the text index for free-text search, not a token bloom filter.
  • Pick the tokenizer and case handling up front; changing them means rebuilding the index.
  • Drop any old token bloom filter on the same column, or it can cancel out the speedup.
  • Measure storage and merge overhead on a real table: unique tokens drive size, and merges rewrite the index many times.
  • Test common-word searches with a cold cache, where long posting lists can slow queries down.
  • Keep plain bloom filters for rare exact values (trace ID, customer ID) on columns outside the sort key.
  • For JSON logs on ClickHouse 26.4 or later, start with a text index on JSONAllValues(log) before adding a String copy of the payload.

What's next?

Episode 10 will be the finale of this series: answering the original question of why we moved our logs off ClickHouse, and when we would pick it again.

See your own telemetry in Oodle

Start debugging in minutes.

Start freeBook a demo

Get new posts by email

Engineering write-ups from the team.