# chromadb.errors.DimensionError：插入的嵌入维度（512）与集合维度（768）不匹配

- **ID:** `llm/embedding-dimension-mismatch-insert`
- **领域:** llm
- **类别:** data_error
- **错误码:** `DimensionError`
- **验证级别:** ai_generated
- **修复率:** 85%

## 根因

用于插入的嵌入模型生成的向量维度与创建集合时使用的模型维度不同，通常是由于切换了嵌入模型或使用了不同输出维度的模型。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| chromadb==0.4.22 | active | — | — |
| chromadb==0.5.0 | active | — | — |
| sentence-transformers==2.2.2 | active | — | — |
| openai==1.12.0 | active | — | — |

## 解决方案

1. ```
   删除现有集合并使用相同的嵌入模型重新创建，该模型将用于所有插入。例如，在 ChromaDB 中：`client.delete_collection("my_collection"); collection = client.create_collection(name="my_collection", embedding_function=current_embedding_function)`
   ```
2. ```
   如果必须保留现有集合，请使用新模型重新嵌入所有现有文档并重新插入。使用脚本遍历所有文档，调用 `embedding_model.encode(doc)` 并更新到集合中。
   ```
3. ```
   创建集合时显式设置嵌入函数维度：`collection = client.create_collection(name="my_collection", metadata={"hnsw:space": "cosine"}, embedding_function=current_embedding_function)` 并验证 `collection.metadata['dimension']` 是否与您的模型输出匹配。
   ```

## 无效尝试

- **** — Padding distorts the vector space and ruins retrieval accuracy; the collection's distance metrics expect all vectors to have the same semantic dimensionality. (95% 失败率)
- **** — ChromaDB infers dimension from the first inserted embedding; if the first insert uses the wrong model, the same mismatch occurs again. (80% 失败率)
- **** — Reshaping changes the data layout but not the semantic content; distance computations become meaningless and retrieval degrades to random. (90% 失败率)
