AI Wiki中文/EN

Vector databases: a nearest neighbor is only one part of the job

向量数据库

Persist vectors, enforce an embedding-space contract, and test filtering, updates and snapshots.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

The closest record has been deleted

A museum search service finds the perfect exhibit description. Unfortunately, that record was withdrawn yesterday. Another result belongs to the staff inventory. A third was encoded with an older model whose coordinates mean something different. None of these failures can be fixed by making nearest-neighbor search faster.

A vector index organizes vectors for similarity search. A vector database also manages the records around those vectors: stable identifiers, attributes, persistence, updates, deletion and visibility. The 2021 Milvus paper describes entities, attribute filtering, mutable storage segments and consistent reads alongside its index choices. These are properties of the system described in that paper, not a guarantee that every vector database implements identical semantics. Milvus, sections 2.1–2.4

Start with an ordinary keyed lookup when a visitor asks for an exact exhibit ID. Use lexical search for inventory codes and rare proper names. Add vector search when the task benefits from matching meaning across different wording, and compare it against those baselines. Buying a vector database does not establish that the embedding model understands the collection.

Updates, deletion and a retained backup change which records are visible.
Updates, deletion and a retained backup change which records are visible.

Define the eligible records before the nearest ones

Let a stored record contain an identifier, a vector, metadata and its source text:

ri=(idi,vi,mi,ti),vi∈Rd.r_i=(\mathrm{id}_i,v_i,m_i,t_i),\qquad v_i\in\mathbb R^d.

The embedding contract includes the encoder version, preprocessing, dimension, normalization and distance rule. Two vectors of equal length can inhabit incompatible learned spaces. A model migration therefore needs re-embedding or a separately versioned collection; changing a label on old vectors is insufficient.

At a specified read version, let an eligibility predicate encode the required attributes and visibility. The search target is then:

E(q)={i:eligible⁡(mi,q)=1},Rk(q)=arg topk⁡i∈E(q)[−δ(q,vi)].E(q)=\{i:\operatorname{eligible}(m_i,q)=1\},\qquad R_k(q)=\operatorname{arg\,topk}_{i\in E(q)}[-\delta(q,v_i)].

Our example uses squared Euclidean distance, so smaller is better:

δ(q,vi)=∑j=1d(qj−vij)2.\delta(q,v_i)=\sum_{j=1}^{d}(q_j-v_{ij})^2.

Filtering an unrestricted top-k list afterwards solves a different problem. With query zero, a staff vector at zero beats public vectors at distances 1 and 4. Taking only the unrestricted first result and then removing staff records returns nothing, although public results exist. Approximate indexes introduce an additional candidate-selection question; Faiss’s IVFADC description separates coarse candidate lists from distance computation. Faiss, physical PDF 2 and 6

For N eligible records, the deliberately simple implementation below scans every vector and fully sorts its scores:

T(N,d)=O(Nd+Nlog⁡N),S(N,d)=O(Nd).T(N,d)=O(Nd+N\log N),\qquad S(N,d)=O(Nd).

The space bound includes materialized vectors. A bounded heap can reduce the ranking term; an ANN index changes the search work and may sacrifice recall. Neither automatically defines update visibility or recovery behavior.

For a production workload, compare p50/p95 latency, eligible-set recall, memory and update lag under one documented query distribution. Define the lag being measured:

Lvisible=tfirst searchable−tacknowledged write.L_{\mathrm{visible}}=t_{\mathrm{first\ searchable}}-t_{\mathrm{acknowledged\ write}}.

This is a measurement definition, not a promise that all systems have positive lag or the same write acknowledgment contract.

A small store that survives reopening

Run this standalone program with Python 3.12; it uses only the standard library. SQLite stores authored two-dimensional vectors as JSON. A primary key makes an upsert replace one record. Parameterized SQL filters the tenant before computing distances. An explicit encoder name and dimension guard the collection when opened. Here the caller must obey that contract: the store cannot discover which model actually produced a numerical vector.

"""Original exact-search SQLite teaching store; no ANN or distributed guarantees."""
import json
import math
import sqlite3
import tempfile
from pathlib import Path


class Store:
    def __init__(self, path, dimension=2, encoder='museum-v1'):
        if not isinstance(dimension, int) or dimension < 1 or not encoder:
            raise ValueError('positive dimension and named encoder required')
        self.db = sqlite3.connect(path)
        self.dimension, self.encoder = dimension, encoder
        self.db.execute('CREATE TABLE IF NOT EXISTS config (id INTEGER PRIMARY KEY, dimension INTEGER, encoder TEXT)')
        self.db.execute('CREATE TABLE IF NOT EXISTS items (id TEXT PRIMARY KEY, tenant TEXT, vector TEXT, text TEXT)')
        old = self.db.execute('SELECT dimension, encoder FROM config WHERE id=1').fetchone()
        if old and old != (dimension, encoder):
            self.db.close()
            raise ValueError('incompatible embedding space')
        self.db.execute('INSERT OR IGNORE INTO config VALUES (1, ?, ?)', (dimension, encoder))
        self.db.commit()

    def vector(self, vector):
        v = list(map(float, vector))
        if len(v) != self.dimension or not all(math.isfinite(x) for x in v):
            raise ValueError('invalid vector')
        return v

    def put(self, identity, tenant, vector, text):
        v = self.vector(vector)
        if not identity or not tenant:
            raise ValueError('identity and tenant required')
        with self.db:
            self.db.execute('INSERT INTO items VALUES (?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET tenant=excluded.tenant, vector=excluded.vector, text=excluded.text', (identity, tenant, json.dumps(v), text))

    def delete(self, identity):
        with self.db:
            self.db.execute('DELETE FROM items WHERE id=?', (identity,))

    def search(self, query, tenant, k=2):
        q = self.vector(query)
        if not isinstance(k, int) or k < 0 or not tenant:
            raise ValueError('nonnegative k and tenant required')
        # One SELECT materializes one read result before distance calculation.
        rows = self.db.execute('SELECT id, vector FROM items WHERE tenant=?', (tenant,)).fetchall()
        scores = [(sum((a-b)**2 for a, b in zip(q, json.loads(v))), identity) for identity, v in rows]
        return sorted(scores)[:k]

    def snapshot(self, target):
        # SQLite backup, not an emulation of a distributed snapshot protocol.
        with sqlite3.connect(target) as other:
            self.db.backup(other)

    def close(self):
        self.db.close()


def demo():
    with tempfile.TemporaryDirectory() as folder:
        path = str(Path(folder)/'live.db'); snap = str(Path(folder)/'snapshot.db')
        s = Store(path)
        s.put('private', 'staff', [0, 0], 'Staff inventory')
        s.put('orion', 'public', [1, 0], 'Orion exhibit')
        s.put('lyra', 'public', [2, 0], 'Lyra exhibit')
        before = s.search([0, 0], 'public')
        s.snapshot(snap)
        s.put('lyra', 'public', [.5, 0], 'Revised Lyra exhibit')
        updated = s.search([0, 0], 'public')
        s.delete('orion'); s.close()
        s = Store(path); after = s.search([0, 0], 'public'); s.close()
        s = Store(snap); frozen = s.search([0, 0], 'public'); s.close()
        return dict(before=before, updated=updated, restarted=after, snapshot=frozen,
                    public_counts=[len(before), len(updated), len(after), len(frozen)])


if __name__ == '__main__':
    print(json.dumps(demo(), allow_nan=False))

Public results initially have squared distances 1 and 4. Updating Lyra moves its distance to 0.25. After deleting Orion, closing and reopening the file leaves only Lyra. The backup still contains the earlier two records. Equal distances break ties by ID, so repeated runs are comparable.

Each mutation commits through a transaction. Search materializes the result of one SELECT before scoring; snapshot uses SQLite’s backup operation. These checks demonstrate this local implementation’s behavior. They do not reproduce Milvus’s segment layout, distributed snapshots or concurrent load performance. The Milvus paper explicitly treats dynamic storage and indexing as separate cooperating concerns. Milvus

The database cannot supply the missing policy

The tenant argument is an explicit filter, not authentication. A real service must derive allowed tenants from trusted request context and apply the same policy to vectors, source text, caches and citations. A client choosing its own tenant value is not an access-control system.

This program has no ANN index, replication, crash-injection test, historical version retention or embedding pipeline. Stable IDs are unique across tenants here. Deletion removes the live row, while the separately created backup intentionally keeps its old copy. Data retention must therefore cover backups as well as search results. A read that started before a deletion may legitimately observe an older state under a documented snapshot policy; “deleted” needs a defined visibility boundary.

Use exact scan as the reference for small eligible sets. If latency forces an ANN index, evaluate recall after filtering and include writes in the workload. The index choice is only one decision in a data lifecycle.

Test the contract

  1. Explain. Why does equal dimension fail to prove encoder compatibility? Answer: Dimension specifies the number of coordinates, not what each coordinate means. A new encoder may rotate or otherwise change the representation; matching old document vectors against new query vectors has no established similarity interpretation.
  2. Calculate. For query zero, a staff record has distance 0 and two public records have distances 1 and 4. What is public top-1? Answer: The record at distance 1. Unrestricted top-1 followed by filtering is empty and fails this target.
  3. Modify. Delete Orion after making a backup, then reopen both files. What should differ? Answer: The live file contains only Lyra; the independent backup retains both original public records. Assert the identities and scores, not merely the number of returned rows.
  4. Investigate. How would you compare an ANN-backed replacement? Answer: Freeze the encoder, metric, eligible set and query set; compare to exact results, then measure latency, memory and acknowledged-write visibility under updates. A read-only speed test cannot answer the update question.

Read storage and search together

Milvus explains why a vector service needs query processing, indexing and storage management. Faiss explains the numerical search machinery without serving as a complete account of database lifecycle semantics. Read ANN search for approximation and chunking for the records that enter the store. The examples here are original, synthetic and local; no published throughput claim is reproduced.

Make a prediction, then check

Why reject a query encoded with a different model even if its dimension matches?

Choose one answer

Learning objectives

  • Separate an index from the data lifecycle and retrieve only eligible records.
  • Run the original example, explain its counterexample and identify the untested deployment assumptions.

Prerequisites & connections

Explore related knowledge →

References

  1. Milvus: A Purpose-Built Vector Data Management System
    Jianguo Wang; Xiaomeng Yi; Rentong Guo; Hai Jin; Peng Xu; Shengjun Li; Xiangyu Wang; Xiangzhou Guo; Chengming Li; Xiaohai Xu; Kun Yu; Yuxing Yuan; Yinghao Zou; Jiquan Long; Yudong Cai; Zhenxiang Li; Zhifeng Zhang; Yihua Mo; Jun Gu; Ruiyi Jiang; Yi Wei; Charles Xie · 2021
  2. Billion-scale similarity search with GPUs — arXiv v1
    Jeff Johnson; Matthijs Douze; Hervé Jégou · 2017

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-20 · Single AI author. Recorded source scopes (some exact source objects reused from earlier checks): Physical PDF 1 identity and 3–4 system design: entities, filtering, mutable segments, storage and snapshot statement. Text read; benchmarks not reproduced. Viewed physical PDF2/6: exact squared-L2, IVFADC coarse/fine quantizers, candidate lists and PQ lookup tables; no GPU kernels or speed claims reproduced. 5 paired equations and four explained exercises. Executed persistence, snapshot, upsert/delete, eligibility, SQL parameter data and incompatible-space rejection. Tenant filter is not authentication; no ANN or distributed claim.

  • Executed persistence, snapshot, upsert/delete, eligibility, SQL parameter data and incompatible-space rejection. Tenant filter is not authentication; no ANN or distributed claim.
  • Four computed SVG variants per topic;12 numeric/geometry tests and42 responsive cases passed. Fourteen selected final captures directly viewed. Full article acceptance recorded separately.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.