> For the complete documentation index, see [llms.txt](https://litedb.gitbook.io/litedb-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://litedb.gitbook.io/litedb-docs/architecture_and_design/vector_index/distance_and_flat.md).

# 向量键、距离与精确扫描

## VectorIndexKey

向量进入任何索引前都会转换为 `VectorIndexKey`。合法键必须：

* 来自 `VECTOR` 值；
* 至少包含一个元素；
* 所有元素均为有限浮点数；
* 维度与索引描述符完全一致。

因此 `NaN`、正负无穷和维度错误会在距离计算或图修改前被拒绝。`NULL` 由引擎提前跳过，不是一种向量键。

## 距离度量

所有后端共享 `vector_distance`：

| 度量            | 返回值                     | 越近的含义        |
| ------------- | ----------------------- | ------------ |
| L2            | 欧氏距离                    | 值越小          |
| Inner Product | 负内积                     | 原始内积越大，返回值越小 |
| Cosine        | `1 - cosine_similarity` | 方向越相近，值越小    |

L2 使用缩放累积算法降低平方和中间溢出的风险。内积使用更宽的中间精度。最终结果若不能表示为有限 `double`，会返回数值溢出错误。

余弦距离把相似度限制在 `[-1, 1]`，减少浮点误差导致的非法范围。任一向量为零向量时，距离定义为 `1.0`。

三个度量都统一为“距离越小越近”，因此 top-k 排序和 HNSW 候选队列无需为不同度量改变方向。

## 结果的确定性

搜索结果先按距离升序排列；距离相同时按 `RecordId` 升序排列。这一规则同时用于 Flat 和 HNSW 的最终结果。

## FlatIndex

Flat 后端不建立额外文件或内存条目。每次查询：

1. 获取集合扫描游标；
2. 跳过向量列为 `NULL` 的记录；
3. 验证每个向量；
4. 计算与查询向量的精确距离；
5. 使用大小不超过 `top_k` 的堆保留最近结果；
6. 最后按稳定规则升序输出。

时间复杂度近似为 `O(N × dimension)`，额外候选内存为 `O(top_k)`。

`top_k == 0` 直接返回空结果。若 `top_k` 大于非空向量记录数，则返回全部可用记录。

## Flat 的维护语义

因为数据源始终是 `StorageEngine`：

* `insert` 只验证传入键；
* `erase` 不执行任何操作；
* `size()` 始终返回 0；
* 集合数据更新后无需重建 Flat 索引。

这使 Flat 成为精确性基线和小数据集方案，但当前 Catalog 创建路径不产生 Flat 类型的持久化索引定义。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://litedb.gitbook.io/litedb-docs/architecture_and_design/vector_index/distance_and_flat.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
