Vector databases
Run pgvector and Milvus on OpenShift: create a collection, build an index, insert, search, and run a hybrid keyword plus vector query.
A vector database stores the embeddings the RAG lab searches. The chunks come from the document pipeline. This lab puts the same three rows in pgvector and Milvus. The vectors are three numbers long so you can read them. A real embedding has the width /v1/embeddings returns; both stores reject a mismatch, and a new model means a new collection.
Prerequisites
- OpenShift 4.x,
oc, and a namespacevectors - The Crunchy Postgres operator. The Crunchy Postgres labs cover it. pgvector has shipped in its images since the 5.4 line
- The Milvus operator (
oc get crd milvus.milvus.io) - Python with
pymilvuson a machine that can port-forward
oc new-project vectors
oc get crd postgresclusters.postgres-operator.crunchydata.com milvus.milvus.io
When each
| pgvector | Milvus | |
|---|---|---|
| Run it when | You already operate Postgres and the collection fits the database you back up | The index is its own service |
| You write | SQL | pymilvus, or any client of the same API |
| Hybrid | Cosine distance plus ILIKE or a tsvector, fused in SQL |
A dense vector plus a BM25 index, fused in the engine |
| GPU | CPU | GPU_CAGRA when the pod has a GPU (cuVS; see the RAPIDS overview) |
| Business rows | The chunk can sit beside rows you already join | The account row stays in Postgres or Iceberg |
Neither store replaces the Parquet in the bucket. Pick pgvector when the corpus belongs in the application database, and Milvus when the index is large or you want BM25 in the same request.
pgvector
apiVersion: postgres-operator.crunchydata.com/v1beta1
kind: PostgresCluster
metadata:
name: vectors
namespace: vectors
spec:
postgresVersion: 16
instances:
- name: instance1
replicas: 1
dataVolumeClaimSpec:
accessModes: ["ReadWriteOnce"]
resources: {requests: {storage: 20Gi}}
users:
- {name: rag, databases: [rag]}
oc apply -f vectors-postgres.yaml
oc wait -n vectors pod \
-l postgres-operator.crunchydata.com/cluster=vectors,postgres-operator.crunchydata.com/role=master \
--for=condition=Ready --timeout=300s
POD=$(oc get pod -n vectors -o name \
-l postgres-operator.crunchydata.com/cluster=vectors,postgres-operator.crunchydata.com/role=master)
oc exec -n vectors -c database "$POD" -- psql -d rag -c "CREATE EXTENSION IF NOT EXISTS vector;"
\dx lists vector. If USING hnsw fails, that image's pgvector is older than 0.5; use ivfflat instead.
CREATE TABLE chunks (
id bigserial PRIMARY KEY,
doc_id text NOT NULL,
page int,
content text NOT NULL,
embedding vector(3)
);
INSERT INTO chunks (doc_id, page, content, embedding) VALUES
('policy-12', 3, 'reset a password at the branch with a national id', '[0.10, 0.80, 0.10]'),
('policy-12', 4, 'daily balance is the closing ledger balance', '[0.70, 0.10, 0.20]'),
('tariff-2', 1, 'the fee code FX-19 applies to outward telegraphic transfers', '[0.20, 0.20, 0.90]');
CREATE INDEX chunks_embedding_hnsw ON chunks USING hnsw (embedding vector_cosine_ops);
<=> is cosine distance. The vector [0.12, 0.80, 0.08] ranks the password page first and misses FX-19. to_tsvector('simple', ...) splits on the hyphen, so the keyword half for a code is ILIKE. Add WHERE doc_id = 'policy-12' on the semantic side when the caller may only see one document. The constant 60 only has to match on both sides of the fusion.
WITH semantic AS (
SELECT id, row_number() OVER (ORDER BY embedding <=> '[0.12, 0.80, 0.08]') AS rnk
FROM chunks
ORDER BY embedding <=> '[0.12, 0.80, 0.08]'
LIMIT 5
),
keyword AS (
SELECT id, row_number() OVER (ORDER BY id) AS rnk
FROM chunks
WHERE content ILIKE '%FX-19%'
LIMIT 5
)
SELECT c.doc_id, c.page,
coalesce(1.0 / (60 + s.rnk), 0) + coalesce(1.0 / (60 + k.rnk), 0) AS score
FROM chunks c
LEFT JOIN semantic s ON s.id = c.id
LEFT JOIN keyword k ON k.id = c.id
WHERE s.id IS NOT NULL OR k.id IS NOT NULL
ORDER BY score DESC;
The password row leads the vector list. The tariff row is there only because of the code. For words rather than codes, store to_tsvector('simple', content) and index it with GIN. simple does not stem, and it still matches a Bangla heading stored as UTF-8.
Milvus
The operator's standalone mode runs Milvus plus its own etcd and object storage. Point dependencies.storage at the object store you already run when this leaves the lab. Hybrid BM25 needs Milvus 2.5 or newer; if the operator's default image is older, set spec.components.image to a 2.5 or newer tag you have mirrored.
apiVersion: milvus.io/v1beta1
kind: Milvus
metadata:
name: lab
namespace: vectors
spec:
mode: standalone
components:
standalone:
replicas: 1
serviceType: ClusterIP
dependencies:
etcd:
inCluster: {deletionPolicy: Delete, pvcDeletion: true}
storage:
inCluster: {deletionPolicy: Delete, pvcDeletion: true}
oc apply -f milvus.yaml
oc get milvus,pods,svc -n vectors
Wait until the pod is Running. Port 19530 is gRPC; oc get svc -n vectors prints the service name, usually lab-milvus. If oc describe pod says unable to validate against any security context constraint, bind that pod's service account in this namespace only and delete the pod:
SA=$(oc get pod -n vectors <pod> -o jsonpath='{.spec.serviceAccountName}')
oc adm policy add-scc-to-user anyuid -z "$SA" -n vectors
oc delete pod -n vectors <pod>
oc port-forward -n vectors svc/lab-milvus 19530:19530
Do not grant anyuid outside vectors. The collection stores the text, a dense vector, and a sparse vector Milvus fills from the text. You do not compute the sparse vector.
from pymilvus import AnnSearchRequest, DataType, Function, FunctionType, MilvusClient, RRFRanker
client = MilvusClient(uri="http://127.0.0.1:19530")
schema = client.create_schema(auto_id=True, enable_dynamic_field=False)
schema.add_field("id", DataType.INT64, is_primary=True)
schema.add_field("doc_id", DataType.VARCHAR, max_length=64)
schema.add_field("page", DataType.INT32)
schema.add_field("content", DataType.VARCHAR, max_length=4000, enable_analyzer=True)
schema.add_field("sparse", DataType.SPARSE_FLOAT_VECTOR)
schema.add_field("embedding", DataType.FLOAT_VECTOR, dim=3)
schema.add_function(Function(
name="content_bm25", function_type=FunctionType.BM25,
input_field_names=["content"], output_field_names=["sparse"],
))
index = client.prepare_index_params()
index.add_index(field_name="embedding", index_type="HNSW", metric_type="COSINE",
params={"M": 16, "efConstruction": 64})
index.add_index(field_name="sparse", index_type="SPARSE_INVERTED_INDEX", metric_type="BM25")
client.create_collection(collection_name="chunks", schema=schema, index_params=index)
client.insert("chunks", [
{"doc_id": "policy-12", "page": 3, "embedding": [0.10, 0.80, 0.10],
"content": "reset a password at the branch with a national id"},
{"doc_id": "policy-12", "page": 4, "embedding": [0.70, 0.10, 0.20],
"content": "daily balance is the closing ledger balance"},
{"doc_id": "tariff-2", "page": 1, "embedding": [0.20, 0.20, 0.90],
"content": "the fee code FX-19 applies to outward telegraphic transfers"},
])
client.load_collection("chunks")
print(client.search(
collection_name="chunks", data=[[0.12, 0.80, 0.08]], anns_field="embedding",
search_params={"metric_type": "COSINE", "params": {"ef": 32}},
limit=2, filter='doc_id == "policy-12"',
output_fields=["doc_id", "page", "content"],
))
print(client.hybrid_search(
collection_name="chunks",
reqs=[
AnnSearchRequest(data=[[0.12, 0.80, 0.08]], anns_field="embedding",
param={"metric_type": "COSINE", "params": {"ef": 32}}, limit=5),
AnnSearchRequest(data=["FX-19"], anns_field="sparse",
param={"metric_type": "BM25"}, limit=5),
],
ranker=RRFRanker(k=60), limit=3, output_fields=["doc_id", "page", "content"],
))
filter is the RAG lab's access check: the model never sees a chunk the caller may not read. The dense index returns the password row; BM25 returns the tariff row. Use GPU_CAGRA instead of HNSW only on a pod that requests nvidia.com/gpu, and compare recall on your own questions first. Load a real corpus from bronze/doc_chunks/ after the embedding NIM fills embedding, and keep doc_id and the heading or the answer cannot be cited.
What's next
- RAG: the indexing and answering paths that call this search.
- Pipelines for AI: the job that writes the chunk Parquet.
- NeMo Retriever: the embedding and reranking NIMs.
- NIM microservices: how those NIMs run on a GPU node.