Milvus 向量数据库入门篇

Milvus 设计之初就是为 AI 而生的一个高效的向量数据库,在大多数情况下,Milvus 的性能是其他向量数据库的 2-5 倍,它能实现万亿级向量的毫秒级相似性搜索,而且 Milvus 还是开源的。

安装 Milvus

  • 下面以一台 Ubuntu 24.04 系统部署为例,规划如下:
ip地址 配置 OS版本 Milvus版本
192.168.31.101 4C-16G-500GB Ubuntu 24.04.3 LTS Milvus 2.6.17
  • 安装 docker 29.0.0
curl -sL 'http://iso.sqlfans.cn/docker/install_docker_2900.sh' | bash
docker --version
  • 安装 docker-compose 5.1.4
curl -sL 'http://iso.sqlfans.cn/docker/install_docker_compose_514.sh' | bash
docker-compose --version
  • 配置 docker 加速
mkdir -p /etc/docker
curl http://iso.sqlfans.cn/config/docker/daemon.202504.json > /etc/docker/daemon.json
systemctl daemon-reload
systemctl restart docker
  • 通过 docker-compose 部署 milvus 2.6.17 及其依赖组件(etcd元数据存储、minio对象存储、woodpecker消息队列)
curl -s https://github.com/milvus-io/milvus/releases/latest/download/milvus-standalone-docker-compose.yml -o /opt/milvus-docker-compose.yml
# curl -s http://iso.sqlfans.cn/docker/yml/milvus-standalone-docker-compose.yml -o /opt/milvus-docker-compose.yml
cat /opt/milvus-docker-compose.yml | egrep "(2379|9000|9001|9091|19530)"
docker-compose -f /opt/milvus-docker-compose.yml up -d
docker ps -a

安装 UI 客户端

  • Milvus 服务安装之后,可以安装 Attu v2.6.5 客户端 连接 Milvus(示例地址 192.168.31.101:19530)

  • 查看 Milvus 节点信息如下:

使用 Milvus

  • 安装 python 3.12.3
curl -sL 'http://iso.sqlfans.cn/python/install_python_3123.sh' | bash
python3 --version
  • 使用 Milvus 通常通过其提供的 SDK(比如 PyMilvus)进行
#.安装pymilvus
pip3 install pymilvus
  • 准备一个通过 PyMilvus 操作 Milvus 数据库的 python 演示文件:
curl -s http://iso.sqlfans.cn/python/demo/milvus-pymilvus-demo.py -o /opt/milvus.py
  • 该 python 脚本的内容如下:
root@ubuntu:~# cat /opt/milvus.py 
# 1. 引入类
from pymilvus import MilvusClient, DataType, FieldSchema, CollectionSchema, Collection

# 2. 连接到 Milvus 实例
client: MilvusClient = MilvusClient(uri="http://192.168.31.101:19530")

# 3. 定义 Collection 的 Schema
fields = [
    FieldSchema(name="id", dtype=DataType.INT64, is_primary=True, auto_id=False),
    FieldSchema(name="vector", dtype=DataType.FLOAT_VECTOR, dim=128),  # 假设向量维度是 128
    FieldSchema(name="text", dtype=DataType.VARCHAR, max_length=512)   # 附加的标量字段
]
schema = CollectionSchema(fields, description="This is my first Milvus collection")

# 4. 创建 Collection (类似于传统数据库中的表, 用于存储具有相同结构的向量数据)
collection_name = "my_test_collection"
if client.has_collection(collection_name=collection_name):
    client.drop_collection(collection_name=collection_name)
client.create_collection(collection_name=collection_name, schema=schema)

# 5. 插入100条测试数据 (实际应用中, 这些向量会由深度学习模型生成)
import random
data = []
for i in range(100):
    data.append({
        "id": i,
        "vector": [random.random() for _ in range(128)],  # 实际需要替换为 embedding 后的向量, 否则查询不到数据
        "text": f"This is text number {i}"
    })

res = client.insert(collection_name=collection_name, data=data)
print(f"Inserted entities: {res}")

# 6. 创建索引
index_params = client.prepare_index_params()
index_params.add_index(
    field_name="vector",
    index_type="IVF_FLAT",   # 索引类型, 例如 IVF_FLAT, HNSW
    metric_type="L2",        # 距离度量, 例如 L2, COSINE
    params={"nlist": 128}    # 索引参数
)
client.create_index(collection_name=collection_name, index_params=index_params)
print("Index created.")

# 7. 加载 Collection (在进行搜索前必须加载)
client.load_collection(collection_name=collection_name)
print("Collection loaded.")

# 8. 执行向量搜索
query_vector = data[0].get('vector') # 查询向量
search_results = client.search(
    collection_name=collection_name,
    data=[query_vector],
    limit=5,                  # 返回前 5 个最相似的结果
    output_fields=["text"]    # 返回结果中包含 'text' 字段
)

print(f"\nSearch Results: {search_results}")
for hit in search_results[0]:
    print(f"ID: {hit['id']}, Distance: {hit['distance']}, Text: {hit['text']}")

# 9. 执行过滤搜索
filter_search_results = client.search(
    collection_name=collection_name,
    data=[query_vector],
    limit=3,
    filter="id > 50",  # 过滤条件, 只搜索 id 大于 50 的实体
    output_fields=["text"]
)
print("\nFiltered Search Results (id > 50):")
for hit in filter_search_results[0]:
    print(f"ID: {hit['id']}, Distance: {hit['distance']}, Text: {hit['text']}")

# 10. 测完删掉 Collection
# collection_name = "my_test_collection"
# client.drop_collection(collection_name=collection_name)
# print(f"Collection '{collection_name}' dropped.")
  • 该 python 脚本的执行结果如下:
root@ubuntu:~# python3 /opt/milvus.py     
Inserted entities: {'insert_count': 100, 'ids': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]}
Index created.
Collection loaded.

Search Results: data: [[{'id': 0, 'distance': 0.0, 'entity': {'text': 'This is text number 0'}}, {'id': 2, 'distance': 17.998577117919922, 'entity': {'text': 'This is text number 2'}}, {'id': 35, 'distance': 18.14667510986328, 'entity': {'text': 'This is text number 35'}}, {'id': 37, 'distance': 18.220375061035156, 'entity': {'text': 'This is text number 37'}}, {'id': 65, 'distance': 18.363632202148438, 'entity': {'text': 'This is text number 65'}}]]
ID: 0, Distance: 0.0, Text: This is text number 0
ID: 2, Distance: 17.998577117919922, Text: This is text number 2
ID: 35, Distance: 18.14667510986328, Text: This is text number 35
ID: 37, Distance: 18.220375061035156, Text: This is text number 37
ID: 65, Distance: 18.363632202148438, Text: This is text number 65

Filtered Search Results (id > 50):
ID: 65, Distance: 18.363632202148438, Text: This is text number 65
ID: 86, Distance: 18.62433624267578, Text: This is text number 86
ID: 85, Distance: 18.981603622436523, Text: This is text number 85
  • 通过 Attu 客户端看到的效果如下:

  • 下面演示如何删除 my_test_collection 这张测试表:
root@ubuntu:~# python3
>>> from pymilvus import MilvusClient, DataType, FieldSchema, CollectionSchema, Collection
>>> client: MilvusClient = MilvusClient(uri="http://192.168.31.101:19530")
>>> collection_name = "my_test_collection"
>>> client.drop_collection(collection_name=collection_name)
>>> quit()
Copyright © www.sqlfans.cn 2021 - 2026 All Right Reserved更新时间: 2026-09-01 12:20:15

results matching ""

    No results matching ""