HTMLCSSJAVASCRIPTANGULARINTERVIEW QUESTIONSSQLPYTHONJAVAPHPHOW TOW3.CSSCC++C#BOOTSTRAPREACTNEXTJSMYSQLJQUERYEXCELXMLDJANGONUMPYPANDASNODEJSDSATYPESCRIPTANGULARJSGITPOSTGRESQLMONGODBASPAIRGOKOTLINSWIFTSASSVUEGEN AIAGENTIC AIPROMPT ENGINEERINGDOCKERKUBERNETESSPRINGSPRING BOOTUNIXSCIPYAWSCYBERSECURITYDATA SCIENCEINTRO TO PROGRAMMINGINTRO TO HTML & CSSBASHRUSTTOOLS
AI-Powered Full Stack Tutorial 0/70 lessons ~6 min read Lesson 27“React, Next.js, Node, PostgreSQL, LLMs, RAG, agents, and production AI apps”
Vector Databases and PostgreSQL pgvector
The in-memory title index from lesson 17 was the right place to learn cosine similarity.
Course progress0%
Focus
16 guided sections
Practice signal
Concept-first lesson
Career prep
Foundation builder
AI-Powered Full Stack Development · Lesson 27 · RAG, Search and Knowledge Systems
Lesson Overview
The in-memory title index from lesson 17 was the right place to learn cosine similarity. It is the wrong place to search the lesson corpus once every section is a chunk. A prototype moved those arrays into PostgreSQL by concatenating the organization id into the SQL text and ordering with <->, the L2 distance. The threshold in the handler was still the cosine-similarity cut from lesson 17, so weak neighbors looked acceptable, and a quote in a hand-built literal was an injection. A second query took the global nearest rows and dropped other organizations in the application. The ids had already been read by a role that could see every tenant, and the log line included them.
pgvector is a PostgreSQL extension that stores a vector column and orders rows by a distance operator. This lesson keeps the corpus in the database you already operate, adds chunk_embeddings, and searches with cosine distance <=> through bound parameters. The organization, the embedder id, the dimension count, the active flag, and the visibility rule sit in the same statement as the ordering. Cosine distance and cosine similarity are different directions: distance <=> is 1 - cosine similarity for the way pgvector defines it, so a lesson 17 minimum similarity of 0.5 is a maximum distance of 0.5. Higher similarity is better. Lower distance is better. Mixing them up is how a cutoff admits the neighbors you meant to refuse.
The chunks being embedded are the rows from lesson 26. The caller is the retriever port from lesson 24. /learn/genai/vector-db names the product category. /learn/postgresql is the engine. You will not invent a vendor embeddings URL. The lab embedder is the lexicon-shaped port from lesson 17, id lexicon-v1, four dimensions. A provider adapter replaces that port later, after you read that provider's current embeddings reference, and it stores the same embedder_id the query filters on.
Planning assumptions:
vector(4) matches lexicon-v1. A production model card with a different dimension gets a new column or a new table and a new embedder_id. It does not get an in-place alter that pretends old and new rows share a geometry.
HNSW index parameters m = 16 and ef_construction = 64 are pgvector's usual defaults, not a tuning study. Confirm them in the README for the extension version you installed.
Approximate indexes can miss a true nearest neighbor. Correctness tests use an exact ORDER BY plan on a small set, or they assert the SQL predicate, not a specific recall number.
No provider key. Tests can record SQL without a server. An integration test that executes <=> needs PostgreSQL with the vector extension.
Learning Objectives
By the end of this lesson you will be able to:
Explain what a vector database is doing in this product: store chunk vectors beside the ACL columns and order them by a distance.
Install and detect pgvector, and read extversion before depending on an index option.
Choose cosine distance <=> to match lesson 17's cosine similarity, and convert a minimum similarity into a maximum distance.
Reject L2 <-> and inner-product <#> for this corpus unless you have normalized vectors and rewritten the threshold on purpose.
Insert embeddings with a bound vector literal built from finite numbers, never from raw user text.
Query with organization_id, embedder_id, dimensions, active, visibility, and enrolled courses in the same parameterized statement as ORDER BY ... <=>.
Keep the application role from scanning another tenant's nearest neighbors and filtering afterward.
Add an HNSW index using vector_cosine_ops, and explain why the index does not replace the WHERE clause.
State that HNSW and IVFFlat are approximate, and that filtered queries can return fewer than LIMIT rows unless the plan actually applied the filter in time.
Map a zero vector and a dimension mismatch to a failed embed, not to a NaN distance.
Test the parameter order, the distance cutoff, and a foreign organization that the SQL does not ask for.
Connect the result rows to lesson 24's RetrievedChunk without letting the model pick the table name.
PostgreSQL you can install an extension on. pgvector is a separate extension project. CREATE EXTENSION vector succeeds only after the package is installed on the server. Node.js with the pg driver, as in lesson 11. No API key.
Detailed Core Concepts
Why the vectors live in PostgreSQL
A dedicated vector engine is a second database: another backup, another tenant model, another place an id can be joined without organization_id. TechLearningPro already stores documents, chunks, enrollments, and progress in PostgreSQL. pgvector adds a column type and an operator so the chunk and its vector commit together. The join to visibility is a normal join. The day the corpus outgrows a single primary, you will have measured it. You will not have guessed it on the third lesson file.
The extension does not know what a tenant is. Distance is a number. The WHERE clause is the product. A vector engine with metadata filters is the same design in different packaging. If you adopt one later, the statement you are about to write is the checklist: organization, embedder, dimensions, active generation, visibility, enrollment, then the nearest neighbors under a distance cap.
Cosine distance is the inverse direction of lesson 17
Lesson 17 ranked by cosine similarity (a · b) / (||a|| ||b||). pgvector's operator <=> is cosine distance. For the extension's definition, that distance equals 1 - cosine similarity. Identical direction is similarity 1 and distance 0. Orthogonal is similarity 0 and distance 1. Opposite direction approaches similarity -1 and distance 2.
Lesson 17 similarity
pgvector <=>
Admit when min similarity is 0.5?
0.92
0.08
Yes
0.50
0.50
Yes, at the cut
0.20
0.80
No
The SQL uses embedding <=> $vector <= $max_distance and ORDER BY embedding <=> $vector. max_distance is 1 - minScore. Do not pass minScore as if it were a distance. Do not order by <=> DESC. Descending cosine distance prefers the least similar rows.
<-> is Euclidean L2 distance. <#> is negative inner product, so ascending <#> prefers a larger inner product. Those operators answer different questions. An index built USING hnsw (embedding vector_l2_ops) is not a cosine index. The operator in ORDER BY has to match the operator class or the planner will not use that index, and a threshold copied from cosine will not mean what you think.
The literal is a list of numbers you produced
pgvector accepts text of the form [0.1,0.2,0.3,0.4] and casts it with $1::vector. The application builds that string from a number[] after Number.isFinite on every component and a length check against the embedder's dimension. The learner's question is not concatenated into the SQL. It is passed to the embedder, and only the resulting numbers are bound. A question containing a quote or a parenthesis never reaches the parser as syntax.
node-pg returns values of unknown types as strings. The distance column will often arrive as "0.125" rather than a number. Coerce with Number and reject a non-finite result. Do not sort in JavaScript on the raw strings. "0.9" and "0.10" do not sort numerically as strings, and you should not be re-sorting a limit the database already applied except as a test.
Embedder identity is part of the key
A row stores embedder_id and dimensions with a check that dimensions equals the column width. The query passes the current embedder id. Rows written by lexicon-v1 do not appear in a search for provider-model-2026-01. When you change models, you insert a new generation and point the retriever at the new id. You do not update the old vector to "approximate" the new space. Lesson 17's re-embed rule is now a SQL predicate.
The lab column is vector(4) because the lexicon has four axes. The number 1536 shows up in articles about particular models. It is an illustration of "read the model card," not a default you should migrate to because this paragraph mentioned it. If the card says 1024, the column is vector(1024) and the check constraint says 1024. Changing width is a new physical column. PostgreSQL will not treat a 4-dimensional value as a prefix of a 1024-dimensional one, and neither will cosine.
ANN indexes and the filter
CREATE INDEX ... USING hnsw (embedding vector_cosine_ops) builds an approximate nearest-neighbor structure for <=>. IVFFlat (USING ivfflat ... WITH (lists = ...)) is the other common pgvector index. Both can return a set that is not the exact top-k. For a knowledge assistant, a missed chunk becomes a weaker answer or no_context, which is a quality miss. A missing organization_id predicate is a tenant miss. Take the tenant miss first. Use an exact plan in tests on small data by leaving the index off, or by checking EXPLAIN that you still see the filter.
Filtered ANN has a known shape: the index finds global neighbors, then the filter throws them away, and LIMIT 4 might return one row or none even though the tenant has closer rows that were not in the candidate list. pgvector has added iterative scans in later releases so the index keeps searching until the limit is filled under the filter. The setting names have changed with versions. Read SELECT extversion FROM pg_extension WHERE extname = 'vector' and the README for that version before you set hnsw.ef_search or any iterative-scan option. hnsw.ef_search is the long-standing candidate-list knob for HNSW. This lesson does not hard-code a SET that your extension build might reject.
The WHERE clause is mandatory on every version. An iterative scan is an availability improvement. It is not the ACL.
What the embedder port is allowed to see
typescript
exportinterfaceEmbedder{
readonly id:string;
readonly dimensions:number;
embed(text:string):Promise<readonlynumber[]>;
}
embed receives chunk body or the learner's question, both already authorized for this workflow. It returns numbers or throws zero_vector / dimension_mismatch. A provider-backed implementation sends that text to an embeddings endpoint. That send is an export of tenant data, which lesson 17 already named. Build it when you have the provider's current URL, auth scheme, and JSON fields in front of you. Tests in this lesson use a fake that returns a fixed vector. They do not call a network, and they do not contain a key.
Zero vectors are rejected before insert. pgvector's cosine against a zero vector can yield NaN, and NaN in an ORDER BY is a ranking bug you will not enjoy reading in a log.
Architecture and Request Flow
flowchart TB
subgraph api [TechLearningPro API]
Ask[Retriever for lesson 24]
Emb[Embedder port]
end
subgraph data [PostgreSQL plus pgvector]
Chunks[(corpus_chunks)]
Vec[(chunk_embeddings)]
end
Ask --> Emb
Emb -->|question vector| Ask
Ask -->|parameterized SELECT| Vec
Vec --> Chunks
Chunks -->|authorized rows| Ask
Index flow, which is a job and not the question request: read active chunks with no embedding for this embedder_id, embed the body, insert the vector in a transaction that re-checks organization_id. Query flow: embed the question with the same id, then one SELECT. The model port from lesson 24 is not in this diagram. It runs only after these rows return.
flowchart LR
Q[Question text] --> E[Embedder]
E --> L[Finite vector literal]
L --> S["WHERE organization AND embedder AND visibility"]
S --> D["ORDER BY embedding <=> query"]
D --> Cap[Distance cap and LIMIT]
Failure points: extension missing, dimension mismatch, non-finite component, zero vector, embedder id with no rows, distance returned as non-numeric text, a plan that sequential-scans a large table, a filter so selective that an approximate index returns an empty set. The last one is a recall problem to confirm with EXPLAIN and a known neighbor, not a reason to drop organization_id from the predicate.
ON chunk_embeddings (organization_id, embedder_id);
CREATEINDEX chunk_embeddings_cosine_hnsw
ON chunk_embeddings
USING hnsw (embedding vector_cosine_ops)
WITH(m =16, ef_construction =64);
vector_dims is pgvector's function for the length of a stored value. The check stops a client from binding a literal of the wrong width if a future bug skips the TypeScript guard. ON DELETE CASCADE drops the vector when lesson 26 deletes a replaced chunk.
Confirm the extension after migrate:
sql
SELECT extversion FROM pg_extension WHERE extname ='vector';
If that returns no row, the rest of this lesson is not installed. Do not catch the error and fall back to storing vectors in jsonb and sorting in Node. That fallback is the full-table read you left lesson 17 to avoid, and it will be copied into production.
HNSW build parameters live in the WITH clause at index creation. hnsw.ef_search is a query-time setting, not an argument to CREATE INDEX. IVFFlat wants rows loaded before you build it, because lists is a guess about the data. This lesson uses HNSW so an empty lab database can still create the index. Either index is approximate. Say so in the design note.
join(",") on numbers cannot inject SQL. The cast to ::vector still happens in the statement, not by pasting the literal into the query string. Math.hypot is the magnitude. A zero vector never becomes a row.
Organization and course ids are the uuids from lesson 11. Lesson 24's in-memory tests use readable stand-ins such as org_01. Do not bind those stand-ins to $6::uuid[]. A database test uses real uuids.
Parameter positions are part of the contract:
Placeholder
Value
$1
Session organization
$2
Current embedder id
$3
Dimension count
$4
Vector literal from finite numbers
$5
Instructor flag, server-derived
$6
Enrolled course ids for a learner
$7
Maximum cosine distance
$8
Limit
$5 is bound twice in the text and once in the parameter list. PostgreSQL allows a placeholder to repeat. pg still has a single value at index 5 (zero-based index 4). Do not push staffAllowed twice.
A learner with an empty enrolledCourseIds matches nothing through ANY, which is the right outcome. An instructor passes the visibility disjunct and the course disjunct because $5 is true. The organization predicate does not become optional for instructors.
score is converted back to similarity so lesson 24's minScore and selectAuthorized speak the same unit. Apply the cutoff in SQL anyway so a large table does not return a hundred weak rows for the application to drop.
The join predicate e.organization_id = c.organization_id is belt and braces. The foreign key already ties chunk_id to one chunk. Repeating the organization stops a bug that inserts an embedding under the wrong organization from becoming a join hit. The insert in the next step writes both from the chunk row.
Step 4: Insert from the chunk, not from the client
LEXICON_DIMENSIONS is the same 4 as vector(4) and as CHECK (dimensions = 4). A provider embedder passes embedder.dimensions from the config you set when you wrote the migration, not values.length, which would accept any width and leave the database to reject it. 23514 is PostgreSQL's check-violation code. Map it to bad_vector so a wrong width does not spin as a transient job error.
The primary key is (chunk_id, embedder_id), so lexicon-v1 and a later provider id can both exist for the same chunk until you delete the old generation. A primary key on chunk_id alone would make that cutover an update that destroys the previous vector before the new recall set passes.
ON CONFLICT DO NOTHING makes a retry of the same chunk and embedder a no-op. A no-op and a wrong organization both report rowCount === 0. Neither case writes a row, and the caller does not learn that another organization owns the uuid. If a worker must tell "already embedded" from "not in this tenant," SELECT under the same organization first and keep that read parameterized.
Step 5: How you run it
Install the pgvector package for your PostgreSQL major version. The extension and the server major have to match. The project README is the install path. This lesson does not copy package-manager commands that go stale.
CREATE EXTENSION vector as a privileged role. Record extversion.
Apply 012_chunk_embeddings.sql as migrator.
Insert a lab chunk and a four-number embedding with insertEmbedding.
Search with a second vector and a minSimilarity you can compute by hand from lesson 17's cosine.
EXPLAIN (ANALYZE, BUFFERS) the search on a staging copy once the table is large enough that a sequential scan would hurt. On three rows the plan will sequential-scan, and that is fine.
Do not put a superuser URL in the application config so the process can run CREATE EXTENSION at boot. Migrate with migrator. Query with app_rw.
Security
The search statement is the ACL on retrieved chunks. Lesson 24 repeats it in selectAuthorized because a second bug should still fail closed. The database is where the bytes are actually read.
$1 is the session organization. There is no code path that interpolates it. A reviewer who builds `WHERE organization_id = '${id}'` is reverting this lesson.
The statement does not take a table name, a column name, or an operator from the request. The operator is the literal <=> in source. If you ever parameterize the operator, you will not be able to bind it as a value. An allow-list of one operator is the only acceptable version, and it is simpler to keep <=> in the SQL text.
Learners bind staffAllowed false and their enrolled course ids. Instructors are still constrained by $1. Membership, not this query, decides the role, as in lesson 11.
insertEmbedding copies organization_id from corpus_chunks via SELECT, and the WHERE requires the caller's organization. A client-supplied organization on the embedding row cannot drift from the chunk.
Logs: organization id, embedder id, chunk ids, distances, extversion in the deploy note. Not body, not the vector literal (it is reversible toward the text by anyone with the embedder), not a connection string.
Set a statement_timeout on app_rw so a surprise sequential scan cannot hold a connection until the gateway gives up. The timeout is an availability control. It does not change the WHERE.
Optional defense in depth, after the parameterized predicate is tested: enable row level security and set the organization at the start of the transaction with SELECT set_config('app.organization_id', $1, true). set_config binds the value. Do not SET app.organization_id = ' + id + '. The table owner and any BYPASSRLS role skip the policy, so the application role must be neither. RLS does not excuse removing $1 from the statement a superuser might run in a console.
Embedding text leaves the network only inside an adapter you reviewed. The lexicon fake stays in-process. A provider adapter uses the secret handle from lesson 23, not a key in this file.
Do not query. A bad question vector is no_context at the retriever, after you log the reason without the question if the question may contain another learner's pasted secret. A bad chunk vector is bad_vector and the chunk stays unembedded
Check violation 23514
bad_vector. Stop the job. Fix the dimension constant
not_found on insert
The chunk is inactive or in another organization. Do not upsert with a client-supplied organization
Extension missing
Fail the migration. Do not emulate <=> in application code for production
Non-finite distance string
Drop the row. If every row drops, return no hits and alert. A NaN from a zero vector means the insert guard was bypassed
statement_timeout
The assistant takes lesson 24's unavailable path. Progress is untouched
Empty hit list
Lesson 24 returns no_context and does not call the model
A timeout is not a signal to retry the same expensive ORDER BY in a loop. One user retry is a new request. Approximate-index misses are not errors. Track how often a known relevant chunk is absent from the top-k on a fixed question set, and raise hnsw.ef_search only after you have read the setting's name for your extversion.
Add a test that records the SQL text and the parameter array from a fake Pool:
The text contains c.organization_id = $1 and <=> and does not contain <->.
params[0] is the session organization, params[3] starts with [ and was produced by toVectorLiteral, params[6] equals maxCosineDistance(0.5).
The text does not contain the raw question. Pass the question only to the embedder fake, and pass the numbers to searchChunks.
A learner's params include false for the instructor flag. An instructor's include true. Neither call's SQL string contains the other organization's id.
An integration test against a real vector extension inserts two organizations, searches as organization A, and asserts organization B's body is absent even when B's vector is a closer cosine. That test is the one that fails if someone selects global top-k and filters in JavaScript after logging the rows.
Recall eval: five questions whose relevant chunk_id you marked by hand. Report how often that id appears inside LIMIT 4 at the distance cap. That number is a retrieval metric. It is not a license to weaken the organization predicate when the number is low. Fix recall with chunking, the embedder, ef_search, or the limit, in that order of suspicion.
Performance and Cost
Embedding the corpus is the spend. The query is a latency path the assistant waits on before it even calls ModelPort.
Embed each active chunk once per embedder_id. ON CONFLICT DO NOTHING makes the job retryable. Changing the chunk id, which lesson 26 does on replace, is what triggers a new embedding. Do not re-embed on every question.
The question is embedded on the request path. Cache that vector only under a key that includes the embedder id and the question hash, not under the lesson id.
HNSW build time and memory grow with row count and with m and ef_construction. Defaults are the starting point. Measure build time on a staging copy before you raise them.
LIMIT plus the distance predicate keeps the assistant's context small. Fetching 100 rows "for reranking later" pulls staff-eligible bodies into the application for a learner if the visibility predicate was also postponed. Reranking is lesson 29, and it reranks rows the ACL already returned.
A sequential scan of chunk_embeddings on a small corpus is cheaper than HNSW. The index exists so the plan can change when EXPLAIN says the scan is the cost. Do not drop the WHERE to "help the index."
Storage is one vector(4) in the lab, which is tiny. A 1024-wide float32 vector is about 4 KB before index overhead, times chunks, times embedder generations you forgot to retire. Deactivate an old embedder_id and delete its rows when the new id has passed the recall set. Until that delete, you pay storage and you risk a query that forgets the embedder predicate and mixes geometries.
Illustrative, not a quote: embedding cost is proportional to chunk count, overlap from lesson 26, and how often you bump embedder_id. Query cost is one embedding of a short question plus one indexed read. The completion in lesson 24 is still the larger token bill. Skipping complete on an empty search is the cost control that empty retrieval already gives you.
Knowledge Check
1. What problem does this capability solve?
It stores one vector per chunk per embedder in PostgreSQL and returns the nearest authorized chunks under cosine distance, with the tenant and the ACL in the same parameterized statement. The in-memory index could not hold the corpus, and a string-built query with the wrong operator both leaked and mis-ranked.
2. What alternatives exist, and when would you choose each?
pgvector fits a corpus that should stay in the same database as enrollments and chunks. An external vector service fits a scale or an operational split you have measured, and it still needs the same predicates. An exact scan in application memory fits lesson 17's teaching index and the unit tests. L2 or inner product fits after you normalize and you rewrite the threshold; they are not drop-in replacements for <=> in this assistant.
3. Which data, identity, and trust boundaries matter?
The session organization is $1. The embedder id and the dimension are server config. The instructor flag and the enrolled courses come from membership and enrollments. The vector is numbers from the embedder, not the raw question. Chunk bodies returned by this query are the bodies lesson 24 may pack. A provider embedding call, when you add one, is an export of that text.
4. What can fail, and how should the system respond?
Bad vectors never query. A check failure stops the embed job. A missing chunk returns not_found without writing. A timeout becomes unavailable on the assistant. An empty authorized hit list becomes no_context. A non-finite distance is dropped. An approximate index that skips a relevant chunk is a recall bug to measure, not a reason to remove the filter.
5. How would you test quality, security, performance, and cost?
Unit tests cover the distance conversion, the literal guards, and the parameter positions, including the absence of <-> and of the raw question in the SQL. An integration test with two organizations proves the closer foreign vector is invisible. EXPLAIN (ANALYZE, BUFFERS) on staging checks the plan. Cost review counts embeddings per publish and confirms a retry does not insert a second vector for the same chunk id.
Hands-on Assignment
Lab note. Unit tests need no server and no key. The integration test needs a local PostgreSQL with pgvector. Keep the connection string out of Git.
Problem. Embed one active chunk with lexicon-v1 and search it so a nearer vector in another organization is not returned, using <=> and a similarity cut of 0.5.
Tasks.
Apply the migration. Record extversion in your notes.
Implement toVectorLiteral, maxCosineDistance, searchChunks, and insertEmbedding with the dimension constant 4.
Pass the unit tests. Add the fake-pool assertion on parameter order.
Compute one cosine by hand for two four-dimensional vectors, convert to distance, and show the SQL cutoff admits one and rejects the other.
Write the EXPLAIN you ran, or state that you only have the unit tests and what an integration test still has to prove.
List the log fields for a search. Include organization and chunk ids. Exclude body and connection strings.
Deliverable. Migration, source, test output, the hand-computed distance, and the log-field list.
Challenge. Describe the cutover from lexicon-v1 at 4 dimensions to a provider embedder at the width on its model card. Include the new column or table, the new embedder_id, the query change, and the moment you delete the old rows. State what fails if one statement orders by a mixture of both widths.
Rubric. Conceptual accuracy and architecture 20%. Working implementation and code quality 25%. Security, privacy, and responsible AI 20%. Testing, reliability, and observability 20%. Documentation and decision rationale 15%.
Common Mistakes
Filtering tenants after a global top-k. Symptom: empty answers for a tenant whose neighbors were not in the global four, or foreign ids in a log. Cause: LIMIT ran before organization_id. Fix: both predicates in one statement, then limit.
Using <-> with a cosine threshold. Symptom: unrelated chunks pass a "0.5" check, or close chunks disappear. Cause: L2 distance and cosine similarity were treated as the same unit. Fix: <=> and maxCosineDistance.
Ordering cosine distance descending. Symptom: the worst neighbors come back first and the cutoff looks random. Cause: the lesson 17 habit of "higher is better" was applied to a distance. Fix: ORDER BY embedding <=> $4::vector ascending, which is the default direction.
Concatenating the organization or the question into SQL. Symptom: quotes break the query, or a crafted question changes the predicate. Cause: a prototype built the statement as a string. Fix: bind $1 and bind a numeric literal the embedder produced.
Comparing two embedder generations. Symptom: recall collapses after a model upgrade and some old chunks still win. Cause: the query omitted embedder_id. Fix: store it, filter it, and re-embed before you switch the id the retriever sends.
Trusting the HNSW index as an ACL. Symptom: a filtered query returns too few rows, and someone removes the filter to "fill" the limit. Cause: approximate search and post-filtering were confused with authorization. Fix: keep the WHERE. Tune recall with the version's documented search parameter after you read extversion.
Altering vector(4) in place when the model card changes. Symptom: inserts fail, or worse, a cast hides mixed widths. Cause: one column was asked to host two geometries. Fix: a new column or table, a new id, a cutover, then a delete.
Storing a zero vector. Symptom: NaN distances and an unstable ORDER BY. Cause: empty text produced zeros and the insert did not check magnitude. Fix: zero_vector before the statement.
Summary
pgvector stores the chunk embedding next to the chunk's organization and serves nearest neighbors with cosine distance <=>, bound parameters, and the same visibility rules the assistant already enforced in memory. Similarity and distance face opposite directions, and the threshold converts explicitly. The index speeds a correct predicate. It does not define who may read a chunk. The next lesson adds keyword match beside this distance, without dropping the predicate either signal is filtered by.
Next Lesson Preview
Semantic, Keyword and Hybrid Search runs this cosine query beside a keyword query on the same authorized chunks. Fusion comes after both lists exist. It does not replace organization_id, and it does not average the two scores as if they were one unit.
Further Reading
pgvector for <=>, HNSW, IVFFlat, and the README that matches the extversion you installed.