ミルバス ベクター データベース
第1章 ミルバスの概要
Milvus は、ディープ ニューラル ネットワークやその他の機械学習 (ML )モデルによって生成された多数の埋め込みベクトルを保存、インデックス付け、管理するという 1 つの目標を掲げて 2019 年に作成されました。
ストレージ オブジェクト: ベクトル
NOTE:embedding vectors是对非结构化数据的特征抽象,比如电子邮件、物联网传感器数据、Instagram照片、蛋白质结构等等。现代嵌入技术用于将非结构化数据转换为嵌入向量,从数学上讲,嵌入向量是浮点数或二进制数的数组。
Milvus は、類似性距離を計算することで 2 つのベクトル間の相関を分析できます。2 つの埋め込みベクトルが非常に類似している場合、元のデータ ソースも類似していることを意味します。
1.1 関連アプリケーション
-
画像類似性検索: 画像は検索可能で、大規模なデータベースから最も類似した画像を即座に返します。
-
ビデオの類似性検索: キーフレームをベクトルに変換し、その結果を Milvus にフィードすることで、数十億のビデオをほぼリアルタイムで検索し、推奨できます。
-
オーディオの類似性検索: 音声、音楽、音響効果、表面的に類似したサウンドなどの大量のオーディオ データを迅速にクエリします。
-
分子類似性検索: 特定の分子の高速類似性検索、部分構造検索、または超構造検索を実行します。
-
推薦制度:推薦
公式サイト:https: //milvus.io/bootcamp/
1.2 Milvus はどのように設計されていますか?
クラウドネイティブのベクター データベースとして、Milvus は設計によりストレージと計算を分離します。回復力と柔軟性を強化するために、Milvus のすべてのコンポーネントはステートレスです。
システムは 4 つのレベルに分かれています。
-
アクセス層: アクセス層は、システムのフロントエンド層およびユーザーのエンドポイントとして機能する一連のステートレス プロキシで構成されます。
-
調整サービス: 調整サービスはタスクをワーカー ノードに割り当て、システムの頭脳として機能します。
-
ワーカー ノード: ワーカー ノードは腕と脚のようなもので、ダム実行者であり、コーディネーター サービスの指示に従い、ユーザーによってトリガーされた DML/DDL コマンドを実行します。
-
ストレージ: ストレージはシステムのバックボーンであり、データの永続性を担当します。メタストレージ、ログが含まれます
詳細については、「アーキテクチャの概要」を参照してください。
1.3 開発者ツール
Milvus は、DevOps を促進するための豊富な API とツールによってサポートされています。
Milvus には、アプリケーション コード内からデータをプログラムで挿入、削除、クエリするために使用できる、Milvus API 上にラップされたクライアント ライブラリがあります。
第 2 章 クイックスタート
2.1 Milvus のインストール
docker-composeを使用してインストールするMilvus Standalone
【ステップ1】ダウンロードしmilvus-standalone-docker-compose.yml
て名前を付けて保存docker-compose.yml
https://github.com/milvus-io/milvus/releases/download/v2.2.3/milvus-standalone-docker-compose.yml
リナックス
wget https://github.com/milvus-io/milvus/releases/download/v2.2.3/milvus-standalone-docker-compose.yml -O docker-compose.yml
[ステップ 2] とdocker-compose.yml
同じディレクトリで、すべてのdocker-compose
サービスを開始し、バックグラウンドで実行します。
docker-compose up -d
[ステップ 3]docker-compose
現在実行がスケジュールされているすべてのコンテナを表示する
docker-compose ps
故障中
docker-compose down
Milvusを停止後、データを削除して実行
sudo rm -rf volumes
第3章 学習
前提条件のダウンロード: PyMilvus 2.2.2
pip3 install pymilvus==2.2.2 -i https://pypi.tuna.tsinghua.edu.cn/simple
3.1Milvus 接続の管理 (接続管理)
Milvusサーバーに接続および切断する方法
milvus は 2 つのポートをサポートします: 19530、9091
-
gRPC はポート 19530 をサポートします
これは、異なる Milvus SDK の Milvus サーバーを接続する場合のデフォルトのポートです。
-
RESTful API はポート 9091 をサポートします
HTTPクライアントを使用してMilvusサーバーに接続する場合に使用されます。
Milvusサーバーに接続する
Milvus 接続を確立します。何かを行う前に、Milvus サーバーに接続していることを確認してください。
サンプルコード:
from pymilvus import connections
connections.connect(
alias="default",
host='localhost',
port='19530'
)
パラメータ | 説明 |
---|---|
alias |
構築する Milvus 接続のエイリアス。 |
host |
Milvus サーバーの IP アドレス。 |
port |
Milvus サーバー ポート。 |
戻り値: 渡されたパラメータによって作成された Milvus 接続
注: 最大接続数は 65,536 です。
Milvusサーバーが切断されました
サンプルコード:
connections.disconnect("default")
パラメータ | 説明 |
---|---|
alias |
切断する Milvus サーバーのエイリアス。 |
3.2 コレクションの管理 (コレクション管理)
作成するコレクションには、主キー フィールドとベクトル フィールドが含まれている必要があります。主キー フィールドでサポートされるデータ型は INT64 と String です。
スキーマの準備
まず、フィールド スキーマ、コレクション スキーマ、コレクション名などのパラメーターを準備します。
サンプルコード:
from pymilvus import CollectionSchema, FieldSchema, DataType
book_id = FieldSchema(
name="book_id",
dtype=DataType.INT64,
is_primary=True,
)
book_name = FieldSchema(
name="book_name",
dtype=DataType.VARCHAR,
max_length=200,
)
word_count = FieldSchema(
name="word_count",
dtype=DataType.INT64,
)
book_intro = FieldSchema(
name="book_intro",
dtype=DataType.FLOAT_VECTOR,
dim=2
)
schema = CollectionSchema(
fields=[book_id, book_name, word_count, book_intro],
description="Test book search"
)
collection_name = "book"
パラメータ | 説明 | オプション |
---|---|---|
FieldSchema |
作成するコレクション内のフィールドのスキーマ。 | 該当なし |
name |
作成するフィールドの名前 | 該当なし |
dtype |
作成するフィールドのデータ型。 | DataType.INT64 、DataType.VARCHAR 、DataType.BOOL 、DataType.INT64``DataType.FLOAT 、DataType.DOUBLE BINARY_VECTOR FLOAT_VECTOR |
is_primary 主キーフィールドは必須です |
作成するフィールドが主キーかどうか | True またFalse |
auto_id (主キーフィールドは必須です) |
ID (主キー) の自動割り当てを有効または無効にします。 | True またFalse |
max_length (VARCHAR フィールドには必須) |
挿入できる文字列の最大長。 | [1, 65,535] |
dim (ベクトルフィールドは必須です) |
ベクトルの次元数。 | [1, 32,768] |
description (オプション) |
フィールドの説明。 | 該当なし |
CollectionSchema |
作成するコレクションのスキーマ。 | 該当なし |
fields |
作成するコレクションのフィールド。 | 該当なし |
description (オプション) |
作成するコレクションの説明。 | 該当なし |
collection_name |
作成するコレクションの名前。 | 該当なし |
コレクションを作成する
サンプルコード:
from pymilvus import Collection
collection = Collection(
name=collection_name,
schema=schema,
using='default',
shards_num=2
)
パラメータ | 説明 | オプション |
---|---|---|
using オプション |
ここでサーバー エイリアスを指定して、コレクションを作成する Milvus サーバーを選択します。 | 該当なし |
shards_num オプション |
作成するコレクションのシャードの数。 | [1,256] |
properties: collection.ttl.seconds オプション |
TTL (Collection time to live) は、コレクションの有効期限です。期限切れのコレクション内のデータはクリーンアップされ、検索やクエリには関与しなくなります。TTL は秒単位です。 | 値は 0 以上である必要があります。0 は TTL をオフにすることを意味します。 |
限界
特徴 | 上限 |
---|---|
コレクション名の長さ | 255文字 |
コレクション内のパーティションの数 | 4,096 |
コレクション内のフィールドの数 | 64 |
コレクション内のシャードの数 | 256 |
コレクションを変更する
サンプルコード:
collection.set_properties(properties={
"collection.ttl.seconds": 1800})
TTL (コレクション存続期間) は、コレクション内のデータの有効期限です。コレクション内の期限切れのデータはクリーンアップされ、検索やクエリには関与しなくなります。TTL は秒単位です。値は 0 以上である必要があります。デフォルト値は 0、つまり TTL 機能は無効です。
コレクション情報を確認する
コレクションが存在するかどうかを確認する
from pymilvus import utility
utility.has_collection("book")
コレクションの具体的な情報を確認する
from pymilvus import Collection
collection = Collection("book") # Get an existing collection.
collection.schema # Return the schema.CollectionSchema of the collection.
collection.description # Return the description of the collection.
collection.name # Return the name of the collection.
collection.is_empty # Return the boolean value that indicates if the collection is empty.
collection.num_entities # Return the number of entities in the collection.
collection.primary_field # Return the schema.FieldSchema of the primary key field.
collection.partitions # Return the list[Partition] object.
collection.indexes # Return the list[Index] object.
collection.properties # Return the expiration time of data in the collection.
この Milvus インスタンス内のすべてのコレクションをリストします。
from pymilvus import utility
utility.list_collections()
コレクションをドロップする (コレクションを削除する)
from pymilvus import utility
utility.drop_collection("book")
コレクションエイリアス (コレクションエイリアス)
コレクションの別名管理。別名の長さは 255 文字を超えることはできません
コレクションのエイリアスを作成する
from pymilvus import utility
utility.create_alias(
collection_name = "book",
alias = "publication"
)
コレクションのエイリアスを削除する
from pymilvus import utility
utility.drop_alias(alias = "publication")
コレクションのエイリアスを変更する
from pymilvus import utility
utility.alter_alias(
collection_name = "book",
alias = "publication"
)
コレクションをロードする (コレクションをロードする)
コレクションをメモリにロードします。Milvus のすべての検索操作とクエリ操作はメモリ内で実行されます。
サンプルコード:
from pymilvus import Collection
collection = Collection("book") # Get an existing collection.
collection.load(replica_number=2)
パラメータ | 説明 |
---|---|
partition_name (オプション) |
ロードするパーティション名 |
replica_number (オプション) |
ロードするコピーの番号 |
コピー情報を取得する
from pymilvus import Collection
collection = Collection("book") # Get an existing collection.
collection.load(replica_number=2) # Load collection as 2 replicas
result = collection.get_replicas()
print(result)
コレクションをリリースする (コレクションをリリースする)
メモリからコレクションを解放してメモリ使用量を削減します。
サンプルコード:
from pymilvus import Collection
collection = Collection("book") # Get an existing collection.
collection.release()
3.3 パーティションの管理(パーティション管理)
パーティションの作成 (パーティションの作成)
Milvus を使用すると、大量のベクトル データを少数のパーティションに分割でき、検索やその他の操作を 1 つのパーティションに制限してパフォーマンスを向上させることができます。
コレクションは 1 つ以上のパーティションで構成されます。新しいコレクションを作成するとき、Milvus はデフォルトのパーティションを作成します_default
。
コレクション内のパーティションの数は 4096 を超えることはできません
例:コレクションブックにパーティション小説を作成します。
from pymilvus import Collection
collection = Collection("book") # Get an existing collection.
collection.create_partition("novel")
パーティション情報の確認 (パーティション情報の確認)
1) パーティションがあるかどうかを確認しますcollection.has_partition()
from pymilvus import Collection
collection = Collection("book") # Get an existing collection.
collection.has_partition("novel")
2) すべてのパーティションをリストします。collection.partitions
from pymilvus import Collection
collection = Collection("book") # Get an existing collection.
collection.partitions
パーティションの削除
指定されたコレクション内のパーティションを削除します
collection.drop_partition("novel")
パラメータ | 説明 |
---|---|
partition_name |
削除するパーティションの名前。 |
パーティションをロードする
パーティションをメモリにロードする
将分区而不是整个集合加载到内存中可以显著降低内存使用,Milvus中的所有搜索和查询操作都在内存中执行。
from pymilvus import Collection
collection = Collection("book") # Get an existing collection.
collection.load(["novel"], replica_number=2)
from pymilvus import Partition
partition = Partition("novel") # Get an existing partition.
partition.load(replica_number=2)
Parameter | Description |
---|---|
partition_name |
分区名称。 |
replica_number (optional) |
要加载的副本的编号。 |
Get replica information(获取副本信息)
示例代码:
from pymilvus import Partition
partition = Partition("novel") # Get an existing partition.
partition.load(replica_number=2) # Load partition as 2 replicas
result = partition.get_replicas()
print(result)
Release a Partition(释放分区)
在执行搜索或查询操作后,将分区从内存中释放,以减少对内存的占用。
示例代码:
from pymilvus import Partition
partition = Partition("novel") # Get an existing partition.
partition.release()
Parameter | Description |
---|---|
partition_name |
分区的名称 |
3.4Manage Data(数据管理)
Insert Entities(插入实体)
Prepare data(准备数据)
首先,准备要插入的数据。要插入的数据的数据类型必须与集合的模式匹配,否则Milvus将引发异常。
import random
data = [
[i for i in range(2000)],
[str(i) for i in range(2000)],
[i for i in range(10000, 12000)],
[[random.random() for _ in range(2)] for _ in range(2000)],
]
Insert data to Milvus(数据存储)
指定partition_name
,选择将数据插入哪个分区。
from pymilvus import Collection
collection = Collection("book") # Get an existing collection.
mr = collection.insert(data)
Parameter | Description |
---|---|
data |
Data to insert into Milvus. |
partition_name (optional) |
要插入数据的分区名称。 |
Delete Entities(删除实体)
Milvus支持通过布尔表达式过滤的主键删除实体。
Prepare boolean expression
Milvus只支持删除带有明确指定主键的实体,这可以通过术语 in
实现
其他运算符只能用于向量搜索中的查询或标量过滤。
下面的示例过滤主键值为0和1的数据。
expr = "book_id in [0,1]"
Delete entities
删除满足布尔表达式的实体。Milvus返回已删除实体的ID列表。
from pymilvus import Collection
collection = Collection("book") # Get an existing collection.
collection.delete(expr)
Parameter | Description |
---|---|
expr |
布尔表达式,指定要删除的实体。 |
partition_name (optional) |
删除实体的分区名称。 |
3.5Manage Indexes(索引管理)
Build an Index on Vectors
向量索引是元数据的组织单位,用于加速向量相似性搜索。如果没有建立在向量上的索引,Milvus将默认执行暴力搜索。
下面的例子用欧几里得距离(L2)作为相似度度量来构建一个1024个集群的IVF_FLAT索引。
更多的相似度测量:https://milvus.io/docs/metric.md
Prepare index parameter
index_params = {
"metric_type":"L2",
"index_type":"IVF_FLAT",
"params":{
"nlist":1024}
}
参数说明:
1)metric_type 用于度量向量相似性的度量类型。
- 浮点向量
L2
(Euclidean distance) 欧几里得距离IP
(Inner product) 内积(即点积)
- 二进制向量
JACCARD
(Jaccard distance) 杰卡德距离TANIMOTO
(Tanimoto distance) Tanimoto距离HAMMING
(Hamming distance) 海明距离SUPERSTRUCTURE
(Superstructure)SUBSTRUCTURE
(Substructure)
2)index_type 用于加速向量搜索的索引类型。
-
浮点向量
FLAT
(FLAT)IVF_FLAT
(IVF_FLAT)IVF_SQ8
(IVF_SQ8)IVF_PQ
(IVF_PQ)HNSW
(HNSW)ANNOY
(ANNOY)DISKANN*
(DISK_ANN)
-
二进制向量
BIN_FLAT
(BIN_FLAT)BIN_IVF_FLAT
(BIN_IVF_FLAT)
3)params
针对索引构建参数,请参阅内存索引和磁盘索引。See In-memory Index and On-disk Index for more information.
Build index
针对向量字段构建索引
通过指定向量字段名和索引参数来构建索引。
from pymilvus import Collection
collection = Collection("book") # Get an existing collection.
collection.create_index(
field_name="book_intro",
index_params=index_params
)
Parameter | Description |
---|---|
field_name |
要在其上构建索引的向量字段的名称。 |
index_params |
要构建的索引的参数。 |
Build an Index on Scalars
针对标量构建索引。
不像向量,向量有大小和方向,标量只有大小。Milvus将单个数字和字符串视为标量。下面是Milvus中标量字段可用数据类型的列表。
为了加快混合搜索中的属性过滤,从Milvus v2.1.0开始,可以在标量字段上构建索引。
Build index
针对标量构建索引
要在标量字段上构建索引,不需要设置任何索引参数。标量字段索引名的默认值为default_idx。您可以将它设置为另一个合适的值。
下面的代码片段假设一个名为book
的集合已经存在,并且要在字符串字段book_name
上创建索引。
from pymilvus import Collection
collection = Collection("book")
collection.create_index(
field_name="book_name",
index_name="scalar_index",
)
collection.load()
一旦创建了索引,可以在向量相似度搜索中包含一个布尔表达式:
search_param = {
"data": [[0.1, 0.2]],
"anns_field": "book_intro",
"param": {
"metric_type": "L2", "params": {
"nprobe": 10}},
"limit": 2,
"expr": "book_name like \"Hello%\"",
}
res = collection.search(**search_param)
Drop an Index(删除一个索引)
示例代码:
from pymilvus import Collection
collection = Collection("book") # Get an existing collection.
collection.drop_index()
3.6Search And Query
Conduct a Vector Similarity Search(向量相似度搜索)
Milvus中的向量相似搜索,计算查询向量与集合中具有指定相似度量的向量之间的距离,并返回最相似的结果。通过指定筛选标量字段或主键字段的布尔表达式【boolean expression 】,您可以执行混合搜索【 hybrid search 】,甚至使用Time Travel【 Time Travel】进行搜索。
需求:在包含图书ID(主键)、字数(标量字段)和图书介绍(向量字段)的2000行数据集上执行向量相似度搜索,模拟基于向量搜索某些图书的情况。Milvus将根据定义的查询向量和搜索参数返回最相似的结果。
Load collection 加载集合
Milvus中的所有搜索和查询操作都在内存中执行。在进行向量相似性搜索之前,将集合加载到内存中。
from pymilvus import Collection
collection = Collection("book") # Get an existing collection.
collection.load()
Prepare search parameters 准备查询参数
准备适合搜索场景的参数。
下面的示例定义了搜索策略,使用欧几里得距离计算距离,并从IVF_FLAT索引构建的10个最近的群集中检索向量。
search_params = {
"metric_type": "L2", "params": {
"nprobe": 10}, "offset": 5}
Parameter | Description |
---|---|
metric_type |
用于度量向量的相似性策略。See Simlarity Metrics for more information. |
params |
特定于索引的搜索参数. See Vector Index for more information. |
Conduct a vector search 执行向量查询
若要在特定分区 partition中搜索,请指定分区名称列表。
results = collection.search(
data=[[0.1, 0.2]],
anns_field="book_intro",
param=search_params,
limit=10,
expr=None,
consistency_level="Strong"
)
Parameter | Description |
---|---|
data |
用于搜索的向量 |
anns_field |
要搜索的字段的名称。 |
param |
特定于索引的搜索参数。See Vector Index for more information. |
offset |
返回集中要跳过的结果数。这个值和“limit”的和应该小于16384。 |
limit |
数最相似的结果返回。这个值和offset的和应该小于16384。 |
expr |
用于过滤属性的布尔表达式. See Boolean Expression Rules for more information. |
partition_names (optional) |
要搜索的分区的名称列表。 |
output_fields (optional) |
要返回的字段的名称。当前版本不支持向量字段。 |
timeout (optional) |
允许RPC的持续时间(以秒为单位)。当设置为None时,客户端等待服务器响应或发生错误。 |
round_decimal (optional) |
返回距离的小数位数 |
consistency_level (optional) |
搜索的一致性级别。 |
检查最相似向量的主键值及其距离。
results[0].ids
results[0].distances
释放在Milvus中加载的集合,以减少搜索完成时的内存消耗。
collection.release()
Conduct a Hybrid Search(混合搜索)
混合搜索本质上是带有属性过滤的向量搜索,通过指定过滤标量字段或主键字段的布尔表达式,可以用某些条件限制搜索。
需求:假设根据向量化搜索某些书籍,但只想要字数在特定范围内的书籍,然后可以指定布尔表达式来过滤搜索参数中的word_count字段。Milvus将只在与表达式匹配的实体中搜索相似的向量。
Load collection(加载集合)
from pymilvus import Collection
collection = Collection("book") # Get an existing collection.
collection.load()
Conduct a hybrid vector search(执行混合向量搜索)
通过指定布尔表达式,可以在向量搜索期间过滤实体的标量字段。
示例代码:将搜索范围限制为指定的word_count值范围内的向量。
search_param = {
"data": [[0.1, 0.2]],
"anns_field": "book_intro",
"param": {
"metric_type": "L2", "params": {
"nprobe": 10}},
"offset": 0,
"limit": 2,
"expr": "word_count <= 11000",
}
res = collection.search(**search_param)
NOTE:collection.search
返回结果为 SearchResult对象,一个可迭代的2d数组类,其第一个维度是要查询的向量数(nq),第二个维度是极限数(topk)。
Conduct a Vector Query(向量查询)
与向量相似度搜索不同,向量查询通过基于布尔表达式的标量过滤来检索向量。Milvus支持标量字段中的许多数据类型和各种布尔表达式。布尔表达式对标量字段或主键字段进行筛选,并检索与筛选器匹配的所有结果。
需求:对2000行的图书ID(主键)、字数(标量字段)和图书介绍(向量字段)数据集执行向量查询,模拟根据其ID查询某些图书的情况。
Load collection(加载集合)
from pymilvus import Collection
collection = Collection("book") # Get an existing collection.
collection.load()
Conduct a vector query(执行向量查询)
res = collection.query(
expr = "book_id in [2,4,6,8]",
offset = 0,
limit = 10,
output_fields = ["book_id", "book_intro"],
consistency_level="Strong"
)
3.7Similarity Metrics
在Milvus中,相似性度量用于度量向量之间的相似性。选择一个好的距离度量有助于显著提高分类和聚类性能。下表显示了这些广泛使用的相似性度量如何与各种输入数据形式和Milvus索引相匹配。
欧式距离(L2)
其中,a = (a1, a2,…), an) 、b = (b1, b2,…, bn)是n维欧几里德空间中的两个点。
适用于连续性数据
内积(IP)
两个向量之间的内积定义如下:
其中A和B是向量。