Skip to content

Report vector index use for pgvector searches - #414

Merged
iskakaushik merged 1 commit into
mainfrom
vector-index-use
Oct 19, 2026
Merged

iskakaushik merged 1 commit into
mainfrom
vector-index-use

Conversation

@iskakaushik

@iskakaushik iskakaushik commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator

What

ClickHouse serves a nearest neighbor search from a vector similarity index only for some query shapes. Otherwise it compares every row, and nothing tells the user. This PR makes pg_clickhouse report which case a pgvector search falls into:

try=# EXPLAIN (VERBOSE, COSTS OFF) SELECT id FROM items ORDER BY embedding <=> '[1,0]' LIMIT 5;
WARNING:  pg_clickhouse: vector search on "items" will not use a ClickHouse vector index
DETAIL:  index "items_idx" uses L2Distance (<->), not cosineDistance
HINT:  set pg_clickhouse.vector_planner_warnings = off to hide this warning.
                                                                 QUERY PLAN
--------------------------------------------------------------------------------------------------------------------------------------------
 Foreign Scan on public.items
   Output: id, (embedding <=> '[1,0]'::vector)
   Vector Search: cosineDistance on embedding
   Vector Index: none
   Vector Index Not Used: index "items_idx" uses L2Distance (<->), not cosineDistance
   Remote SQL: SELECT id, embedding FROM try.items ORDER BY cosineDistance(embedding, cast([1,0] as Array(Float32))) ASC NULLS LAST LIMIT 5
(6 rows)

It adds:

  • Vector Search, Vector Index, and Vector Index Not Used lines in EXPLAIN
  • a planner warning when no index applies, with the reason in the DETAIL, silenced by pg_clickhouse.vector_planner_warnings = false
  • pg_clickhouse.vector_metadata_ttl (default 60 seconds) and clickhouse_refresh_vector_metadata() for the index metadata cache

How it works

  • src/vector_plan.c: chfdw_vector_plan_info() runs in clickhouseGetForeignPlan() for a base rel whose first query pathkey is a pgvector distance on one of its columns. It checks, in order: whether the ORDER BY pushed down, the server version (25.8+), whether a LIMIT pushed down, the number of sort keys, the direction (<#> sorts as dotProduct DESC), an index on the column with the same metric, and max_limit_for_vector_search_queries. The result goes in a new fdw_private slot after the settings slot, for EXPLAIN.
  • src/vector_meta.c: reads system.data_skipping_indices and the effective max_limit_for_vector_search_queries in one query. It runs in an internal subtransaction, so any error, including an unreachable server, leaves the search unclassified instead of failing planning. Results are cached per backend in CacheMemoryContext, keyed by foreign table and user. The lookup happens only when planning a scan sorted by a pgvector distance, and only on a cache miss, so it costs one small query per table and user per TTL. ClickHouse has no unquoteIdentifier() in any version CI tests, so the query strips the backticks it puts around some column names with replaceRegexpAll().
  • Nothing is stored in Postgres, so indexes created directly in ClickHouse are seen too, after the TTL or clickhouse_refresh_vector_metadata().
  • The classification only drives EXPLAIN and the warning. It never changes the remote SQL or the results.

Notes for review

  • The query helper chfdw_run_text_query() now lives in pglink.c and chfdw_construct_create_tables() uses it too, rather than keeping two copies.
  • This adds a SQL function, so it bumps the extension to 0.12 with sql/pg_clickhouse--0.11--0.12.sql. The CHANGELOG section is still titled v0.11.1; it should probably become v0.12.0, but I left that to you.
  • The warning about an old server is issued once per server per backend (warned_old_servers). The others are issued at each planning, like other planner warnings.
  • vector_pushdown.sql turns the warnings off, since it tests pushdown, and gains vector_pushdown_3.out for ClickHouse 23.8–25.3, where EXPLAIN reports that the server is too old for indexes.
  • vector_index_use.sql creates its indexes directly in ClickHouse and covers each fallback reason, cache refresh with a long TTL, a column name ClickHouse quotes in backticks, and a server that is down.
  • Fixed a leak in the metadata cache: each refresh replaced the cached index list without freeing it (about 300 B per refresh, every query with a TTL of 0), and entries for dropped tables never went away. Each entry now has its own memory context, freed when it refreshes, and a lookup that fetches also evicts other entries older than the TTL.

@iskakaushik
iskakaushik marked this pull request as ready for review October 15, 2026 21:43
@iskakaushik
iskakaushik requested a review from serprex October 15, 2026 21:43
Comment thread src/vector_meta.c Resolved
Comment thread doc/pg_clickhouse.md Resolved
Comment thread doc/pg_clickhouse.md Resolved
Comment thread doc/pg_clickhouse.md Resolved
Comment thread src/include/fdw.h Resolved
Comment thread src/deparse.c Resolved
Comment thread src/fdw.c
makeString(sql.data),
retrieved_attrs,
settings,
chfdw_vector_plan_info(root, foreignrel, best_path, has_limit)

@theory theory Oct 16, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

So we bear the overhead of the vector plan info anytime a query has a vector distance expression? And that overhead requires an additional query sent to ClickHouse unless the data is in the cache?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Yes, but only for a scan sorted by a pgvector distance, and only on a cache miss: one small query per table and user every vector_metadata_ttl seconds (60 by default). Other queries pay nothing. I can't skip it when warnings are off, because EXPLAIN also shows the index name and the plan doesn't know whether it will be explained. I documented the cost in the Vector Index Use section instead.

Comment thread src/option.c

DefineCustomBoolVariable(
"pg_clickhouse.vector_planner_warnings",
"Warn when a vector search cannot use a ClickHouse vector index.",

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Might we want to extend this to support any index in the future?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Possibly, but I kept the name. The checks and reasons are specific to vector similarity indexes, and someone may want to silence them apart from warnings about other indexes. If we add those later, they can get their own GUC, or this one can be folded into it.

Comment thread src/option.c Resolved
Comment thread src/vector_meta.c Resolved
Comment thread src/vector_meta.c Resolved
Comment thread src/vector_meta.c Resolved
Comment thread src/vector_meta.c Resolved
Comment thread src/vector_meta.c Resolved
Comment thread src/vector_meta.c Resolved
Comment thread src/vector_meta.c

chfdw_remote_table_name(relid, &db, &table);

/* A failed lookup must not fail the query, so run it in a subtransaction */

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

So we call this function and start a sub transaction any time the planner only when ordering by a pgvector column and when EXPLAINing the plan or explaining the failure to use an index in a warning? How does it know when it can't use an index?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Yes. The planner calls it only when a scan is sorted by a pgvector distance, and it starts a subtransaction only on a cache miss, so once per table and user per TTL. It decides that an index can't be used in fallback_reason(), from the query shape (pushdown, LIMIT, sort keys, direction) and the indexes that ClickHouse reports in system.data_skipping_indices. I added the cost to the docs.

Comment thread src/vector_plan.c Resolved
Comment thread test/sql/vector_index_use.sql Resolved
Comment thread test/expected/vector_index_use.out Resolved
Comment thread test/expected/vector_index_use.out Resolved
Comment thread test/expected/vector_index_use.out Resolved
@theory theory added enhancement New feature or request pushdown Improvements to query pushdown data types Improve data type support labels Oct 19, 2026
ClickHouse serves a nearest neighbor search from a vector similarity index
only for some query shapes: a single ascending sort by the index's
distance function, with a `LIMIT` no higher than
`max_limit_for_vector_search_queries`, on ClickHouse 25.8 or later.
Otherwise it compares every row, and nothing tells the user.

So teach the planner to recognize these searches. For a scan sorted by a
pgvector distance on a foreign table column, `chfdw_vector_plan_info()`
checks the query shape against the indexes ClickHouse reports in
`system.data_skipping_indices` and records the result in `fdw_private`.
`EXPLAIN` then shows the distance function, the index, and, when no index
applies, why not as `Vector Index Not Used`. The planner also warns in
that case, with the reason in the `DETAIL`, once per server for old
servers. Set `pg_clickhouse.vector_planner_warnings` to false to silence
the warnings.

pg_clickhouse stores no index metadata. It reads it from ClickHouse in a
subtransaction, so that a failure, such as an unreachable server, leaves
the search unclassified rather than failing the query. It does so only
when planning such a search, and caches the result per backend for
`pg_clickhouse.vector_metadata_ttl` seconds. Since only vector metadata
is cached, `clickhouse_refresh_vector_metadata()` clears the cache. The
new function requires extension version 0.12. ClickHouse has no
`unquoteIdentifier()` in any version we test, so the query strips the
backticks it puts around column names that need them with
`replaceRegexpAll()`.

Move the text-row query out of `chfdw_construct_create_tables()` into
`chfdw_run_text_query()` and use it for both, rather than add a second
implementation. Also export `chfdw_remote_table_name()` and
`chfdw_rel_user_mapping()` from `deparse.c` for the metadata lookup,
silence the warnings in `vector_pushdown.sql`, which tests pushdown rather
than index use, and add `vector_pushdown_3.out` for ClickHouse 23.8
through 25.3, where `EXPLAIN` reports that the server is too old for
indexes. Adapt `vector_distance()` to the operators that deparse as
ClickHouse functions.

Co-authored-by: Philip Dubé <159546+serprex@users.noreply.github.com>
@iskakaushik
iskakaushik merged commit 45e260a into main Oct 19, 2026
30 checks passed
@iskakaushik
iskakaushik deleted the vector-index-use branch October 19, 2026 20:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

data types Improve data type support enhancement New feature or request pushdown Improvements to query pushdown

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants