🚀 免費嘗試 Zilliz Cloud,完全托管的 Milvus,體驗速度提升 10 倍!立即嘗試

milvus-logo
LFAI
主頁
  • 開始使用

Milvus Lite 快速入門

Open In Colab GitHub Repository

向量是神經網路模型的輸出資料格式,可以有效地編碼資訊,並在知識庫、語意搜尋、Retrieval Augmented Generation (RAG) 等人工智慧應用中扮演關鍵的角色。

Milvus 是一個開放原始碼的向量資料庫,適合各種規模的 AI 應用程式,從在 Jupyter notebook 中執行示範聊天機器人,到建立服務數十億使用者的網路規模搜尋。在本指南中,我們將教您如何在幾分鐘內在本機設定 Milvus,並使用 Python 用戶端函式庫來產生、儲存和搜尋向量。

安裝 Milvus

在本指南中,我們使用 Milvus Lite,它是pymilvus 中包含的一個 python 函式庫,可以嵌入到客戶端應用程式中。Milvus 也支援部署在DockerKubernetes上,以應用於生產使用個案。

在開始之前,請確認您的本機環境中有 Python 3.8+ 可用。安裝pymilvus ,其中包含 python 客戶端函式庫和 Milvus Lite:

$ pip install -U pymilvus

如果您正在使用 Google Colab,為了啟用剛安裝的相依性,您可能需要重新啟動運行時間。(按一下螢幕上方的「Runtime」功能表,從下拉式功能表中選擇「Restart session」)。

設定向量資料庫

要建立一個本機的 Milvus 向量資料庫,只要實體化一個MilvusClient ,指定一個檔案名稱來儲存所有資料,例如 "milvus_demo.db"。

from pymilvus import MilvusClient

client = MilvusClient("milvus_demo.db")

建立一個集合

在 Milvus 中,我們需要一個集合來儲存向量及其相關的元資料。您可以將它想像成傳統 SQL 資料庫中的資料表。建立集合時,您可以定義 schema 和索引參數,以設定向量規格,例如維度、索引類型和遠端指標。此外,還有一些複雜的概念,可以優化索引的向量搜尋效能。目前,讓我們先專注於基本概念,並盡可能使用預設值。至少,您只需要設定集合名稱和集合向量欄位的維度。

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
)

在上面的設定中

  • 主鍵和向量欄位使用預設名稱("id 「和 」vector")。
  • 度量類型 (向量距離定義) 設定為預設值(COSINE)。
  • 主鍵欄位接受整數,並且不會自動遞增(即不使用自動識別功能)。 或者,您可以按照此指令正式定義集合的模式。

準備資料

在本指南中,我們使用向量來對文字執行語意搜尋。我們需要下載嵌入模型來為文字產生向量。使用pymilvus[model] 函式庫中的實用函式即可輕鬆完成這項工作。

使用向量表示文字

首先,安裝模型函式庫。這個套件包含基本的 ML 工具,例如 PyTorch。如果您的本地環境從未安裝過 PyTorch,下載套件可能需要一些時間。

$ pip install "pymilvus[model]"

使用預設模型產生向量內嵌。Milvus 希望資料是以字典清單的方式插入,每個字典代表一個資料記錄,稱為一個實體。

from pymilvus import model

# If connection to https://huggingface.co/ failed, uncomment the following path
# import os
# os.environ['HF_ENDPOINT'] = 'https://hf-mirror.com'

# This will download a small embedding model "paraphrase-albert-small-v2" (~50MB).
embedding_fn = model.DefaultEmbeddingFunction()

# 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.",
]

vectors = embedding_fn.encode_documents(docs)
# The output vector has 768 dimensions, matching the collection that we just created.
print("Dim:", embedding_fn.dim, vectors[0].shape)  # Dim: 768 (768,)

# Each entity has id, vector representation, raw text, and a subject label that we use
# to demo metadata filtering later.
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

[另一種方法] 使用隨機向量的偽造表示法

如果您因為網路問題而無法下載模型,您可以使用隨機向量來表示文字,並繼續完成範例。只要注意搜尋結果不會反映語意相似性,因為向量是假的。

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

插入資料

讓我們將資料插入到資料集中:

res = client.insert(collection_name="demo_collection", data=data)

print(res)
{'insert_count': 3, 'ids': [0, 1, 2], 'cost': 0}

現在我們可以用向量來表示搜尋查詢的文字,並在 Milvus 上進行向量相似性搜尋,從而進行語意搜尋。

Milvus 可同時接受一個或多個向量搜尋請求。query_vectors 變數的值是一個向量清單,其中每個向量是一個浮點數的陣列。

query_vectors = embedding_fn.encode_queries(["Who is Alan Turing?"])
# If you don't have the embedding function you can use a fake vector to finish the demo:
# query_vectors = [ [ random.uniform(-1, 1) for _ in range(768) ] ]

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}

輸出是一個結果清單,每個結果對應到一個向量搜尋查詢。每個查詢包含一個結果清單,其中每個結果包含實體主鍵、到查詢向量的距離,以及指定output_fields 的實體詳細資料。

使用元資料篩選的向量搜尋

您也可以在考慮元資料值(在 Milvus 中稱為 「標量 」欄位,因為標量指的是非向量資料)的同時進行向量搜尋。這是透過指定特定條件的篩選表達式來完成的。讓我們在下面的範例中看看如何使用subject 欄位進行搜尋和篩選。

# Insert more docs in another subject.
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)

# This will exclude any text in "history" subject despite close to the query vector.
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}

預設情況下,標量欄位不會被索引。如果您需要在大型資料集中執行 metadata 過濾搜尋,您可以考慮使用固定模式,同時開啟索引以改善搜尋效能。

除了向量搜尋外,您也可以執行其他類型的搜尋:

查詢

查詢()是擷取所有符合條件的實體的操作,例如篩選表達式或符合某些 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"],
)

刪除實體

如果您想清除資料,您可以刪除指定主索引鍵的實體,或刪除符合特定篩選表達式的所有實體。

# Delete entities by primary key
res = client.delete(collection_name="demo_collection", ids=[0, 2])

print(res)

# Delete entities by a filter expression
res = client.delete(
    collection_name="demo_collection",
    filter="subject == 'biology'",
)

print(res)
[0, 2]
[3, 4, 5]

載入現有資料

由於 Milvus Lite 的所有資料都儲存在本機檔案中,即使在程式終止後,您也可以透過建立MilvusClient 與現有檔案,將所有資料載入記憶體中。例如,這將恢復 "milvus_demo.db" 檔案中的集合,並繼續將資料寫入其中。

from pymilvus import MilvusClient

client = MilvusClient("milvus_demo.db")

刪除集合

如果您想刪除一個資料集中的所有資料,您可以使用

# Drop collection
client.drop_collection(collection_name="demo_collection")

瞭解更多

Milvus Lite 非常適合使用本機 python 程式上手。如果您有大規模的資料,或想在生產中使用 Milvus,您可以學習在DockerKubernetes 上部署 Milvus。Milvus 的所有部署模式都共用相同的 API,因此如果轉換到其他部署模式,您的用戶端程式碼不需要做太大的變更。只要指定部署在任何地方的 Milvus 伺服器的URI 和 Token即可:

client = MilvusClient(uri="http://localhost:19530", token="root:Milvus")

Milvus 提供 REST 和 gRPC API,以及PythonJavaGo、C# 和Node.js 等語言的用戶端程式庫。

免費嘗試托管的 Milvus

Zilliz Cloud 無縫接入,由 Milvus 提供動力,速度提升 10 倍。

開始使用
反饋

這個頁面有幫助嗎?