Works of Vector Database after We Have Embeddings A second-part tutorial builds a test vector-search service from FAISS, SQLite and NumPy to demonstrate the operational components a production vector database must handle beyond similarity search, including chunking, indexing, metadata filtering, persistence and concurrency. The article argues that FAISS is a vector similarity search library rather than a database server, so identifiers, original text, metadata, lifecycle and filtering must be handled by a separate retrieval service. The author notes that in Part 1, an 8-dimensional NumPy semantic search over solar energy and night-time lighting sentences showed the mathematically closest sentence may not be the most contextual answer. In Part 1 of the work - Why Vector Search is Mathematically Right and Still Give the Answer Which Can be Least Expected https://pub.towardsai.net/why-vector-search-is-mathematically-right-and-still-give-the-answer-which-can-be-least-expected-6de0687d3ab9 — we built a semantic search application with Python NumPy Library. We converted and linked some sentences to be 8 dimensional vectors and matched the question vectors with sentences. With matrix multiplication of sentence vector and question vector, we ranked the information Similarity Score about solar energy and night time lighting. During the work, we learned and proved that - the mathematical closest sentence may not be the most contextual answer. There the search was working without any syntactical or logical bug, but the representation and the ranking were not giving us most appropriate answers as binary feature representations of the concepts in raw sentences were not fulfilling the requirement. We introduced some feature mixing concept to improve the result. In a real production application, we will have millions of passages with a chance of data growth. Organizations upload their own material with proprietary business rules associated with their environment. All those documents are edited, replaced time to time and may be versioned as per requirement. In such situation, an query should return most appropriate information to the information retriever components. There should be some kind of document indexes and the index should be serialized and modified as dataset changes or grows. Also the response time to the request of information should have reasonable fetch time at parallel to similarity calculation - dot products for a fairly big no of records or raw data of documents. During the work, I have used AI Tools to generate the images and sample data tables. The images are edited with draw.io as and when required. Rest of the pictures/plots are generated through the python program and matplotlib library -which can be found in Github https://github.com/piyasde/article companion/blob/main/vector service.py . In this article. we will try to explain about vector databases and their components in operations like chunking, indexing, metadata filtering, storage points in the below writing.This will help us to identify the operations around the vectors to make retrieval mostly right, scalable with fair request/response time with manageable infrastructures in mind. In a vector-search system, a vector database comes with many of the above responsibilities to form a reliable data service. To check the functional parts of the above components, we will build a test version of the work using FAISS , SQLite and NumPy . All of the software are free and available to be downloaded locally and we can test all of the above functional works in our own machine without any special need. An embedding model converts content to numerical vectors. A vector index structures the vectors to help in similarity search . A retrieval service operates for the records and the respective manipulations such as identifiers, original text, metadata, lifecycle, filtering, persistence, concurrency in production. There are other ancillary services and operations in a production system related to Vector Data Operations, which will be part of real-world applications. FAISS is a capable vector similarity search library and it is not a database server. FAISS can index and retrieve numerical vectors. The FAISS project documentation https://faiss.ai/ will have documentation for all the functional features. For our work, we will split these works with following logical components - This logical division will be focused for a task or a set of tasks. This will help us to understand the workarounds that an all-in-one vector database will serve for operations of semantic retrievals. Earlier in part 1 of this work https://pub.towardsai.net/why-vector-search-is-mathematically-right-and-still-give-the-answer-which-can-be-least-expected-6de0687d3ab9 , the corpus was an array M.shape = 15, 8 . Here records need a stable identity and a connection back to its source which is part of metadata. As an example for S03, we will have information like - ID: 3Document ID: S03Text: Battery banks supply electricity to lamps after sunset.Owner: SampleOrgnCategory: energyActive: yesEmbedding: 0, 1, 1, 1, 1, 0, 0, 0 before normalizationEncoder: concepts-v1 Most of the above data are meta information for the actual data. Here the numeric ID goes into the FAISS index , and a search will return it. The text and metadata will remain stored in SQLite . The record here also stores the normalized embedding for the indexing purpose to be rebuilt later. Production applications store document IDs , chunk offsets , source links , data ingestion timestamps , versions , content hashes and any other relevant information -which are part of the domain. The original text is stored as because - an embedding is not reversible compressed sentence. It is a data representation in numeric terms which is built to support the specific type of vector comparisons. After the search is giving us back the identifier of a sentence - here is - S03 , the application will have to show the original words to make the human readable display of words to be meaningful at any particular time. We need the model version to be specified and stored. If we change the encoder, it will change the vector space. We will never be able to mix our work specific 8-dimensional vectors with vectors from another model even in the case of the shapes happen to match. Always re-embedding and re-indexing are needed in the model after the change of the data. The model version changes with the embedding changes for the dataset. FAISS provides an exact inner-product index called IndexFlatIP . We normalize every non-zero embedding, so inner product equals cosine similarity . This is supported by the FAISS metric guide https://github.com/facebookresearch/faiss/wiki/MetricType-and-distances . Below is the example codebase with using FAISS . It uses the embed , unit , SENTENCES and QUERY definitions from the attached file for Part 1, this can be retrieved from Github https://github.com/piyasde/article companion/blob/main/vector search.py . python import faissimport numpy as npfrom vector search import SENTENCES, QUERY, embed, unitvectors = np.ascontiguousarray unit np.stack embed s for s in SENTENCES , dtype=np.float32 query = np.ascontiguousarray unit embed QUERY .reshape 1, -1 , dtype=np.float32 ids = np.arange 1, len SENTENCES + 1, dtype=np.int64 d = vectors.shape 1 index = faiss.IndexIDMap2 faiss.IndexFlatIP d index.add with ids vectors, ids scores, found ids = index.search query, 5 for score, doc id in zip scores 0 , found ids 0 : print f"S{doc id:02d}: {score:.4f} | {SENTENCES doc id - 1 }" In FAISS , IndexFlatIP compares vectors for inner product. We can use IndexIDMap2 for explicit 64-bit integer identifiers. In our 15 sentence dataset, this produces the ranking which is same as NumPy , with insignificant floating-point rounding and possible tie ordering. So we understand a point - FAISS has not made the previous embedding smarter . It has given us a structured and optimized implementation of numerical nearest-neighbour search. Here is a situation where our small corpus may belong to two organizations - ABC and XYZ . The labels are inserted here to work with metadata filtering. Here in our work, we assign sentences with S01, S02, S03, S04, S05, S12 and S14 identifier to ABC . Rest of the records belong to XYZ . Our question remains the same - How can electricity from sunshine keep lamps running after dark? If we search for the top 3 records, FAISS will give the result - In a situation, when we want to show records which are not in the scope of ABC — 2 records remain, even though ABC has at least 3 relevant searchable records. S01 is also appeared with a score of 0.7071 . So we filtered after limiting the global search to 3results. If we restrict candidates to ABC before finding its 3nearest vectors, the result will be - The global ranking contains a higher-scoring document owned by XYZ . It occupies a slot that should never have been eligible for ABC’s search. In our program, we can solve this by querying in SQLite for ABC ’s active records and then using NumPy to score those relevant candidates. The whole work is fairly doable for 15 documents. Below is the relevant code - rows = conn.execute "SELECT id, embedding FROM documents WHERE active=1 AND owner=?", "alpha", .fetchall X = np.vstack np.frombuffer row "embedding" , dtype=np.float32 for row in rows scores = X @ query.reshape -1 order = np.argsort -scores, kind="stable" :3 In a production system, where we will have millions of records, copying and scanning every vector will be too time-taking and expensive. Here full vector databases integrate payload filtering with their vector indexes - Qdrant’s filter-aware HNSW documentation https://qdrant.tech/documentation/manage-data/indexing/ is a good candidate to try for this reason. Retrieval filtering is not about security and mostly it is business rule of the environment. Authentication, authorization, tenant isolation and secure record access need enforcement by the production application and related data services. Pulling a large global top-K and filtering afterward will not always be best way to fill a tenant-specific top-K. Over-fetching may mitigate for some cases — it is not an universal correct solution. In production, after seeing the data and understanding the most used queries, we should choose the retrieval strategies. The NumPy matrix in earlier work example will not be stored when the Python process stops unless we save it. A FAISS index can be written to disk and loaded again - faiss.write index index, "energy flat.faiss" restored = faiss.read index "energy flat.faiss" print restored.ntotal This helps in serializing the vectors with one part of persistence. The original text, ownership, document IDs and content state are stored in the SQLLite . In the program https://github.com/piyasde/article companion/blob/main/vector service.py , these data are stored in normal SQLite file — here it is lab.sqlite3 as mentioned in the code-base with hard-coded filename. These 2 files are part of our work here. Following table is a comparison. With this separation of information, we have some situations like SQLite is updated and the process crashes before the FAISS index is saved . The 2 versions of data will not match at this stage. We can try to edit the SQLite files as the source of truth and then rebuilding FAISS from the previously stored active embeddings. That will work for the our experimental work but will not be a viable solution in production system with large datasets. Production systems will need viable write strategies with versioned index snapshots, incremental updates, write-ahead logs or queues, transactional coordination when and where supported. Also there should have recovery procedures and tests for failure within the defined steps of the production operation. A serialized FAISS index is not a transactional database kind of system with established procedures like replication etc. We should never load an non-trusted FAISS index file. The FAISS index I/O documentation https://github.com/facebookresearch/faiss/wiki/Index-IO%2C-cloning-and-hyper-parameter-tuning warns that integrity checking is the caller’s responsibility. In the work example, we have following words with identifier S02 — Rechargeable batteries store electrical energy for later use. Now when we edit it to — Solar batteries store electricity to power lamps after dark. — The texts are changed. So the representation has changed with changed words. Here we should encode the new version to make sure about the index — which will eventually use the new embedding. With our original query, S02 ’s cosine similarity changes from 0.3536 to 0.8944 . In our code, following functions are important for the above work. Reader can check these functions to understand FAISS usage - php def normalized 32 text: str - np.ndarray: """Encode and L2-normalize """ return np.ascontiguousarray unit embed text .astype np.float32 def score document conn: sqlite3.Connection, doc id: str, question: str - float: """Score stored vector directly, including before/after an update.""" row = conn.execute "SELECT embedding FROM documents WHERE doc id=? AND active=1", doc id, .fetchone if row is None: raise KeyError f"Active record not found: {doc id}" vector = np.frombuffer row "embedding" , dtype=np.float32 return float vector @ normalized 32 question def search global index, conn: sqlite3.Connection, question: str, k: int = 5 : Used for searching in Vector query = normalized 32 question if np.linalg.norm query == 0 or index.ntotal == 0: return scores, ids = index.search query.reshape 1, -1 , min k, index.ntotal result = for score, numeric id in zip scores 0 , ids 0 : if numeric id < 0: continue row = conn.execute "SELECT FROM documents WHERE id=? AND active=1", int numeric id , .fetchone if row is not None: result.append {"doc id": row "doc id" , "owner": row "owner" , "score": float score , "content": row "content" } return result Recomputing the embedding changes where S02 appears in the ranking. Altering the source text without updating the index would leave stale search results. The program https://github.com/piyasde/article companion/blob/main/vector service.py will perform the following steps - 1. Update S02 ’s text and make normalized embedding in SQLite. 2. Rebuild the FAISS index from the current records with the changed texts. 3. Search again to have confirmation about S02 ’s new ranking. 4. It will mark S13 inactive, rebuild the index again, and verify that — it no longer appears. Relevant code-base is here in the code https://github.com/piyasde/article companion/blob/main/vector service.py - before s02 = score document conn, "S02", QUERY update document conn, "S02", "Solar batteries store electricity to power lamps after dark." after s02 = score document conn, "S02", QUERY index = build index conn, backend print hits "After modifying S02 and rebuilding", search global index, conn, QUERY, 3 print f"S02 score changed: {before s02:.4f} - {after s02:.4f}" All FAISS index supports deletion or updates in the same way. As we see with documentation, HNSW index deletion behavior having differences from that of flat and inverted-file indexes. For our earlier database experiment, rebuilding the index removes ambiguity. At scale in production system, the index choice affects record update costs and we should decide upon the operational strategy beforehand. So we have to think about the end-to-end workflow for the semantic retrieval system and not just similarity search as it appears the most visible thing in the work. For 15 records, exact search is always a fair choice. It needs to be implemented for million documents and their converted vectors with multi dimensions. As an example, a single vector may require — 384 coordinates × 4 bytes = 1,536 bytes 10 million of vectors will require approximately 15 GB and higher raw vector storage even without considering text, IDs, indexes or database overhead. This plot is a storage baseline. Actual memory includes additional structures and depends on the data for the index. Exact search needs work proportional to both the number of vectors and their dimensions — O N × d for a query evaluated against all stored vectors. O N × d represents the computational complexity of an exact vector search. Here - N = Number of stored vectors sentences or document chunks . d = Number of dimensions numerical elements in each vector. In a production system efficient implementation, memory bandwidth and hardware are the part of consideration at the time of application design. Our thinking should be towards the parts of the collection - we need to inspect for a useful answer — while considering the best cost of the infrastructure and overall return on the investment. In a business language — how the semantic search implementation will improve customer experience and thus increased productivity and revenue and cost optimization in long term. This opens an idea for approximate nearest neighbor search ANN . Flat or exhaustive index — We can think of inspection of all book’s catalogue entry in a library and compare it with the search question. We will get the mostly nearest results under the chosen similarity metric. This is IndexFlatIP for normalized inner-product search. Inverted file IVF — We can divide the library into broad topic-like clusters. Then we inspect a selected number of clusters with better relevancy. FAISS uses trained centroids to assign vectors to lists. The important controls are nlist — the number of lists — and nprobe — the number searched at query time. When we have multiple search on lists, then the recall metric improves with the additional storage cost. Additional storage will be needed for these numerical clusters in system. Also we have to remember, during re-embedding, the additional clusters are to be rebuild. Hierarchical Navigable Small World HNSW - In such systems rather than checking every records, we will follow links toward neighbors of the query. HNSW uses a navigation oriented graph with layers. A tuning parameter such as efSearch controls the breadth of exploration. Increasing the tuning parameter improves recall with more search work and additional storage. Also other overheads are there during rebuilding or updating of the index. The FAISS index overview https://github.com/facebookresearch/faiss/wiki/Faiss-indexes and the original HNSW paper https://arxiv.org/abs/1603.09320 explain the underlying algorithms. ANN on a small collection with additional indexing and traversal overhead can make it slower. It is useful and applicable for large data based applications. For many tasks, exact retrieval is the better design engineering decision — it can be done in RDBMS with right kind of indexing based on the maximum query assumption. Our working program includes an ANN experiment using FAISS ’s Flat , HNSW and IVF indexes. It creates 64-dimensional vectors with fixed random seed and compares approximate results against exact Flat results. It measures Recall@10 which is defined as the number of top-10 neighbors recovered by an ANN result divided by 10 and averaged across the production test queries. This is ANN recall — which is a measured metric apart from human-judged semantic recall discussed in earlier work. The working python program records mean search time per query inside a batch of 100 queries and produces a recall-vs-latency chart. This is a local measurement and not p95 latency or general speed measurement about FAISS . We run — python vector service.py --backend faiss --benchmark --plots The important sections in the program are - Exact baselineflat = faiss.IndexFlatIP d Navigable graphhnsw = faiss.IndexHNSWFlat d, 16, faiss.METRIC INNER PRODUCT hnsw.hnsw.efSearch = 32 Coarse clustering + inner-product searchivf = faiss.IndexIVFFlat faiss.IndexFlatIP d , d, 64, faiss.METRIC INNER PRODUCT ivf.train training vectors IVF must be trained before adding vectorsivf.add database vectors ivf.nprobe = 8 These are geometric tests . Random vectors can show how an index behaves, they can not prove that a retrieval model understands solar energy, legal clauses or customer questions. We need real documents, representative questions and relevance answers. In practical cases, when we import n-page user manuals, we should not embed the whole manual as one vector based document. A single vector will have summaries for many topics and the data will be big enough. As a workaround we should divide the manual into sections or overlapping passages - with linkage of passages to its source document and page or section. The workflow will be like - Here we are chunking the data. Some trade-offs are — Short passages may lack necessary context, whereas long passages may dilute specific topics. Chunks with overlap can preserve context at boundaries and creates requirement of additional storage. Also there are ways to summarize texts in paragraphs and store or convert to vectors. There is no universal way of chunking method — it depends on the production system documents and questions. Nearest Neighbor Ranking is an important factor in Vector Search. We calculate the distance of data with their numerical vector form here. A higher cosine similarity score indicates greater directional similarity between vectors. Top-K retrieval means selecting the first K nearest results . Nearest-neighbor ranking is the first retrieval stage in a search path. Here in case of chunking, it stores most optimized links with actual context. We can go for a second-stage re-ranker which can store contextual information after analyzing the set of coverage queries. Lexical search can complement embedding search when we go for exact terms, entity codes, particular section numbers or error identifiers. With metadata filters we can exclude expired or stale content. It is matter of data verification and structuring stage, which we should analyze before doing the semantic search system design. A vector database is of specific requirements in production system because it can combine these above behaviors — there are functional requirement of operational components with main idea of cosine similarity . In a production system, following are the points - we have to remember - Relevance - Determination of the correct benchmark of sources for 100–200 representative questions of a production system — so to understand the Precision@K and semantic Recall@K change when we change encoders or chunk sizes/behavior and other components to improve the search behavior. Index quality - The ANN Recall@K scoring compared with exact Flat retrieval and efSearch or nprobe changes are in place. A short note on ANN — Approximate Nearest Neighbor is a search technique where vectors are likely to be closest to a query.ANN reduces search work within relevant regions within the vector space. ANN makes large vector search more efficient with a minimal trade-off on retrieval accuracy.This trade-off is commonly evaluated using Recall@K, latency, and memory consumption. Some relevant codes for the ANN bench-marking are shown below, which are in the code https://github.com/piyasde/article companion/blob/main/vector service.py also - php def benchmark path: Path, plots: bool, n: int = 10 000, d: int = 64 - None: ... k = 10 flat = faiss.IndexFlatIP d flat.add vectors , exact ids = flat.search queries, k hnsw = faiss.IndexHNSWFlat d, 16, faiss.METRIC INNER PRODUCT hnsw.hnsw.efConstruction = 80 hnsw.add vectors clusters = min 64, max 4, n // 60 ivf = faiss.IndexIVFFlat faiss.IndexFlatIP d , d, clusters, faiss.METRIC INNER PRODUCT ... ivf.train vectors :min n, max 3000, 50 clusters ivf.add vectors ... def measure label: str, idx : idx.search queries, k warm up start = time.perf counter , ids = idx.search queries, k total ms = time.perf counter - start 1000 recall = sum len set ids i & set exact ids i for i in range len queries / len queries k result = {"index": label, "vectors": n, "dimension": d, "recall at 10": float recall , ... results = measure "Flat exact", flat for ef in 8, 16, 32, 64 : hnsw.hnsw.efSearch = ef results.append measure f"HNSW ef={ef}", hnsw for nprobe in 1, 4, 16, 32 : ivf.nprobe = min nprobe, clusters results.append measure f"IVF nprobe={nprobe}", ivf All the bench-marking results are saved in csv, which will be generated after running the program. Security and filtering — All the result elements are to be constrained to the caller’s tenant or document set. We have to test for forbidden cross-tenant results. For a production application, the authorization context can be outside of the search functionality i.e.end-to-end application scope. Lifecycle - The data changes and soft/hard deletions are to be searchable within minimum possible time. We should be able to recover the search application after the application stop/start between updating the record store and updating the index. Capacity - The questions , we should understand before the search application design are like -how many vectors, how many dimensions, how much memory, how many writes and how many concurrent queries? We should measure the p50 and p95 latencies using real requests/response result set. Traceability — All the search paths and their return hit are to be logged in the system with the source passage, document version, access policy and other relevant measures in a production system. All of the above measurement will help us to choose the application components with much confidence. For a proof of concept application - an in-process index with a relational database may be right choice of application stack. In larger systems, a dedicated vector database will reduce the amount of infrastructure with a trade-off of cost in infrastructure. So Qdrant, Milvus, Weaviate, PostgreSQL with pgvector and other managed services are the alternatives in production system design. Their indexing, metadata-filtering, persistence, consistency, scaling, deployment models, cost of infrastructure — whether recurring for service or fixed upfront cost are the main part of consideration while implementing a Vector Database Environment. We need to install following libraries - python -m pip install numpy matplotlib faiss-cpu SQLite is already included with Python. We used Ubuntu 22.04 as our operating system. On a platform without a suitable FAISS wheel, consult FAISS installation options https://github.com/facebookresearch/faiss/blob/main/INSTALL.md . The work database demonstration includes a NumPy fallback so that the filtering, update and SQLite works can still be run without FAISS , the ANN benchmark requires FAISS . We should put vector-search.py and vector service.py in the same folder. Then we should run - FAISS-backed record and lifecycle demopython vector service.py --backend faiss Includes Flat, HNSW and IVF comparison and a chartpython vector service.py --backend faiss --benchmark --plots Storage / filtering / update demo even without FAISS installedpython vector service.py --backend numpy We will see the top 3 results the incomplete result from post-filtering the corrected top 3an updated sentence moving up in the rankinga deleted record disappearing after re-indexing. The program writes a SQLite file, and with FAISS installed, it saves and reloads the FAISS index. The benchmark writes CSV measurements. Our sample work is single-process and rebuilds its index after changes. It is not a production vector database implementation . Those are the boundaries which we had learned within our above work. Part 1 https://pub.towardsai.net/why-vector-search-is-mathematically-right-and-still-give-the-answer-which-can-be-least-expected-6de0687d3ab9 gave us the mathematics of finding similar sentences . In current article Part 2 we had gone through the mechanics of running vector search as a data service . We needed stable IDs, source records, metadata, filters, updates, persistent indexes and a way to decide abut the trade-offs when approximate retrieval is worth of the work requirement. The work separation matters because different results can originate in different places, which may hurt customer experience, cost over-run etc. Week trained encoders will create poor vectors. Mis-configured ANN index can miss most nearest neighbors. Bad document splitting can miss the relevant passage that contains the answer. Non-planned metadata filtering can return incomplete sets. Stale indexing can result outdated content. These are different failures with different constructive measurements. Here we can conclude that vector retrieval is a system, not a similarity functio n. The similarity calculation and the quality, scale and trustworthiness of everything around it are the things that make the application usable. - FAISS: Getting Started https://github.com/facebookresearch/faiss/wiki/Getting-started — basic indexes and searches. - FAISS: Indexes https://github.com/facebookresearch/faiss/wiki/Faiss-indexes — Flat, IVF, HNSW and compressed index families. - FAISS: Metric Types and Distances https://github.com/facebookresearch/faiss/wiki/MetricType-and-distances — inner product, L2 and cosine normalization. - FAISS: Guidelines to Choose an Index https://github.com/facebookresearch/faiss/wiki/Guidelines-to-choose-an-index — memory, speed and accuracy choices. - FAISS: Index I/O https://github.com/facebookresearch/faiss/wiki/Index-IO,-cloning-and-hyper-parameter-tuning — persistence and safe handling. - Qdrant: Indexing and Payload Indexes https://qdrant.tech/documentation/manage-data/indexing/ — filter-aware indexing in a vector database. - Malkov & Yashunin: HNSW https://arxiv.org/abs/1603.09320 — graph-based approximate nearest-neighbour search. Works of Vector Database after We Have Embeddings https://pub.towardsai.net/works-of-vector-database-after-we-have-embeddings-5113867eb63e was originally published in Towards AI https://pub.towardsai.net on Medium, where people are continuing the conversation by highlighting and responding to this story.