
類型:向量數(shù)據(jù)庫
簡介:存儲、索引和管理由深度神經(jīng)網(wǎng)絡(luò)和機器學(xué)習(xí)(ML)模型生成的大規(guī)模嵌入向量。
Milvus是一個開源向量數(shù)據(jù)庫,適用于各種規(guī)模的AI應(yīng)用程序,從在Jupyter筆記本中運行演示聊天機器人到構(gòu)建服務(wù)數(shù)十億用戶的Web規(guī)模搜索。本文將介紹如何在幾分鐘內(nèi)在本地設(shè)置Milvus,并使用Python客戶端庫來生成、存儲和搜索向量。
一、安裝Milvus
下面將使用MilvusLite嵌入到客戶端應(yīng)用程序中的python庫。Milvus還支持在Docker和Kubernetes上進行部署,用于生產(chǎn)用例。
在開始之前,請確保本地環(huán)境中有可用的Python3.8+。安裝其中包含python客戶端庫和MilvusLite:
$ pip install -U pymilvus
如果使用的是GoogleColab,要啟用剛剛安裝的依賴項,可能需要重新啟動運行時。(單擊屏幕頂部的“運行時”菜單,然后從下拉菜單中選擇“重新啟動會話”。)
二、設(shè)置向量數(shù)據(jù)庫
要創(chuàng)建本地Milvus向量數(shù)據(jù)庫,只需指定一個文件名來存儲所有數(shù)據(jù),例如“milvus_demo.db”。
from pymilvus import MilvusClient client = MilvusClient("milvus_demo.db")
三、創(chuàng)建集合
在Milvus中,我們需要一個集合來存儲向量及其相關(guān)的元數(shù)據(jù)??梢詫⑵湟暈閭鹘y(tǒng)SQL數(shù)據(jù)庫中的表。創(chuàng)建集合時,可以定義架構(gòu)和索引參數(shù)來配置向量規(guī)格,例如維度、索引類型和距離指標。此外,還有一些復(fù)雜的概念可用于優(yōu)化索引以實現(xiàn)向量搜索性能。現(xiàn)在,讓我們只關(guān)注基礎(chǔ)知識,并對所有可能的事物使用默認值。至少,只需要設(shè)置集合名稱和集合的向量字段的維度。
if client.has_collection(collection_name="demo_collection"): client.drop_collection(collection_name="demo_collection") client.create_collection( collection_name="demo_collection", dimension=768, # The vectors we will use in this demo has 768 dimensions )
在上述設(shè)置中,主鍵和向量字段使用其默認名稱(“id”和“vector”)。度量類型(向量距離定義)設(shè)置為其默認值(COSINE)。主鍵字段接受整數(shù),不會自動遞增(即不使用auto-id功能)?;蛘撸梢园凑沾苏f明正式定義集合的架構(gòu)。
四、準備數(shù)據(jù)
接下來使用向量對文本執(zhí)行語義搜索,需要通過下載嵌入模型來生成文本向量,可以通過使用庫中的實用函數(shù)輕松完成。
五、用向量表示文本
首先,安裝模型庫。此包包括PyTorch等基本ML工具。如果本地環(huán)境從未安裝過PyTorch,則包下載可能需要一些時間。
$ pip install "pymilvus[model]"
使用默認模型生成向量嵌入。Milvus期望數(shù)據(jù)以字典列表的形式輸入,其中每個字典代表一個數(shù)據(jù)記錄,稱為一個實體。
from pymilvus import model embedding_fn = model.DefaultEmbeddingFunction() docs = [ "Artificial intelligence was founded as an academic discipline in 1956.", "Alan Turing was the first person to conduct substantial research in AI.", "Born in Maida Vale, London, Turing was raised in southern England.", ] vectors = embedding_fn.encode_documents(docs) print("Dim:", embedding_fn.dim, vectors[0].shape) # Dim: 768 (768,) data = [ {"id": i, "vector": vectors[i], "text": docs[i], "subject": "history"} for i in range(len(vectors)) ] print("Data has", len(data), "entities, each with fields: ", data[0].keys()) print("Vector dim:", len(data[0]["vector"]))
Dim: 768 (768,) Data has 3 entities, each with fields: dict_keys(['id', 'vector', 'text', 'subject']) Vector dim: 768
或者使用隨機向量的虛假表示:
如果由于網(wǎng)絡(luò)問題而無法下載模型,則可以使用隨機向量來表示文本,同時仍能完成示例。請注意,搜索結(jié)果不會反映語義相似性,因為向量是假的。
import random # Text strings to search from. docs = [ "Artificial intelligence was founded as an academic discipline in 1956.", "Alan Turing was the first person to conduct substantial research in AI.", "Born in Maida Vale, London, Turing was raised in southern England.", ] # Use fake representation with random vectors (768 dimension). vectors = [[random.uniform(-1, 1) for _ in range(768)] for _ in docs] data = [ {"id": i, "vector": vectors[i], "text": docs[i], "subject": "history"} for i in range(len(vectors)) ] print("Data has", len(data), "entities, each with fields: ", data[0].keys()) print("Vector dim:", len(data[0]["vector"]))
Data has 3 entities, each with fields: dict_keys(['id', 'vector', 'text', 'subject']) Vector dim: 768
六、插入數(shù)據(jù)
將數(shù)據(jù)插入到集合中:
res = client.insert(collection_name="demo_collection", data=data) print(res)
{'insert_count': 3, 'ids': [0, 1, 2], 'cost': 0}
七、語義搜索與向量搜索
現(xiàn)在可以通過將搜索查詢文本表示為向量來進行語義搜索,并在Milvus上執(zhí)行向量相似性搜索。
Milvus支持單個或多個向量的搜索請求。query_vectors變量包含一個向量列表,其中每個向量是一個浮點數(shù)數(shù)組。
query_vectors = embedding_fn.encode_queries(["Who is Alan Turing?"]) res = client.search( collection_name="demo_collection", # target collection data=query_vectors, # query vectors limit=2, # number of returned entities output_fields=["text", "subject"], # specifies fields to be returned ) print(res)
data: ["[{'id': 2, 'distance': 0.5859944820404053, 'entity': {'text': 'Born in Maida Vale, London, Turing was raised in southern England.', 'subject': 'history'}}, {'id': 1, 'distance': 0.5118255615234375, 'entity': {'text': 'Alan Turing was the first person to conduct substantial research in AI.', 'subject': 'history'}}]"] , extra_info: {'cost': 0}
輸出是一個結(jié)果列表,每個結(jié)果對應(yīng)于一個搜索查詢。每個查詢的結(jié)果列表包括實體的主鍵、到查詢向量的距離,以及指定的.output_fields。
八、具有元數(shù)據(jù)過濾功能的向量搜索
你可以在進行向量搜索時考慮元數(shù)據(jù)(在Milvus中稱為“標量”字段)。這通過指定篩選表達式來實現(xiàn)。以下示例展示了如何使用字段進行搜索和篩選。
docs = [ "Machine learning has been used for drug design.", "Computational synthesis with AI algorithms predicts molecular properties.", "DDR1 is involved in cancers and fibrosis.", ] vectors = embedding_fn.encode_documents(docs) data = [ {"id": 3 + i, "vector": vectors[i], "text": docs[i], "subject": "biology"} for i in range(len(vectors)) ] client.insert(collection_name="demo_collection", data=data) res = client.search( collection_name="demo_collection", data=embedding_fn.encode_queries(["tell me AI related information"]), filter="subject == 'biology'", limit=2, output_fields=["text", "subject"], ) print(res)
data: ["[{'id': 4, 'distance': 0.27030569314956665, 'entity': {'text': 'Computational synthesis with AI algorithms predicts molecular properties.', 'subject': 'biology'}}, {'id': 3, 'distance': 0.16425910592079163, 'entity': {'text': 'Machine learning has been used for drug design.', 'subject': 'biology'}}]"] , extra_info: {'cost': 0}
九、查詢
query()操作用于檢索與條件匹配的所有實體,例如根據(jù)過濾表達式或特定ID進行檢索。
檢索標量字段具有特定值的所有實體:
res = client.query( collection_name="demo_collection", filter="subject == 'history'", output_fields=["text", "subject"], )
通過主鍵直接檢索實體:
res = client.query( collection_name="demo_collection", ids=[0, 2], output_fields=["vector", "text", "subject"], )
十、刪除實體
要清除數(shù)據(jù),你可以通過主鍵刪除實體,也可以刪除與特定篩選表達式匹配的所有實體。
通過主鍵刪除實體:
res = client.delete(collection_name="demo_collection", ids=[0, 2]) print(res) res = client.delete( collection_name="demo_collection", filter="subject == 'biology'", ) print(res)
[0, 2] [3, 4, 5]
十一、加載現(xiàn)有數(shù)據(jù)
由于MilvusLite將所有數(shù)據(jù)存儲在本地文件中,你可以在程序終止后使用現(xiàn)有文件創(chuàng)建一個文件,并將所有數(shù)據(jù)加載到內(nèi)存中。例如,從“milvus_demo.db”文件中恢復(fù)集合,并繼續(xù)寫入數(shù)據(jù)。
from pymilvus import MilvusClient client = MilvusClient("milvus_demo.db")
十二、刪除集合
要刪除集合中的所有數(shù)據(jù),可以使用以下命令:
client.drop_collection(collection_name="demo_collection")
十三、了解更多信息
MilvusLite非常適合開始使用本地Python程序。如果你處理大量數(shù)據(jù)或希望在生產(chǎn)環(huán)境中使用Milvus,可以學(xué)習(xí)如何在Docker和Kubernetes上部署Milvus。Milvus的所有部署模式共享相同的API,因此切換到其他部署模式時,客戶端代碼無需做太大修改。只需指定部署在任何地方的Milvus服務(wù)器的URI和Token:
client = MilvusClient(uri="http://localhost:19530", token="root:Milvus")
Milvus提供REST和gRPCAPI,以及Python、Java、Go、C#和Node.js等語言的客戶端庫。