Google 雙子星

使用 Google Gemini 嵌入模型與 Milvus,方法是選擇一個模型並使用您的 Gemini API 金鑰設定 Milvus。

選擇嵌入模型

Milvus 支援 Google Gemini 提供的嵌入模型。以下是目前可用的 Gemini 嵌入模型,以供快速參考:

模型名稱

尺寸

最大代幣

說明

gemini-embedding-001

預設:3,072 (建議:768、1,536 或 3,072)

8,192

具有彈性維度的文字嵌入模型,使用 Matryoshka Representation Learning (MRL) 訓練。

gemini-embedding-2

預設:3,072 (建議:768、1,536 或 3,072)

8,192

Google 的第一個原生多模式嵌入模型,在統一的嵌入空間中支援文字、圖片、視訊、音訊和文件。

這兩種模型都使用 Matryoshka Representation Learning (MRL) 技術進行訓練,可透過dim 參數彈性設定輸出尺寸。建議從 768 維度開始,必要時可擴充至 1,536 或 3,072 維度。如需詳細資訊,請參閱Gemini 嵌入模型

Gemini 嵌入模型還支援任務類型參數,可針對特定用例優化嵌入。Milvus 會根據操作自動設定任務類型:

  • Insert / UpsertRETRIEVAL_DOCUMENT

  • 搜尋RETRIEVAL_QUERY

您可以透過明確指定task 參數 (例如:SEMANTIC_SIMILARITY,CLASSIFICATION,CLUSTERING),來覆寫這一點。

配置憑證

Milvus 必須知道您的 Gemini API 金鑰,才能請求嵌入。Milvus 提供兩種配置憑證的方法:

  • 設定檔案 (建議使用):將 API 金鑰儲存在milvus.yaml 中,以便每次重新啟動和節點都能自動取得。

  • 環境變數:在部署時注入金鑰 - 最適合 Docker Compose。

在以下兩種方法中選擇一種--配置檔案在裸機和虛擬機器上較容易維護,而 env-var 路線則適合容器工作流程。

如果相同提供者的 API 金鑰同時出現在組態檔案和環境變數中,Milvus 會始終使用milvus.yaml 中的值,而忽略環境變數。

將您的 API 金鑰保留在milvus.yaml ;Milvus 會在啟動時讀取它們,並覆寫相同提供者的任何環境變數。

  1. 在 credential 下宣告您的金鑰:

    您可以列出一個或多個 API 金鑰 - 給每個金鑰一個您自創的標籤,並在稍後參考。

    # milvus.yaml
    credential:
      apikey_dev:            # dev environment
        apikey: <YOUR_DEV_KEY>
      apikey_prod:           # production environment
        apikey: <YOUR_PROD_KEY>    
    

    將 API 金鑰放在這裡,可以讓它們在重新啟動時保持不變,而且只要改變標籤就可以切換金鑰。

  2. 告訴 Milvus 使用哪個金鑰來呼叫 Gemini

    在同一個檔案中,將 Gemini 提供者指向您希望它使用的標籤。

    function:
      textEmbedding:
        providers:
          gemini:
            credential: apikey_dev      # ← choose any label you defined above
    

    這會將特定的金鑰綁定到 Milvus 傳送至 Gemini embeddings endpoint 的每個請求。

選項 2:環境變數

當您使用 Docker Compose 執行 Milvus,並希望不在檔案和影像中洩露秘密時,請使用此方法。

只有在milvus.yaml 中找不到提供者的金鑰時,Milvus 才會使用環境變數。

變數

需要

說明

milvus_gemini_api_key

讓每個 Milvus 容器都可以使用 Gemini 金鑰 (當 milvus.yaml 中有 Gemini 金鑰時忽略)

在您的docker-compose.yaml檔案中,設定MILVUS_GEMINI_API_KEY 環境變數。

# docker-compose.yaml (standalone service section)
standalone:
  # ... other configurations ...
  environment:
    # ... other environment variables ...
    # Set the environment variable pointing to the Gemini API key inside the container
    MILVUS_GEMINI_API_KEY: <YOUR_GEMINI_API_KEY>

environment: 區塊只會將金鑰注入 Milvus 容器,而不會碰觸到您的主機作業系統。詳情請參考使用 Docker Compose 設定 Milvus

步驟 1:建立具有文字嵌入功能的集合

定義模式欄位

若要使用嵌入功能,請建立具有特定模式的集合。此模式必須包含至少三個必要欄位:

  • 唯一識別集合中每個實體的主要欄位。

  • VARCHAR 欄位,用來儲存要嵌入的原始資料。

  • 預留向量欄位,用來儲存文字嵌入函式將為VARCHAR 欄位產生的密集向量嵌入。

以下範例定義了一個模式,其中一個標量欄位"document" 用於儲存文字資料,另一個向量欄位"dense" 用於儲存將由 Function 模組產生的嵌入資料。請記住設定向量維度 (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, Gemini's gemini-embedding-001 model outputs 3072-dimensional vectors by default,
# but can be shortened to 768 or 1536 dimensions.
schema.add_field("dense", DataType.FLOAT_VECTOR, dim=768)

定義文字嵌入函數

文字嵌入函數會自動將儲存在VARCHAR 欄位中的原始資料轉換為嵌入資料,並將其儲存在明確定義的向量欄位中。

以下範例新增了一個 Function 模組 (gemini_embedding),可將標量欄位"document" 轉換成嵌入式資料,並將產生的向量儲存於先前定義的"dense" 向量欄位中。

# Define embedding function (example: Gemini provider)
text_embedding_function = Function(
    name="gemini_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": "gemini",                       # Embedding model provider
        "model_name": "gemini-embedding-001",       # Embedding model
        # Optional parameters:
        # "credential": "apikey_dev",               # Optional: Credential label specified in milvus.yaml
        # "dim": "768",                             # Optional: Output vector dimension (default 3072)
        # "task": "RETRIEVAL_DOCUMENT",             # Optional: Task type for embedding optimization
    }
)

# Add the embedding function to your schema
schema.add_function(text_embedding_function)

支援的任務參數類型:

  • RETRIEVAL_DOCUMENT - 優化嵌入式文件索引(預設為插入/上插)。

  • RETRIEVAL_QUERY - 為查詢檢索優化嵌入式資料(預設為搜尋)。

  • SEMANTIC_SIMILARITY - 為測量文字相似性最佳化內嵌。

  • CLASSIFICATION - 優化文字分類的內嵌。

  • CLUSTERING - 優化聚類的內嵌。

如果沒有明確設定,Milvus 會在插入/上載時自動使用RETRIEVAL_DOCUMENT ,在搜尋時自動使用RETRIEVAL_QUERY

設定索引

定義包含必要欄位和內建函式的模式後,為您的資料集設定索引。為了簡化這個過程,使用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" 
)

建立資料集

現在使用已定義的模式和索引參數建立資料夾。

# Create collection named "demo"
client.create_collection(
    collection_name='demo', 
    schema=schema, 
    index_params=index_params
)

步驟 2:插入資料

設定資料集和索引後,您就可以插入原始資料了。在這個過程中,您只需要提供原始文字。我們之前定義的 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.'},
])

步驟 3:使用文字搜尋

插入資料後,使用原始查詢文字執行語意搜尋。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)

有關搜尋和查詢操作的詳細資訊,請參閱基本向量 搜尋和查詢