quanglee/ field notes
← field notes
coderevised 12 nov 2614 min4 live figures#clickhouse#search#vectors#infra

Vector search and BM25 in ClickHouse, compared with Postgres, Qdrant and the rest

How the ClickHouse vector index works, how to set it up, where it stands on BM25 and hybrid search, and how it compares with pgvector, Qdrant, Elasticsearch, Milvus and Weaviate. The last section compares what coding and research agents get from grep and from vector search.



  1. brute force first
  2. the vector_similarity index
  3. setting it up
  4. filters
  5. qbit
  6. bm25
  7. hybrid search with rrf
  8. how the others do it
  9. the same hybrid query on three other systems
  10. benchmarks
  11. do agents still need vector search

ClickHouse made its vector index generally available in 25.8 (August 2025)1 and its full-text index in 26.2 (March 2026)2. Both live inside the normal MergeTree table, next to the logs and events most people already keep there. This post covers how the two indexes work, how to turn them on, what they can’t do yet, and how they compare with the search systems people usually pick. Versions are the ones current on 11 November 2026: ClickHouse 26.10, pgvector 0.8.7, Qdrant 1.20, Elasticsearch 9.5, OpenSearch 3.9, Milvus 3.0 and Weaviate 1.40.

brute force first

ClickHouse has no vector type. An embedding is a column of Array(Float32) (or BFloat16), and the distance functions are ordinary SQL functions: L2Distance, cosineDistance, dotProduct. Exact nearest-neighbour search is a sort:

SELECT id, title
FROM docs
ORDER BY cosineDistance(embedding, {q:Array(Float32)})
LIMIT 10;

This reads every vector in the table. ClickHouse reads columns fast and on every core, so up to a few million rows this is often fine, and the answer is exact. I’d start here and add the index when the scan gets too slow.

the vector_similarity index

The approximate index is HNSW, built on the usearch library1. If you want to understand how HNSW itself works, I wrote it up in how HNSW works, with the graph, the layers and why inserts are expensive. It went experimental, then beta in 25.5, then GA in 25.8, which also removed the older annoy and usearch index types. Since 25.8 it needs no experimental setting.

ClickHouse stores a table as parts, immutable chunks written by each insert. Its secondary indexes are called skip indexes. The usual kind keeps a small summary of each block of rows, such as the block’s minimum and maximum, so a query can skip blocks that can’t match3. A skip index is stored inside a part and, by default, built when the part is written. The vector index is one more skip index type, vector_similarity, and what it stores is an HNSW graph over the part’s vectors. So each part gets its own small HNSW graph, and a query searches every part’s graph and merges the top results.

You don’t schedule merges. ClickHouse keeps picking a few small parts of the same partition in the background and merges them into one larger part, until parts reach about 150 GB4; OPTIMIZE TABLE forces one. A merge reads the rows of its input parts and writes them out as a new part, and it recreates the new part’s skip indexes from the merged columns4. For a vector index, that means every vector of the new part goes into an empty graph; the graphs of the old parts are not reused. Queries keep using the old parts and their graphs until the new part is written. Then the old parts are marked inactive and deleted after a configurable delay, eight minutes by default4. By default, a row is indexed when it is inserted, and again in every merge it goes through. ClickHouse’s own RFC on the next version of the index lists this rebuild-on-merge as the main cost5.

Three parts appear one after another, each holding nine vectors joined into a small neighbour graph. A query vector then sends a line to each part, and the two nearest points in each part light up; the results from all parts are merged. Finally parts 1 and 2 merge into one bigger part: their two graphs disappear and a new graph over all eighteen points is drawn from scratch.

fig 1Each part has its own graph, and a merge builds a new one. Real HNSW graphs have several layers and far more points; the points here are random and each one links to its two nearest neighbours, with separate pieces joined by their shortest gap so the drawing stays connected.Based on the ClickHouse vector index docs and RFC #104122.

A few things follow from that design:

The index stores vectors in bf16 by default. The other options are f64, f32, f16, i8 and b1 (one bit per dimension). With i8 or b1, turn on vector_search_with_rescoring, which recomputes the final distances on the full-precision column. The 26.7 release added experimental quantized column codecs (int8, RaBitQ, TurboQuant, PQ and a Matryoshka truncation) behind enable_quantized_codec6.

setting it up

A server from Docker is enough to try it:

docker run -d --name ch -p 8123:8123 -p 9000:9000 \
  -e CLICKHOUSE_PASSWORD=dev clickhouse/clickhouse-server:26.10
docker exec -it ch clickhouse-client --password dev

A table with both indexes. The vector index arguments are the method, the distance, the number of dimensions, the quantization, M (links per node) and ef_construction (how hard the build searches for neighbours):

CREATE TABLE docs
(
    id        UInt64,
    title     String,
    body      String,
    body_lc   String MATERIALIZED lower(body),
    embedding Array(Float32) CODEC(NONE),
    INDEX vec_idx embedding TYPE vector_similarity('hnsw', 'cosineDistance', 1024, 'bf16', 32, 128),
    INDEX txt_idx body_lc TYPE text(tokenizer = splitByNonAlpha)
)
ENGINE = MergeTree
ORDER BY id;

CODEC(NONE) is what the docs recommend for the vector column, since float vectors barely compress. Every array you insert must have exactly 1,024 values or the insert fails. On a table that already has data and was created without the index, add it and build it for the existing parts:

ALTER TABLE docs ADD INDEX vec_idx embedding TYPE vector_similarity('hnsw', 'cosineDistance', 1024);
ALTER TABLE docs MATERIALIZE INDEX vec_idx SETTINGS mutations_sync = 2;

Loading embeddings from Python with clickhouse-connect and a sentence-transformers model (BGE large gives 1,024 dimensions):

import clickhouse_connect
from sentence_transformers import SentenceTransformer

model = SentenceTransformer("BAAI/bge-large-en-v1.5")
ch = clickhouse_connect.get_client(host="localhost", password="dev")

rows = [
    (1, "ClickHouse vectors", "HNSW index inside a column store"),
    (2, "Postgres pgvector", "pgvector adds a vector type to Postgres"),
]
vecs = model.encode([body for _, _, body in rows], normalize_embeddings=True)
ch.insert(
    "docs",
    [(*row, vec.tolist()) for row, vec in zip(rows, vecs)],
    column_names=["id", "title", "body", "embedding"],
)

q = model.encode("vector search in a column store", normalize_embeddings=True).tolist()
result = ch.query(
    """SELECT id, title, cosineDistance(embedding, {q:Array(Float32)}) AS d
       FROM docs ORDER BY d LIMIT 10""",
    parameters={"q": q},
)
print(result.result_rows)

The query settings that matter, and the check that the index is used:

SELECT id, title, cosineDistance(embedding, {q:Array(Float32)}) AS d
FROM docs
ORDER BY d ASC              -- ASC for L2 and cosine, DESC for dotProduct
LIMIT 10
SETTINGS hnsw_candidate_list_size_for_search = 512;   -- ef_search, 256 by default: higher means better recall and slower

EXPLAIN indexes = 1
SELECT id FROM docs ORDER BY cosineDistance(embedding, {q:Array(Float32)}) LIMIT 10;
-- look for "Skip ... Name: vec_idx" in the plan

If writes are heavy, materialize_skip_indexes_on_insert = 0 defers building the graph to merge time, and materialize_skip_indexes_on_merge = 0 defers it further, until you run MATERIALIZE INDEX yourself. Parts without a graph are searched exactly.

filters

The default filter strategy is post-filtering: the index returns the k nearest rows of each part, then the WHERE clause runs on them. If the filter matches few rows, most of the k get thrown away and the query returns fewer than k results. There are two settings to fix it1. vector_search_index_fetch_multiplier makes the index return more candidates (up to 1,000 times k), and vector_search_filter_strategy = 'prefilter' applies the filter first and computes exact distances on the rows that pass. The default 'auto' picks between the two using the filter’s estimated selectivity.

Two hundred candidate rows are drawn as squares in order of distance to the query, nearest first. Filled squares match the WHERE filter. With a filter that matches 20% of rows, post-filtering fetches the nearest 10 and only 2 of them survive. Fetching 40 returns 8. Prefiltering scans every matching row exactly and returns all 10. With a 5% filter the numbers are 0, 1 and 10.

fig 2The outlined squares are what the index fetches, and the coloured ones are the rows returned. Toggle the strategy and how much of the table the filter matches. The rows are random, seeded so every toggle shows the same table.k = 10. Settings from the ClickHouse vector index docs.
SELECT id, title, cosineDistance(embedding, {q:Array(Float32)}) AS d
FROM docs
WHERE title ILIKE '%postgres%'
ORDER BY d
LIMIT 10
SETTINGS vector_search_index_fetch_multiplier = 4;
-- or, for very selective filters: vector_search_filter_strategy = 'prefilter'

If the filter is on a column in the table’s ORDER BY key (a tenant id, a date), the primary index prunes whole granules before the vector search, which is the cheapest filter ClickHouse has. Qdrant and Weaviate check filters while walking the graph, so they keep returning k results under selective filters without either trick7.

qbit

QBit is a column type, production-ready since 26.2, that stores a vector bit plane by bit plane: all the sign bits, then all the next bits, and so on8. A query picks how many planes to read, so the precision becomes a query parameter. One informal test in the announcement, on 10 million DBpedia vectors, went from 1.157 s to 0.271 s and from 6.05 GiB to 740 MiB of memory at reduced precision.

CREATE TABLE docs_q (id UInt64, vec QBit(Float32, 1024)) ENGINE = MergeTree ORDER BY id;

SELECT id
FROM docs_q
ORDER BY L2DistanceTransposed(vec, {q:Array(Float32)}, 12)   -- read 12 of the 32 bit planes
LIMIT 10;

QBit is a brute-force tool with no graph. It suits tables where the HNSW memory bill is too high and a few hundred milliseconds per query is acceptable. 26.7 added Int8 elements and a stride argument6.

bm25

ClickHouse has no BM25 today. The text index is an inverted index: it maps each token to the rows that contain it and speeds up hasToken, hasAnyTokens, hasAllTokens, hasPhrase, LIKE, match and =. It finds rows; it doesn’t score them. The GA post says so directly: the text index “is not a relevance engine”2. On 10 billion GitHub events, a token search went from 193 s to 0.42 s with the index, which took 216 GiB and cut insert throughput by about half.

BM25 is coming. Pull request #117519 adds a bm25([k1, b]) scoring function behind allow_experimental_text_index_scoring, and draft #125775 stores the per-part statistics it needs (document count, average length, document frequency), pointing at 26.119. Until then, the formula fits in one query. The text index narrows the candidates, and the scoring runs on them:

WITH
    ['vector', 'index'] AS q,
    (SELECT count() FROM docs) AS N,
    (SELECT avg(length(tokens(body_lc))) FROM docs) AS avgdl,     -- store this in production
    [(SELECT count() FROM docs WHERE hasToken(body_lc, 'vector')),
     (SELECT count() FROM docs WHERE hasToken(body_lc, 'index'))] AS df,
    1.2 AS k1,
    0.75 AS b
SELECT
    id,
    title,
    arraySum(arrayMap((t, n) ->
        log(1 + (N - n + 0.5) / (n + 0.5))
        * countEqual(toks, t) * (k1 + 1)
        / (countEqual(toks, t) + k1 * (1 - b + b * length(toks) / avgdl)),
        q, df)) AS bm25
FROM
(
    SELECT id, title, tokens(body_lc) AS toks
    FROM docs
    WHERE hasAnyTokens(body_lc, ['vector', 'index'])
)
ORDER BY bm25 DESC
LIMIT 50;

tokens() splits on non-alphanumeric characters, the same rule as the splitByNonAlpha tokenizer on the index, so the counts agree with what the index matched. The avgdl subquery scans the whole column; in production keep it in a small table that a materialized view updates on insert. Tinybird published a repository with the same idea plus hybrid search10.

hybrid search with rrf

Keyword search finds exact terms (an error code, a function name), and vector search finds paraphrases. Reciprocal rank fusion (RRF) combines the two rankings: each document scores the sum of 1 / (60 + rank) over the lists it appears in. A document in both lists beats one that tops only one list. In Anthropic’s Contextual Retrieval tests, their contextual embeddings cut the top-20 retrieval failure rate by 35%, adding BM25 to them brought the cut to 49%, and adding a reranker brought it to 67%11.

A BM25 ranking and a vector ranking of five documents each, and their fused ranking. Three documents appear in both lists (hnsw tuning, vector index docs, merge settings) and take the top three fused places with scores near 0.031. The BM25 winner, err_42 runbook, drops to fourth with 0.0164.

fig 3Dots mark the documents both lists found. Hover a fused row to see its sum. I made the documents up; the arithmetic is the real RRF formula with k = 60.Cormack, Clarke and Büttcher, SIGIR 2009.

ClickHouse has no fusion operator yet (RFC #105781 proposes a hybridSearch function12), so RRF is two CTEs and a GROUP BY:

WITH
    vec AS (
        SELECT id, row_number() OVER (ORDER BY d) AS r
        FROM (SELECT id, cosineDistance(embedding, {q:Array(Float32)}) AS d
              FROM docs ORDER BY d LIMIT 50)
    ),
    kw AS (
        SELECT id, row_number() OVER (ORDER BY bm25 DESC) AS r
        FROM ( /* the BM25 query above */ )
    )
SELECT id, sum(1 / (60 + r)) AS rrf
FROM (SELECT id, r FROM vec UNION ALL SELECT id, r FROM kw)
GROUP BY id
ORDER BY rrf DESC
LIMIT 10;

how the others do it

ClickHouse 26.10Postgres + pgvector 0.8.7Qdrant 1.20Elasticsearch 9.5 / OpenSearch 3.9Milvus 3.0Weaviate 1.40
ANN indexHNSW per part, in RAMHNSW, IVFFlat; DiskANN through pgvectorscaleHNSWHNSW, DiskBBQ (ES); Faiss, Lucene, JVector (OS)HNSW, IVF, DiskANN, GPU CAGRA and moreHNSW, flat, dynamic, HFresh
compressionbf16, i8, b1; QBithalfvec, bit with re-rankint8, binary, PQ, TurboQuantint8, int4, BBQ (ES); 32× on disk (OS)SQ, PQ, RaBitQPQ, BQ, SQ, RQ
filtered searchpost-filter or exact prefilterpost-filter plus iterative scansfilters inside the graph walkfilters inside the graph walkfilters inside the graph walkfilters inside the graph walk
BM25no (PR open)not in core; pg_textsearch, ParadeDB pg_search, VectorChord-bm25yes, native since 1.20yes, the default rankingyes, BM25 functionyes, BM25F
hybridRRF by hand in SQLRRF by hand in SQLserver-side RRF or DBSFRRF retriever (ES), hybrid query (OS)hybrid_search, RRF or weightedbuilt in, alpha-weighted
scale-outsharded, columnarone primary plus replicasshardedshardedsharded on Kubernetessharded
licenceApache-2.0PostgreSQLApache-2.0ELv2/AGPL (ES), Apache-2.0 (OS)Apache-2.0BSD-3

Sources for the table: each project’s docs and release notes131415161718.

Postgres’s built-in ts_rank is not BM25: it has no inverse document frequency and no length normalisation of the BM25 kind19. For real BM25 there are three extensions. Tiger Data’s pg_textsearch (PostgreSQL licence) is on Google’s AlloyDB and Cloud SQL since September 202620. ParadeDB’s pg_search wraps the Tantivy engine and is AGPL21. VectorChord-bm25 comes from the VectorChord team22.

Until 1.20, Qdrant did BM25 through sparse vectors with an IDF modifier. Version 1.20 (October 2026) added native BM25 scoring on a text payload index. Its statistics are per shard, so scores across shards are approximate15.

A few more worth knowing:

the same hybrid query on three other systems

Postgres with pgvector and pg_textsearch. <@> returns a negative BM25 score, so ascending order puts the best match first:

CREATE EXTENSION vector;
CREATE EXTENSION pg_textsearch;

CREATE TABLE docs (id bigserial PRIMARY KEY, body text, embedding vector(1024));
CREATE INDEX ON docs USING hnsw (embedding vector_cosine_ops) WITH (m = 16, ef_construction = 64);
CREATE INDEX ON docs USING bm25 (body) WITH (text_config = 'english');

SET hnsw.ef_search = 100;
SET hnsw.iterative_scan = relaxed_order;   -- keep scanning when a WHERE filter drops rows

WITH v AS (
    SELECT id, row_number() OVER (ORDER BY embedding <=> $1) AS r
    FROM docs ORDER BY embedding <=> $1 LIMIT 50
), k AS (
    SELECT id, row_number() OVER (ORDER BY body <@> 'vector index') AS r
    FROM docs ORDER BY body <@> 'vector index' LIMIT 50
)
SELECT id, sum(1.0 / (60 + r)) AS rrf
FROM (SELECT * FROM v UNION ALL SELECT * FROM k) u
GROUP BY id
ORDER BY rrf DESC
LIMIT 10;

Qdrant, with a dense vector and a BM25 sparse vector fused on the server. pip install "qdrant-client[fastembed]" and docker run -p 6333:6333 qdrant/qdrant:

from qdrant_client import QdrantClient, models

client = QdrantClient("localhost", port=6333)
client.create_collection(
    "docs",
    vectors_config={"dense": models.VectorParams(size=1024, distance=models.Distance.COSINE)},
    sparse_vectors_config={"bm25": models.SparseVectorParams(modifier=models.Modifier.IDF)},
)

client.upsert("docs", points=[
    models.PointStruct(
        id=1,
        vector={
            "dense": dense_vec,  # your 1,024-d embedding
            "bm25": models.Document(text="HNSW index inside a column store", model="Qdrant/bm25"),
        },
        payload={"title": "ClickHouse vectors"},
    ),
])

hits = client.query_points(
    "docs",
    prefetch=[
        models.Prefetch(query=dense_query, using="dense", limit=50),
        models.Prefetch(query=models.Document(text="vector index", model="Qdrant/bm25"), using="bm25", limit=50),
    ],
    query=models.FusionQuery(fusion=models.Fusion.RRF),
    limit=10,
)

Elasticsearch, with BBQ-quantized HNSW and the RRF retriever:

PUT docs
{
  "mappings": {
    "properties": {
      "body": { "type": "text" },
      "vec":  { "type": "dense_vector", "dims": 1024, "similarity": "cosine",
                "index_options": { "type": "bbq_hnsw" } }
    }
  }
}

GET docs/_search
{
  "retriever": {
    "rrf": {
      "retrievers": [
        { "standard": { "query": { "match": { "body": "vector index" } } } },
        { "knn": { "field": "vec", "query_vector": [0.12, -0.03], "k": 10, "num_candidates": 100 } }
      ]
    }
  }
}

The query_vector is cut to two numbers here; send all 1,024.

benchmarks

No public benchmark includes the ClickHouse vector index. It’s absent from Zilliz’s VDBBench leaderboard and from ann-benchmarks, and the ClickHouse docs publish no recall/QPS table for 25.8 or later. The closest number is in a pull request: 0.985 recall at about 2,750 QPS on Deep10M30. Every comparison below was run by a company selling one of the systems.

Queries per second against recall on VDBBench's Cohere 1M × 768 case. Zilliz Cloud: 13,316 QPS at 0.938 recall, p99 2.0 ms. Milvus on 16 cores: 5,973 at 0.919. OpenSearch: 3,055 at 0.907. Elastic Cloud: 2,354 at 0.914. Qdrant Cloud: 1,242 at 0.947, the highest recall. Pinecone: 1,147 at 0.926. ClickHouse is not on the board.

fig 4Throughput against recall. Recall is not matched across systems, so a point further right is doing a harder job. The two dark points are Zilliz's own products. ClickHouse isn't on the board. Hover a point for p99 latency.Zilliz VDBBench leaderboard, read on 11 November 2026. Zilliz makes Milvus and Zilliz Cloud.

Other published comparisons:

Each vendor wins its own benchmark. VDBBench is open source and runs against your own data, which is the only result I’d trust for a decision.

Claude Code started with a RAG index built on Voyage embeddings and replaced it with plain glob and grep. Boris Cherny gave two reasons on Latent Space: the index has to be stored and secured somewhere, and it drifts out of date while the code changes. He called the evidence “mostly vibes” plus internal benchmarks35. Augment found grep and find enough for their SWE-bench agent36, and Letta’s agent scored 74.0% on the LoCoMo memory benchmark keeping its memory in plain files37.

Other measurements go the other way. Cursor added semantic search next to grep and measured 12.5% higher answer accuracy on their internal benchmark, and 2.6% more of the agent’s code kept by users on codebases over 1,000 files38. On BrowseComp-Plus, a deep-research benchmark with a fixed corpus, GPT-5 answered 55.9% of questions with a BM25 retriever and 70.1% with Qwen3-Embedding-8B, and made fewer search calls with the embeddings39. Anthropic’s own guide to context engineering recommends just-in-time retrieval with tools, and says a hybrid of that and up-front retrieval may work best40.

Both results hold for their setting. Code is full of exact identifiers that grep finds in one call, and the files change while the agent works. A document collection written in many words for the same idea is the opposite case, and that’s where embeddings win. The Contextual Retrieval post also gives the small-corpus rule: under about 200,000 tokens, put the whole thing in the prompt and skip retrieval11.

My view is that vector search stopped being the fixed first step of every pipeline and became one tool the agent calls, next to grep and keyword search. For an agent over code, grep first. Over a large document collection, I’d give it a hybrid search tool with BM25, embeddings and RRF. If the data already sits in ClickHouse I’d build that tool there with the SQL above and move to native BM25 when the PR lands. If it doesn’t, I’d start with Postgres, pgvector and pg_textsearch, and move to Qdrant once filtered queries or scale need a dedicated service.

sources
  1. ClickHouse docs, exact and approximate vector search (read 11 November 2026)
  2. ClickHouse, full-text search is generally available (10 March 2026)
  3. ClickHouse docs, data skipping indexes (read 12 November 2026)
  4. ClickHouse docs, part merges (read 12 November 2026)
  5. ClickHouse issue #104122, RFC for the next vector index
  6. ClickHouse 26.7 release call slides
  7. Qdrant docs, indexing and filterable HNSW
  8. ClickHouse, QBit vector search (27 October 2025) and QBit type docs
  9. ClickHouse PR #117519, BM25 scoring for the text index and draft PR #125775, text index statistics
  10. Tinybird, hybrid search example repository
  11. Anthropic, Introducing Contextual Retrieval (19 September 2024)
  12. ClickHouse issue #105781, RFC for hybrid search
  13. pgvector README and changelog
  14. pgvectorscale
  15. Qdrant 1.20 release post and hybrid queries docs
  16. Elasticsearch dense_vector docs, RRF retriever docs and OpenSearch disk-based vector search
  17. Milvus full-text search docs and index types
  18. Weaviate hybrid search and vector quantization docs
  19. PostgreSQL docs, ranking search results
  20. Tiger Data, pg_textsearch and AlloyDB and Cloud SQL announcement
  21. ParadeDB releases and RRF docs
  22. VectorChord-bm25
  23. Vespa BM25 reference
  24. turbopuffer architecture and hybrid search docs
  25. Pinecone, full-text search is generally available (9 September 2026)
  26. Redis FT.HYBRID
  27. MongoDB $rankFusion
  28. LanceDB hybrid search
  29. DuckDB VSS extension
  30. ClickHouse PR #130214
  31. Tiger Data, pgvector vs Qdrant
  32. MariaDB, vector search benchmark of 10 databases (11 March 2026)
  33. Elastic, BBQ vs OpenSearch FAISS
  34. ClickHouse, log analytics against Elasticsearch (22 May 2026)
  35. Latent Space, Claude Code with Boris Cherny and Cat Wu (7 May 2025)
  36. Jason Liu, why grep beat embeddings in Augment's SWE-bench agent (11 September 2025)
  37. Letta, benchmarking AI agent memory
  38. Cursor, improving agent with semantic search (6 November 2025)
  39. Chen et al., BrowseComp-Plus (arXiv 2508.06600)
  40. Anthropic, effective context engineering for AI agents (29 September 2025)