Skip to content

A platform for community discussion. Free, open, simple.

DEV: Update PG Vector to 0.8.0 (#35156)

Roman Rizzib51b35b5e8a1
diff --git a/plugins/discourse-ai/db/migrate/20251002171950_upgrade_pgvector080.rb b/plugins/discourse-ai/db/migrate/20251002171950_upgrade_pgvector080.rb
new file mode 100644
index 00000000000..86a241cf2c9
--- /dev/null
+++ b/plugins/discourse-ai/db/migrate/20251002171950_upgrade_pgvector080.rb
@@ -0,0 +1,17 @@
+# frozen_string_literal: true
+
+class UpgradePgvector080 < ActiveRecord::Migration[8.0]
+ def up
+ minimum_target_version = "0.8.0"
+ installed_version =
+ DB.query_single("SELECT extversion FROM pg_extension WHERE extname = 'vector';").first
+
+ if Gem::Version.new(installed_version) < Gem::Version.new(minimum_target_version)
+ DB.exec("ALTER EXTENSION vector UPDATE TO '0.8.0';")
+ end
+ end
+
+ def down
+ raise ActiveRecord::IrreversibleMigration
+ end
+end
diff --git a/plugins/discourse-ai/lib/embeddings/schema.rb b/plugins/discourse-ai/lib/embeddings/schema.rb
index 0f37247be96..5e4ba9fa8dc 100644
--- a/plugins/discourse-ai/lib/embeddings/schema.rb
+++ b/plugins/discourse-ai/lib/embeddings/schema.rb
@@ -15,8 +15,6 @@ module DiscourseAi
EMBEDDING_TARGETS = %w[topics posts document_fragments]
EMBEDDING_TABLES = [TOPICS_TABLE, POSTS_TABLE, RAG_DOCS_TABLE]
- DEFAULT_HNSW_EF_SEARCH = 40
-
MissingEmbeddingError = Class.new(StandardError)
class << self
@@ -137,8 +135,6 @@ module DiscourseAi
end
def asymmetric_similarity_search(embedding, limit:, offset:)
- before_query = hnsw_search_workaround(limit)
-
builder = DB.build(<<~SQL)
WITH candidates AS (
SELECT
@@ -179,7 +175,8 @@ module DiscourseAi
end
ActiveRecord::Base.transaction do
- DB.exec(before_query) if before_query.present?
+ DB.exec(hnsw_scan_relaxed_order)
+
builder.query(
query_embedding: embedding,
candidates_limit: candidates_limit,
@@ -194,7 +191,6 @@ module DiscourseAi
def symmetric_similarity_search(record, age_penalty: 0.0)
limit = 200
- before_query = hnsw_search_workaround(limit)
# For topics table, we can apply age penalty. For other tables, ignore the penalty.
use_age_penalty = age_penalty > 0.0 && table == TOPICS_TABLE
@@ -272,7 +268,8 @@ module DiscourseAi
end
ActiveRecord::Base.transaction do
- DB.exec(before_query) if before_query.present?
+ DB.exec(hnsw_scan_relaxed_order)
+
builder.query(query_params)
end
rescue PG::Error => e
@@ -306,11 +303,9 @@ module DiscourseAi
private
- def hnsw_search_workaround(limit)
- threshold = limit * 2
-
- return "" if threshold < DEFAULT_HNSW_EF_SEARCH
- "SET LOCAL hnsw.ef_search = #{threshold};"
+ def hnsw_scan_relaxed_order
+ # https://github.com/pgvector/pgvector?tab=readme-ov-file#iterative-index-scans
+ "SET LOCAL hnsw.iterative_scan = relaxed_order;"
end
delegate :dimensions, :pg_function, to: :vector_def