1.2 核心概念 — Milvus 数据模型与索引技术 本节导读:深入理解 Milvus 的数据模型、索引机制和查询原理,掌握向量相似性搜索的核心算法,为后续优化和实战奠定理论基础。 学习目标 理解 Milvus 的数据模型和架构设计 掌握向量的数学表示和距离度量方法 了解不同索引算法的原理和适用场景 熟悉查询优化和性能调优的基本方法 核心概念详解 数据模型 集合(Collection) 集合是 Milvus 中的逻辑数据单元,类似于关系数据库中的表。
本节导读:深入理解 Milvus 的数据模型、索引机制和查询原理,掌握向量相似性搜索的核心算法,为后续优化和实战奠定理论基础。
集合是 Milvus 中的逻辑数据单元,类似于关系数据库中的表。每个集合包含:
from pymilvus import CollectionSchema, FieldSchema, DataType # 定义 Schema schema = CollectionSchema([ FieldSchema("id", DataType.INT64, is_primary=True), FieldSchema("vector", DataType.FLOAT_VECTOR, dim=128), FieldSchema("metadata", DataType.JSON), FieldSchema("timestamp", DataType.INT64) ]) # 创建集合 collection = Collection("my_collection", schema)
Milvus 支持多种字段类型:
| 字段类型 | 说明 | 示例 |
|---|---|---|
| INT64 | 64位整数 | 用户ID、时间戳 |
| FLOAT_VECTOR | 单精度浮点向量 | 128维、256维向量 |
| BINARY_VECTOR | 二进制向量 | 8位、16位向量 |
| VARCHAR | 可变长字符串 | 文本、标签 |
| JSON | JSON对象 | 元数据配置 |
向量是多维空间中的点,每个维度代表一个特征。在 Milvus 中,向量通常表示为:
v = [v₁, v₂, v₃, ..., vₙ]
其中 n 是向量的维度(如 128、256、768 等)。
Milvus 支持多种距离度量方法:
import numpy as np def euclidean_distance(a, b): return np.sqrt(np.sum((a - b) ** 2)) # 示例 vector_a = np.array([1, 2, 3]) vector_b = np.array([4, 5, 6]) distance = euclidean_distance(vector_a, vector_b)
def inner_product(a, b): return np.dot(a, b) # 适合归一化向量 vector_a = np.array([0.5, 0.8, 0.2]) vector_b = np.array([0.3, 0.9, 0.1]) ip = inner_product(vector_a, vector_b)
暴力搜索算法,适用于小数据集:
# 创建 FLAT 索引 index_params = { "index_type": "FLAT", "metric_type": "L2", "params": {} } collection.create_index("vector", index_params) # 优点:精确查询,100% 准确率 # 缺点:时间复杂度 O(n),大数据集性能差
基于聚类的高效索引:
# 创建 IVF 索引 index_params = { "index_type": "IVF_FLAT", "metric_type": "L2", "params": {"nlist": 1024} # 聚类中心数量 } collection.create_index("vector", index_params)
分层可导航小世界图,目前性能最优:
# 创建 HNSW 索引 index_params = { "index_type": "HNSW", "metric_type": "L2", "params": { "ef": 40, # 搜索时的候选数量 "M": 16 # 每层的连接数量 } } collection.create_index("vector", index_params)
# 不同场景下的参数建议 high_performance_config = { "ef": 64, # 高精度 "M": 32 # 更好的连接 } fast_search_config = { "ef": 16, # 快速搜索 "M": 8 # 节省内存 }
# 创建分区 collection.create_partition("partition1") collection.create_partition("partition2") # 按时间分区 for year in range(2020, 2024): collection.create_partition(f"year_{year}") # 按类别分区 categories = ["tech", "sports", "entertainment"] for category in categories: collection.create_partition(category)
A:根据数据规模和精度要求选择:
A:
A:维度灾难是指随着向量维度的增加,向量之间的距离变得相对接近,导致相似性搜索的准确性下降。解决方法包括:
通过本节的学习,你已经深入理解了 Milvus 的数据模型、数学基础、索引技术和查询优化方法。这些知识将帮助你在实际项目中做出更好的架构决策。
关键词:Milvus, 向量数据库, 索引技术, 数据模型, 查询优化
难度:进阶
预计阅读:40 分钟