Rails pgvector means using the pgvector extension for PostgreSQL from a Rails app, usually through the neighbor gem, so you can store embeddings in an Active Record column and find the most similar records with one query. Your vectors live next to the rest of your data, in the database you already back up and monitor, and you don’t need a separate vector database.
This guide goes past the “add a column, call nearest_neighbors” basics that most tutorials stop at. It covers how to split and embed documents in a background job, which index to add, the filtering mistake that can make a tenant-scoped query return zero results, and how to combine vector and keyword search. It’s for Rails developers building search or RAG features, and for tech leads deciding whether Postgres is enough.
I ran every example on Rails 8.1.4, Ruby 4.0.8, neighbor 1.2.0, RubyLLM 2.1.1 and PostgreSQL 18 with pgvector 0.8.7. Embeddings came from the local nomic-embed-text model through Ollama, which outputs 768 dimensions, the same size the OpenAI configuration below asks for. I didn’t call the OpenAI API for this article.
What pgvector does in a Rails app
An embedding is a list of numbers (a vector) that an AI model produces from a piece of text. Texts with similar meaning get vectors that are close together. pgvector adds a vector column type to PostgreSQL, distance operators to compare vectors, and indexes to search millions of them quickly.
In a Rails app this powers features like:
- Semantic search: “how do I change my credit card” finds the article titled “Billing and invoices”, even though they share almost no words.
- RAG: an AI assistant searches your documents first and answers from the best matches. My guide to Ruby on Rails AI integration shows the assistant side; this article goes deeper on the search side.
- Recommendations and deduplication: “similar products”, “possible duplicate ticket”.
pgvector is open source under the PostgreSQL License. As of November 2026 its latest release is 0.8.7 (October 1, 2026). The neighbor gem (MIT, by Andrew Kane, the main author of pgvector itself) adds the Active Record integration. Its latest release is 1.2.0 (June 2026), which added a threshold option I use below.
pgvector vs a separate vector database
Pinecone, Qdrant, Weaviate and Milvus are databases built only for vectors. For most Rails apps, I recommend starting with pgvector:
| Question | pgvector in your Rails database | Separate vector database |
|---|---|---|
| Extra service to run and pay for | No | Yes |
| Keeping data in sync | One transaction with your other data | You sync deletes and permission changes |
| Filtering by account or status | A normal where |
Copy that metadata into the vector store |
| Keyword + vector search together | Built into Postgres | Depends on the product |
| Very large scale (100M+ vectors) | Possible, but needs tuning and memory | Often easier |
The sync point matters more than it looks. When a customer deletes a document or loses access to it, a pgvector row can go in the same transaction. With a separate store, you need jobs to keep two systems in sync and handle the times they disagree.
Step 1: Install the extension in development, CI and production
pgvector is a Postgres extension, so the database server must have it installed before Rails can enable it. For local development, the official Docker image is the quickest route:
docker run -d -p 5432:5432 -e POSTGRES_PASSWORD=postgres \
pgvector/pgvector:pg18Then add the gem and enable the extension:
bundle add neighbor
bin/rails generate neighbor:vector
bin/rails db:migrateThe generator writes a one-line migration, enable_extension "vector", which also lands in db/schema.rb.
CI is the step people forget. The ci.yml that rails new generates uses the plain postgres image, which doesn’t include pgvector. Your migrations fail with extension "vector" is not available. Change the service image:
# .github/workflows/ci.yml
services:
postgres:
image: pgvector/pgvector:pg18For production, most managed Postgres services support pgvector; the project keeps a list of hosted providers. Check which pgvector version your provider runs, because iterative index scans (used later in this guide) need 0.8.0 or newer.
Step 2: Design the table: documents and chunks
Don’t put one embedding on a whole document. Long text produces a blurry vector, and an AI assistant needs a focused passage, not a 20-page PDF. Store documents as they are, and store their chunks with one embedding each:
# db/migrate/20261103075219_create_chunks.rb
class CreateChunks < ActiveRecord::Migration[8.1]
def change
create_table :chunks do |t|
t.references :document, null: false, foreign_key: true
t.references :account, null: false, foreign_key: true
t.integer :position, null: false
t.text :content, null: false
t.vector :embedding, limit: 768, null: false
t.virtual :searchable, type: :tsvector, stored: true,
as: "to_tsvector('english', content)"
t.timestamps
end
add_index :chunks, :embedding, using: :hnsw, opclass: :vector_cosine_ops
add_index :chunks, :searchable, using: :gin
end
endA few decisions in that migration:
account_idis copied onto each chunk. Every search in a multi-tenant app filters by account, and the filter needs to be on the table you search.limit: 768is the number of dimensions. It must match what your embedding model returns. If you later change models or dimensions, you must re-embed every row.searchableis a generatedtsvectorcolumn for keyword search. Postgres keeps it up to date, and the GIN index makes it fast. Step 6 uses it.
The models are short:
# app/models/chunk.rb
class Chunk < ApplicationRecord
belongs_to :document
belongs_to :account
has_neighbors :embedding
end# app/models/document.rb
class Document < ApplicationRecord
belongs_to :account
has_many :chunks, dependent: :delete_all
after_commit :embed_later, on: %i[create update],
if: -> { saved_change_to_title? || saved_change_to_body? }
private
def embed_later
EmbedDocumentJob.perform_later(self)
end
endStep 3: Split and embed documents in a background job
Embedding calls go over the network and can take seconds, so they belong in a job, not in a before_save callback. Configure the embedding model once:
# config/initializers/ruby_llm.rb
RubyLLM.configure do |config|
config.openai_api_key = Rails.application.credentials.dig(:openai, :api_key)
config.default_embedding_model = "text-embedding-3-small"
endThe job splits the document into passages, embeds them in one request and replaces the old chunks in a transaction:
# app/jobs/embed_document_job.rb
class EmbedDocumentJob < ApplicationJob
queue_as :default
MAX_CHARS = 1_500
def perform(document)
passages = split(document)
vectors = RubyLLM.embed(passages, dimensions: 768).vectors
Chunk.transaction do
document.chunks.delete_all
passages.zip(vectors).each_with_index do |(content, vector), i|
document.chunks.create!(
account: document.account, position: i,
content: content, embedding: vector
)
end
end
end
private
# Groups paragraphs into passages of up to MAX_CHARS and prefixes each
# with the title, so a passage still makes sense on its own
def split(document)
paragraphs = document.body.split(/\n{2,}/).map(&:strip).reject(&:empty?)
passages = []
paragraphs.each do |paragraph|
if passages.empty? || passages.last.size + paragraph.size > MAX_CHARS
passages << paragraph
else
passages[-1] = "#{passages.last}\n\n#{paragraph}"
end
end
passages.map { |text| "#{document.title}\n\n#{text}" }
end
enddimensions: 768 asks text-embedding-3-small for shorter vectors than its default 1,536, which halves storage and index size. Measure search quality on your own data before you pick a size.
Splitting on paragraphs keeps sentences together. In my test, a document with five 600-character paragraphs became three chunks of 2, 2 and 1 paragraphs. One limitation: a single paragraph longer than MAX_CHARS stays whole, so split by sentence too if your content has very long paragraphs. Adding the title to each chunk matters more than it seems: a passage that only says “Click Export in the top right corner” is hard to match without knowing it’s about reports.
Step 4: Query nearest neighbors
With chunks in place, semantic search is one Active Record query:
embedding = RubyLLM.embed("how do I change my credit card").vectors
account.chunks
.nearest_neighbors(:embedding, embedding, distance: "cosine")
.limit(5)Use the same distance in the query as in the index (cosine with vector_cosine_ops), or Postgres can’t use the index. Each result has a neighbor_distance attribute. For cosine distance, 0 means identical and larger means less similar.
Nearest-neighbor search always returns the closest rows, even when none of them are relevant. In my test, the credit card question returned “Billing and invoices” at distance 0.305, then “Resetting your password” at 0.506 and “Single sign-on” at 0.531, which are wrong answers. neighbor 1.2 adds a threshold option to cut those off:
account.chunks
.nearest_neighbors(:embedding, embedding, distance: "cosine",
threshold: 0.45)
.limit(5)
# => only "Billing and invoices" (0.305)The right threshold depends on your embedding model and content, so log distances for real queries and pick it from data. For an AI assistant, returning nothing is better than returning the wrong article, because the model will try to use whatever you give it.
Step 5: Index with HNSW, and don’t lose results when you filter
pgvector has two index types. HNSW is the one to use by default: it has a better speed/accuracy trade-off and, unlike IVFFlat, you can build it on an empty table. IVFFlat builds faster and uses less memory, but it needs data in the table before you build it.
Both are approximate indexes, and that creates a trap in multi-tenant apps. With an approximate index, Postgres applies your WHERE clause after it scans the index. The scan looks at only 40 candidates by default (hnsw.ef_search). If one account owns 2% of the rows, only about one of those 40 candidates belongs to it.
I tested this with 20,000 chunks across 50 accounts and asked for one account’s 10 nearest chunks:
| Setup | Rows returned (of 10) |
|---|---|
B-tree index on account_id (planner’s choice) |
10 |
| HNSW index only | 0 |
HNSW, hnsw.ef_search = 200 |
4 |
HNSW, hnsw.iterative_scan = relaxed_order |
10 |
HNSW, hnsw.iterative_scan = strict_order |
10 |
At 20,000 rows, Postgres chose the account_id index on its own and returned exact results. On bigger tables it will start choosing the HNSW index, and the same query can quietly return fewer results, or none, with no error. Raising ef_search only helps a little.
The fix is iterative index scans, added in pgvector 0.8.0: when filtering removes too many candidates, the index keeps scanning until it finds enough. Set it for the search query only, with SET LOCAL inside a transaction:
# app/models/chunk.rb
def self.semantic_search(query, limit: 5)
embedding = RubyLLM.embed(query, dimensions: 768).vectors
transaction do
connection.execute("SET LOCAL hnsw.iterative_scan = relaxed_order")
nearest_neighbors(:embedding, embedding, distance: "cosine")
.limit(limit).to_a
end
endCall it on a scoped relation, account.chunks.semantic_search("..."), and the account filter applies. The .to_a matters: the query must run inside the transaction, while the setting is active. relaxed_order can return results slightly out of distance order but finds more of them; strict_order keeps exact order. If you call this method inside a bigger transaction, the setting lasts until that transaction ends.
For apps with a few very large tenants, pgvector’s docs suggest partitioning the table by account, or a partial index per large tenant, so each tenant gets its own index.
Step 6: Combine vector and keyword search
Embeddings understand meaning, but they’re weak at exact strings: error codes, SKUs, invoice numbers and names. My test help center had an “Import errors” article listing codes E1041–E1048, and an “Exporting reports” article that mentions E1047. Here are the top results for the query “E1048”:
| Search | First result |
|---|---|
| Semantic | Exporting reports |
| Keyword | Import errors |
| Hybrid | Import errors |
Semantic search ranked the article with a similar-looking code first. Keyword search found the exact code. Hybrid search runs both and merges them with Reciprocal Rank Fusion (RRF), which gives each result a score based on its rank in each list. neighbor includes it:
# app/models/chunk.rb
scope :keyword_search, ->(query) {
where("searchable @@ websearch_to_tsquery('english', ?)", query)
.order(Arel.sql(sanitize_sql_array([
"ts_rank_cd(searchable, websearch_to_tsquery('english', ?)) DESC", query
])))
}
def self.hybrid_search(query, limit: 5)
keyword = keyword_search(query).limit(20).to_a
semantic = semantic_search(query, limit: 20)
Neighbor::Reranking.rrf(keyword, semantic)
.first(limit).map { |hit| hit[:result] }
endwebsearch_to_tsquery accepts the kind of text users type, including quotes and -word, without raising syntax errors. sanitize_sql_array keeps the query string safely quoted inside ORDER BY. For RAG I use hybrid search by default: it costs one extra indexed query and catches exactly the cases that make an assistant look careless.
Step 7: Plan for large embeddings
Some models output more dimensions than an index can hold. pgvector’s HNSW index supports up to 2,000 dimensions for vector. When I created one on a vector(3072) column (the default size of text-embedding-3-large), Postgres refused with column cannot have more than 2000 dimensions for hnsw index.
You have two options. Ask the model for fewer dimensions, as Step 3 does. Or keep full vectors and index them at half precision, which supports up to 4,000 dimensions:
add_index :chunks, "(embedding::halfvec(3072)) halfvec_cosine_ops",
using: :hnswThen query with precision: "half" so the query matches the index:
Chunk.nearest_neighbors(:embedding, embedding, distance: "cosine",
precision: "half")Production checklist
- The extension exists everywhere: development, CI (
pgvector/pgvectorimage) and production, with pgvector 0.8.0 or newer for iterative scans. - Embedding runs in jobs, with retries, and a re-embed task you can run when you change models.
- One model and size everywhere. Documents and queries must use the same embedding model and dimensions, or distances mean nothing.
- Every search is scoped to the current account or user, and iterative scans are on for filtered HNSW queries.
- A distance threshold keeps irrelevant chunks out of AI prompts.
- Memory for the index. HNSW search is fastest when the index fits in memory. Watch index size as data grows (
halfvecor fewer dimensions halve it). - An evaluation set: 20–50 real questions with the chunks that should come back. Run it whenever you change chunking, models or thresholds.
Search quality comes from these details (chunking, filtering, thresholds and evaluation) more than from the database. When I build AI and search features for Rails apps, this is where most of the tuning time goes.
What’s next for pgvector
pgvector’s changelog lists 0.9.0 as unreleased, with asynchronous I/O for HNSW indexes and faster sparse-vector inserts. It also drops support for Postgres 13 and 14, so check your Postgres version before you upgrade the extension.
Conclusion
pgvector lets a Rails app add semantic search and RAG without a second database. With the neighbor gem, a vector is an Active Record column and a similarity search is a scope. The parts that need care are the ones tutorials skip: chunk documents in a background job, scope every query to the account, turn on iterative scans so filtered HNSW queries don’t lose results, cut weak matches with a threshold, and add keyword search for codes and names.
I build search and AI features into existing Rails apps, from embedding pipelines and hybrid search to the assistants that use them. If you’re planning semantic search or RAG on your own data, send me a short brief and book a discovery call.
Frequently asked questions
Does Rails support pgvector?
Not on its own. Active Record doesn’t know the vector type, so you add the neighbor gem, which adds the column type, schema dumping and nearest_neighbors queries. The pgvector extension itself must also be installed on your Postgres server.
What is the neighbor gem?
neighbor is a Ruby gem that connects Active Record to vector search. It supports pgvector and Postgres’s built-in cube extension, and also MariaDB, MySQL and SQLite. With pgvector it handles vector, halfvec, bit and sparsevec columns, plus helpers like Reciprocal Rank Fusion.
Should I use HNSW or IVFFlat in pgvector?
Use HNSW unless index build time or memory is a real constraint. HNSW gives better speed for the same accuracy and can be created on an empty table, so it works with a normal Rails migration. IVFFlat must be built after the table has data, and its number of lists has to be tuned to the table size.
pgvector vs Pinecone: which is better for a Rails app?
For most Rails apps, pgvector is the simpler choice: no extra service, filtering with normal where clauses, and data changes in the same transaction. A dedicated vector database makes sense at very large scale, or when your team doesn’t run Postgres. Start with pgvector and measure before you add a second system.
Why does my pgvector query return fewer results than the limit?
Approximate indexes apply WHERE filters after the index scan, which only looks at hnsw.ef_search candidates (40 by default). Turn on iterative index scans with SET LOCAL hnsw.iterative_scan = relaxed_order (pgvector 0.8.0+), or add a B-tree index on the filter column for small tables. Rows with NULL vectors are also never returned by the index.
Can I use pgvector on Heroku or Amazon RDS?
Yes. Heroku Postgres, Amazon RDS, Aurora and most other managed Postgres services offer pgvector; pgvector keeps a list of providers. The available version differs by provider and Postgres version, so check that it’s 0.8.0 or newer if you need iterative scans.
How many dimensions should my embeddings have?
Smaller vectors use less storage and memory and search faster, while bigger ones can capture more detail. Models like text-embedding-3-small let you choose the size, and 768 is a reasonable start for help-center and product content. Test retrieval on real questions before and after changing it, because every change means re-embedding all rows.


