After Faiss finds a similar vector, where is the text? When is PostgreSQL’s pgvector extension a better fit?

July 14, 2025

I ask “Where is the spare workshop key?” and the program returns 17. The person on duty needs a locker number and wants to check the source. How does the program get from 17 to page 12 of the 2025 Workshop Equipment Manual, then give the answering model the sentence “The spare workshop key is kept in locker B17”?

On the morning of July 14 I looked at several document Q&A frameworks, then opened the Faiss repository and a vector database comparison published by deephub and credited at the end to Youssef Hosni. It listed Chroma, Milvus, Faiss, and Weaviate together, but the Faiss section called it “一个高效的库” (an efficient library), then described indexing vectors, computing distances, and running batch queries.1 Once it identifies the closest passage, is storing the actual sentence and page number also its job? I searched for “faiss数据存储” (Faiss data storage), then “faiss和pgvector” (Faiss and pgvector). A query across two editions of a manual makes the difference visible.

Why store the passage separately from its number?

The program divides the manual into passages that can be cited independently and gives each a stable ID. An embedding model reads a passage and outputs numbers representing its meaning, called a vector. At question time a compatible model also computes the question’s vector, making it possible to find semantically similar passages by distance. Each passage serves two purposes: its vector is for comparison, and its text and source are for people to read.

Passage IDEditionPageOriginal sentence (translated)Example vector
16202410The spare workshop key is kept in locker D42.[1, 0]
17202512The spare workshop key is kept in locker B17.[0.875, 0.125]
28202512Spare filter cartridges are kept in locker D42.[0, 1]

Give the question the vector [1, 0]. The three two-dimensional vectors above are hand-picked to illustrate an easily missed result: the passage most similar to the question may come from an obsolete manual. In real Q&A the model computes the coordinates, while the edition field tells you which manual is current.

Where does the 17 returned by Faiss come from?

Faiss is a library for comparing vectors and finding neighbors. Its basic IndexFlatL2 compares vectors individually and orders results by squared Euclidean distance. Euclidean distance is the straight-line distance between points, and squaring preserves the ordering. With ordinary add, labels start from zero in insertion order. Wrap the index in IndexIDMap and you can use add_with_ids to assign your own passage IDs, then retrieve text by ID later.23

This minimal program adapts the official flat-index example. It needs only Python, NumPy for numeric arrays, and the CPU version of Faiss. In a Python 3.12 environment install them with python -m pip install faiss-cpu==1.9.0.post1 numpy==2.2.6.2

import faiss
import numpy as np

passages = {
    16: (2024, 10, "车间备用钥匙放在 D42 柜。"),
    17: (2025, 12, "车间备用钥匙放在 B17 柜。"),
    28: (2025, 12, "滤芯备件放在 D42 柜。"),
}
ids = np.array([16, 17, 28], dtype="int64")
vectors = np.array([[1, 0], [0.875, 0.125], [0, 1]], dtype="float32")
index = faiss.IndexIDMap(faiss.IndexFlatL2(2))
index.add_with_ids(vectors, ids)

question = np.array([[1, 0]], dtype="float32")
distances, matches = index.search(question, 2)
for passage_id, distance in zip(matches[0], distances[0]):
    edition, page, text = passages[int(passage_id)]
    print(f"{passage_id} | {distance:.5f} | {edition} 版第 {page} 页 | {text}")
16 | 0.00000 | 2024 版第 10 页 | 车间备用钥匙放在 D42 柜。
17 | 0.03125 | 2025 版第 12 页 | 车间备用钥匙放在 B17 柜。

search returns only distances and IDs. The locker number, page, and year come from the next line, passages[int(passage_id)]. Both the dictionary and the index live in memory and disappear when the process exits. In a real application, keep passages in a SQLite or PostgreSQL table keyed by ID and save the index separately with faiss.write_index. Both datasets must refer to the same passages when reloaded. Even an intact index can otherwise point to deleted or revised text.4

search(question, 1) returns only 16, the old edition. If the application discards old editions afterward, the result is empty even though 17 in the new edition is close. Fetching one extra result works for these three records. It would not suffice if the top ten were all old. If searches always target one edition, build a separate current-edition index containing only those passages. What if the edition varies by question? When searching for pgvector I also opened Zilliz’s FAISS and pgvector comparison. The missing passage 17 is a good test of what happens when the database handles the edition filter.

How does pgvector filter editions and return the text in one query?

PostgreSQL can already store an ID, edition, page number, and passage text together in one row. The pgvector extension adds vector columns and distance operations. Reuse the same three records and ask the database for the closest passage within the 2025 edition, returning the sentence from the same row. Run the following SQL in a PostgreSQL test database with pgvector installed and permission to enable the extension. The temporary table lives only in this connection.5

CREATE EXTENSION IF NOT EXISTS vector;

CREATE TEMP TABLE manual_passages (
    passage_id bigint PRIMARY KEY,
    edition integer NOT NULL,
    page_no integer NOT NULL,
    body text NOT NULL,
    embedding vector(2) NOT NULL
);

INSERT INTO manual_passages VALUES
    (16, 2024, 10, '车间备用钥匙放在 D42 柜。', '[1,0]'),
    (17, 2025, 12, '车间备用钥匙放在 B17 柜。', '[0.875,0.125]'),
    (28, 2025, 12, '滤芯备件放在 D42 柜。', '[0,1]');

SELECT passage_id, edition, page_no, body
FROM manual_passages
WHERE edition = 2025
ORDER BY embedding <-> '[1,0]'
LIMIT 1;

The result means 17, 2025 edition, page 12: the spare workshop key is kept in locker B17. Remove WHERE edition = 2025 and the query returns 16 from the old edition. Here <-> computes Euclidean distance, while the Faiss example returns its square. They rank these three records in the same order. SELECT determines which fields SQL returns. You can include a manual file ID in the same row to open page 12 of the correct manual when there are several.6

This query has no dedicated vector index. The pgvector documentation says, “By default, pgvector performs exact nearest neighbor search”. The example compares eligible rows and returns the actual nearest one. With more data, first see how many rows survive the edition filter before deciding whether to build an approximate vector index. Approximate indexes gain speed by narrowing the search and can miss neighbors. The documentation also notes that a plan using an approximate index can scan candidates first and apply filters afterward, potentially returning fewer rows than requested. Compare results and timing with an exact query on the same set of edition-specific questions.7

After a revision, who keeps IDs, text, and vectors in sync?

Suppose an administrator corrects the 2025 edition: the key is actually in B18. Recompute the new sentence’s vector with the same model. With pgvector, one UPDATE can change both the text and the vector of passage 17. To keep the previous source citable, assign a separate edition and passage ID to the revision. With Faiss and an external passage table, the writes are separate. If the text changes before the index, readers might see a new sentence found via the old vector. A simple solution is to build a complete index and passage table for each edition, verify every matching ID retrieves its source, and switch both together.5

How does the application use the manual?What would I try first?Acceptance question
Manuals are published in batches and the program loads one fixed local snapshotFaiss plus a passage table. Match each index edition with its text and assign passage IDs in the application.After restarting and loading the new edition, does a hit on 17 open page 12 of that edition?
Manuals already live in PostgreSQL, with filtering by edition, equipment, or departmentpgvector. Start with exact queries over text, filter fields, and vectors in one table.Even with the old edition closer, does specifying 2025 return B17?
PostgreSQL stores only the text and a separate service will handle vector searchUse both. PostgreSQL holds passages, Faiss uses the same IDs. Include index updates and edition switching in implementation costs.After publishing a new edition or retrying a partial update, can the serving index still retrieve the matching source text?

Back to our two manuals. Faiss gives the application a passage ID and the application fetches the text. The pgvector example filters by edition and retrieves the text together. The person on duty should see the same verifiable answer either way: B17, page 12 of the 2025 Workshop Equipment Manual.

References

Footnotes

  1. Hosni, Y. (credited at the end, published by deephub). (2024, April 25). 开源向量数据库比较:Chroma, Milvus, Faiss,Weaviate. Zhihu. Quotation in the opening sentence of the Faiss section. See also Storage and Performance in comparison item 2. ↩

  2. Meta Platforms. (2025, July). Getting started with a flat index [Python tutorial]. Faiss, GitHub. Adding vectors and retrieving distances and labels. The same revision’s API specifies default ID allocation and squared distance for L2. ↩ ↩2

  3. Meta Platforms. (2025, July). IndexIDMap.h. Faiss, GitHub. User ID mapping and add_with_ids. ↩

  4. Meta Platforms. (2025, July). index_io.h. Faiss, GitHub. Writing and reading an index. ↩

  5. pgvector contributors. (2025, July). pgvector. GitHub. Enabling the extension, defining vector columns, inserting and updating. ↩ ↩2

  6. pgvector contributors. (2025, July). pgvector. GitHub. Querying, distance operators and query syntax. ↩

  7. pgvector contributors. (2025, July). pgvector. GitHub. Quotation in the opening paragraph of Indexing, Filtering and iterative scans. ↩

© 2025 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2025-07-14). After Faiss finds a similar vector, where is the text? When is PostgreSQL’s pgvector extension a better fit?. https://caiborui.com/blog/2025-07-14-zh-faiss-pgvector-document-storage-entrans

@misc{borui2025-73355de9,
  author = {borui},
  title = {{After Faiss finds a similar vector, where is the text? When is PostgreSQL’s pgvector extension a better fit?}},
  year = {2025},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2025-07-14-zh-faiss-pgvector-document-storage-entrans}
}