嵌入功能概述Compatible with Milvus 2.6.x
Milvus 的 Function 模組可讓您透過自動呼叫外部嵌入式服務供應商 (如 OpenAI、AWS Bedrock、Google Vertex AI 等),將原始文字資料轉換為向量嵌入式。有了 Function 模組,您就不需要再手動與嵌入式 API 連接-Milvus 會處理向提供者傳送請求、接收嵌入式資料,以及將其儲存在您的集合中的整個過程。對於語意搜尋,您只需要提供原始查詢資料,而不需要查詢向量。Milvus 會以您用於接收的相同模型產生查詢向量,將其與儲存的向量比較,並傳回最相關的結果。
限制
Function 模組嵌入的任何輸入欄位必須始終包含一個值;如果提供的是空值,模組將拋出一個錯誤。
Function 模組只處理集合模式中明確定義的欄位;它不會產生動態欄位的嵌入。
要嵌入的輸入欄位必須是
VARCHAR類型。Function 模組可以將輸入欄位嵌入到:
FLOAT_VECTORINT8_VECTOR
不支援轉換為
BINARY_VECTOR、FLOAT16_VECTOR或BFLOAT16_VECTOR。
支援的嵌入服務提供者
提供者 |
典型模式 |
嵌入類型 |
驗證方法 |
|---|---|---|---|
文字嵌入-3-* |
|
API 金鑰 |
|
基於部署的 |
|
API 金鑰 |
|
text-embedding-v3 |
|
API 金鑰 |
|
錨定文字-v2 |
|
AK/SK 對 |
|
text-embedding-005 |
|
GCP 服務帳號 JSON 認證 |
|
voyage-3, voyage-lite-02 |
|
API 金鑰 |
|
embed-english-v3.0 |
|
API 金鑰 |
|
BAAI/bge-large-zh-v1.5 |
|
API 金鑰 |
|
任何 TEI 服務的模型 |
|
可選 API 金鑰 |
如何運作
下圖顯示功能如何在 Milvus 中運作。
輸入文字:使用者將原始資料(例如文件)插入 Milvus。
產生嵌入:Milvus 中的 Function 模組會自動呼叫已設定的模型提供者,將原始資料轉換成向量嵌入。
儲存嵌入資料:產生的嵌入資料會儲存在 Milvus 集合中明確定義的向量欄位中。
查詢文字:使用者向 Milvus 提交文字查詢。
語意搜尋:Milvus 內部會將查詢轉換為向量嵌入,針對儲存的嵌入進行相似性搜尋,並擷取相關結果。
傳回結果:Milvus 會將最匹配的結果傳回給應用程式。
嵌入功能概述
配置憑證
在使用 Milvus 的嵌入函式之前,請先設定 Milvus 存取的嵌入服務憑證。
Milvus 讓您以兩種方式提供嵌入服務憑證:
配置檔案(
milvus.yaml):本主題中的範例展示了使用
milvus.yaml的建議設定。環境變數:
有關透過環境變數配置憑證的詳細資訊,請參閱嵌入服務供應商的說明文件 (例如OpenAI或Azure OpenAI)。
下圖顯示透過 Milvus 配置檔案 (milvus.yaml) 配置憑證,然後在 Milvus 內呼叫 Function 的流程。
憑證配置溢出
步驟 1:將憑證新增至 Milvus 配置檔案
在您的milvus.yaml 檔案中,編輯credential 區塊,為您需要存取的每個提供者加入條目:
# milvus.yaml credential store section
# This section defines all your authentication credentials for external embedding providers
# Each credential gets a unique name (e.g., aksk1, apikey1) that you'll reference elsewhere
credential:
# For AWS Bedrock or services using access/secret key pairs
# 'aksk1' is just an example name - you can choose any meaningful identifier
aksk1:
access_key_id: <YOUR_AK>
secret_access_key: <YOUR_SK>
# For OpenAI, Voyage AI, or other API key-based services
# 'apikey1' is a custom name you choose to identify this credential
apikey1:
apikey: <YOUR_API_KEY>
# For Google Vertex AI using service account credentials
# 'gcp1' is an example name for your Google Cloud credentials
gcp1:
credential_json: <BASE64_OF_JSON>
步驟 2:配置提供商設定
在相同的配置文件 (milvus.yaml) 中,編輯function 區塊,告訴 Milvus 在嵌入服務呼叫時使用哪個憑證:
function:
textEmbedding:
providers:
openai: # calls OpenAI
credential: apikey1 # Reference to the credential label
# url: # (optional) custom url
bedrock: # calls AWS Bedrock
credential: aksk1 # Reference to the credential label
region: us-east-2
vertexai: # calls Google Vertex AI
credential: gcp1 # Reference to the credential label
# url: # (optional) custom url
tei: # Built-in Tiny Embedding model
enable: true # Whether to enable TEI model service
關於如何套用 Milvus 設定的更多資訊,請參考Configure Milvus on the Fly。
使用嵌入功能
一旦在 Milvus 配置文件中配置了憑證,請按照以下步驟定義和使用嵌入函數。
步驟 1:定義模式欄位
若要使用嵌入功能,請建立具有特定模式的集合。此模式必須包含至少三個必要欄位:
唯一識別集合中每個實體的主要欄位。
儲存要嵌入的原始資料的標量欄位。
預留向量欄位,用來儲存函式將為標量欄位產生的向量嵌入。
以下範例定義了一個模式,其中一個標量欄位"document" 用來儲存文字資料,另一個向量欄位"dense" 用來儲存函式模組要產生的嵌入資料。請記得設定向量維度 (dim) 以符合您所選擇的嵌入模型輸出。
from pymilvus import MilvusClient, DataType, Function, FunctionType
# Initialize Milvus client
client = MilvusClient(
uri="http://localhost:19530",
)
# Create a new schema for the collection
schema = client.create_schema()
# Add primary field "id"
schema.add_field("id", DataType.INT64, is_primary=True, auto_id=False)
# Add scalar field "document" for storing textual data
schema.add_field("document", DataType.VARCHAR, max_length=9000)
# Add vector field "dense" for storing embeddings.
# IMPORTANT: Set dim to match the exact output dimension of the embedding model.
# For instance, OpenAI's text-embedding-3-small model outputs 1536-dimensional vectors.
# For dense vector, data type can be FLOAT_VECTOR or INT8_VECTOR
schema.add_field("dense", DataType.FLOAT_VECTOR, dim=1536)
// java
// nodejs
// go
# restful
步驟 2:將嵌入函數加入模式
Milvus 中的 Function 模組會自動將儲存在標量欄位中的原始資料轉換為嵌入資料,並將其儲存在明確定義的向量欄位中。
以下範例新增了一個 Function 模組 (openai_embedding),可將標量值欄位"document" 轉換成嵌入式資料,並將產生的向量儲存於先前定義的"dense" 向量欄位中。
# Define embedding function (example: OpenAI provider)
text_embedding_function = Function(
name="openai_embedding", # Unique identifier for this embedding function
function_type=FunctionType.TEXTEMBEDDING, # Type of embedding function
input_field_names=["document"], # Scalar field to embed
output_field_names=["dense"], # Vector field to store embeddings
params={ # Provider-specific configuration (highest priority)
"provider": "openai", # Embedding model provider
"model_name": "text-embedding-3-small", # Embedding model
# "credential": "apikey1", # Optional: Credential label
# Optional parameters:
# "dim": "1536", # Optionally shorten the vector dimension
# "user": "user123" # Optional: identifier for API tracking
}
)
# Add the embedding function to your schema
schema.add_function(text_embedding_function)
// java
// nodejs
// go
# restful
參數 |
說明 |
範例值 |
|---|---|---|
|
Milvus 內嵌入函數的唯一識別碼。 |
|
|
使用的函式類型。對於文字嵌入,請將數值設為 注意:Milvus 接受 |
|
|
包含要嵌入的原始資料的標量欄位。目前,此參數只接受一個欄位名稱。 |
|
|
向量欄位,用於儲存已產生的嵌入。目前,此參數只接受一個欄位名稱。 |
|
|
包含嵌入配置的字典。註: |
|
|
嵌入模型提供者。 |
|
|
指定要使用的嵌入模型。 |
|
|
|
|
|
輸出嵌入的維數。對於 OpenAI 的第三代模型,您可以縮短全向量以降低成本和延遲,而不會造成語意資訊的重大損失。如需詳細資訊,請參閱OpenAI 公告部落格。 注意:如果您縮短向量的維度,請確保在模式的 |
|
|
用於追蹤 API 使用情況的使用者層級識別碼。 |
|
對於具有多個需要將文字轉換為向量的標量欄位的集合,請在集合模式中加入單獨的函式,確保每個函式都有唯一的名稱和output_field_names 值。
步驟 3:配置索引
定義包含必要欄位和內建函式的模式後,為您的集合設定索引。為了簡化這個過程,請使用AUTOINDEX 作為index_type ,這個選項允許 Milvus 根據您的資料結構來選擇和設定最適合的索引類型。
# Prepare index parameters
index_params = client.prepare_index_params()
# Add AUTOINDEX to automatically select optimal indexing method
index_params.add_index(
field_name="dense",
index_type="AUTOINDEX",
metric_type="COSINE"
)
// java
// nodejs
// go
# restful
步驟 4:建立集合
現在使用已定義的模式和索引參數建立集合。
# Create collection named "demo"
client.create_collection(
collection_name='demo',
schema=schema,
index_params=index_params
)
// java
// nodejs
// go
# restful
步驟 5:插入資料
設定好集合和索引後,您就可以插入原始資料了。在這個過程中,您只需要提供原始文字。我們之前定義的 Function 模組會自動為每個文字項目產生相對應的稀疏向量。
# Insert sample documents
client.insert('demo', [
{'id': 1, 'document': 'Milvus simplifies semantic search through embeddings.'},
{'id': 2, 'document': 'Vector embeddings convert text into searchable numeric data.'},
{'id': 3, 'document': 'Semantic search helps users find relevant information quickly.'},
])
// java
// nodejs
// go
# restful
步驟 6:執行向量搜尋
插入資料後,使用原始查詢文字執行語意搜尋。Milvus 會自動將您的查詢轉換成嵌入向量,根據相似度擷取相關文件,並傳回最匹配的結果。
# Perform semantic search
results = client.search(
collection_name='demo',
data=['How does Milvus handle semantic search?'], # Use text query rather than query vector
anns_field='dense', # Use the vector field that stores embeddings
limit=1,
output_fields=['document'],
)
print(results)
# Example output:
# data: ["[{'id': 1, 'distance': 0.8821347951889038, 'entity': {'document': 'Milvus simplifies semantic search through embeddings.'}}]"]
// java
// nodejs
// go
# restful
常見問題
在 milvus.yaml 與環境變數中設定憑證有何不同?
兩種方法都可以使用,但建議使用milvus.yaml ,因為它提供集中化的憑證管理,並在所有提供者之間提供一致的憑證命名。使用環境變數時,變數名稱因嵌入服務供應商而異,因此請參閱各供應商的專屬頁面,以瞭解所需的特定環境變數名稱 (例如,OpenAI或Azure OpenAI)。
如果我沒有在函式定義中指定憑證參數,會發生什麼情況?
Milvus 遵循此憑證解析順序:
- 首先,它會尋找
milvus.yaml檔案中為該提供者設定的預設憑證。 - 如果在 milvus.yaml 中不存在默认凭据,它将返回到环境变量(如果已配置)。
- 如果
milvus.yaml認證或環境變數都沒有設定,Milvus 會產生錯誤。
我如何驗證嵌入是否正確產生?
您可以透過以下方式檢查
- 在插入後查詢您的集合,看看向量欄位是否包含資料
- 檢查向量領域的長度是否符合您的預期尺寸
- 執行簡單的相似性搜尋,以驗證嵌入是否產生有意義的結果
執行相似性搜尋時,我可以使用查詢向量而不是原始文字嗎?
可以,您可以使用預先計算好的查詢向量來代替原始文字進行相似性搜尋。雖然 Function 模組會自動將原始文字查詢轉換成嵌入式資料,但您也可以在搜尋作業中直接提供向量資料給data 參數。注意:您所提供的查詢向量的尺寸大小,必須與您的 Function 模組所產生的向量嵌入的尺寸大小一致。
範例:
# Using raw text (Function module converts automatically)
results = client.search(
collection_name='demo',
data=['How does Milvus handle semantic search?'],
anns_field='dense',
limit=1
)
# Using pre-computed query vector (must match stored vector dimensions)
query_vector = [0.1, 0.2, 0.3, ...] # Must be same dimension as stored embeddings
results = client.search(
collection_name='demo',
data=[query_vector],
anns_field='dense',
limit=1
)
// java
// nodejs
// go
# restful