Embedding

Updated at:
Copy as MD

The AI_EMBEDDING function converts text, images, and videos into dense vectors for semantic search, RAG, and clustering. Call the function directly through the REST API, or configure FunctionType.TEXTEMBEDDING in a collection schema to enable automatic embedding on write. Use params.dim to specify output dimensions, and set is_multimodal to true for image or video inputs.

Prerequisites

  • A Milvus instance with an accessible REST endpoint.

  • Valid authentication credentials for the instance.

  • For Collection Functions: credentials and service endpoints configured by the administrator in milvus.yaml.

  • For multi-modal models (image or video): media URLs accessible to the model.

Command format

You can invoke the AI_EMBEDDING function through the REST API or define it as a Collection Function in the Python SDK.

REST API

REST API

POST /v2/vectordb/ai/embedding
Content-Type: application/json

{
  "model_name": "<model name>",
  "texts": ["<text or media reference>"],
  "params": {"dim": 1024}
}

Python

Python

schema = MilvusClient.create_schema(auto_id=True, enable_dynamic_field=False)
schema.add_field("id", DataType.INT64, is_primary=True)
schema.add_field("content", DataType.VARCHAR, max_length=4096)
schema.add_field("embedding", DataType.FLOAT_VECTOR, dim=1024)
schema.add_function(
    Function(
        name="embed_content",
        function_type=FunctionType.TEXTEMBEDDING,
        input_field_names=["content"],
        output_field_names=["embedding"],
        params={
            "provider": "aliyun_milvus",
            "model_name": "<model name>",
            "dim": 1024,
        },
    )
)

Parameters

ParameterDescription
model_nameRequired. Model name. For text, use text-embedding-v4 or text-embedding-v3. For images or videos, use qwen3-vl-embedding or tongyi-embedding-vision-plus.
textsRequired for REST. A non-empty array of strings. Multi-modal models accept text, image Base64, image URLs, or video URLs.
dimOptional. Output vector dimensions. 0 uses the model's default dimensions. In collection scenarios, this value must match the dimensions of the output vector field.
is_multimodalOptional. Set to true when embedding images or videos. Defaults to false for text models.
max_client_batch_sizeOptional. Maximum number of inputs sent to the model per request. Must be greater than 0. Align this value with the batch size specified for your model in the official Model Studio embedding documentation.
max_concurrencyOptional. Concurrency level, in the range 1 to 64. Default value: 1.
providerRequired only for Collection Functions. Must be set to aliyun_milvus. Credentials and service endpoints are configured by the administrator in milvus.yaml. Do not include them in the request body.
Note

For optimal write throughput, check the batch size specified for your model in the official Model Studio embedding documentation. The array size passed to each insert call should match this batch size, except for the final batch if it is smaller. Batch sizes vary by model.

Return value

On success, data.output.embeddings returns a list of vectors corresponding to the inputs. Each item's text_index is the index of the original input, and embedding is the vector. data.usage records the model usage for this request.

{
  "code": 0,
  "data": {
    "output": {
      "embeddings": [
        {"text_index": 0, "embedding": [0.012, -0.084, "..."]}
      ]
    },
    "usage": {"total_tokens": 22}
  }
}

Example 1: Ingest knowledge base articles and perform semantic search (text)

An enterprise knowledge base stores article text alongside its vector to enable retrieval based on user queries. The input consists of two article excerpts. The key parameters are model_name=text-embedding-v4 and dim=1024.

REST API

REST API

#!/usr/bin/env bash
set -euo pipefail

MILVUS_REST_BASE_URL="http://c-xxxx.milvus.aliyuncs.com:19530"
MILVUS_AUTH_TOKEN="<yourUsername>:<yourPassword>"

post_json() {
  local path="$1"
  local body="$2"
  curl -X POST "$MILVUS_REST_BASE_URL$path" \
    -H "Authorization: Bearer $MILVUS_AUTH_TOKEN" \
    -H "Content-Type: application/json" \
    -d "$body"
}

BODY=$(cat <<'JSON'
{
  "model_name": "text-embedding-v4",
  "texts": [
    "Milvus Serverless is ideal for building enterprise knowledge bases.",
    "AI Function can automatically invoke models during data insertion."
  ],
  "params": {
    "dim": 1024,
    "max_client_batch_size": 2,
    "max_concurrency": 1
  }
}
JSON
)

post_json "/v2/vectordb/ai/embedding" "$BODY"

The response returns two embeddings items with text_index values of 0 and 1 respectively. On the application side, write each item's vector together with the corresponding article into the collection. During search, use the same model and dimensions to generate query vectors.

Python

Python

from __future__ import annotations
from typing import Any

from pymilvus import DataType, Function, FunctionType, MilvusClient

MILVUS_URI = "http://c-xxxx.milvus.aliyuncs.com:19530"
MILVUS_TOKEN = "<yourUsername>:<yourPassword>"

def add_id(schema: Any) -> None:
    schema.add_field("id", DataType.INT64, is_primary=True)

client = MilvusClient(uri=MILVUS_URI, token=MILVUS_TOKEN)

collection_name = "simple_ai_embedding"
if client.has_collection(collection_name):
    client.drop_collection(collection_name)

schema = MilvusClient.create_schema(auto_id=True, enable_dynamic_field=False)
add_id(schema)
schema.add_field("content", DataType.VARCHAR, max_length=4096)
schema.add_field("embedding", DataType.FLOAT_VECTOR, dim=1024)
schema.add_function(
    Function(
        name="embed_content",
        function_type=FunctionType.TEXTEMBEDDING,
        input_field_names=["content"],
        output_field_names=["embedding"],
        params={
            "provider": "aliyun_milvus",
            "model_name": "text-embedding-v4",
            "dim": 1024,
            # The batch size for text-embedding-v4 in the official Bailian documentation is 10.
            "max_client_batch_size": 10,
            "max_concurrency": 1,
        },
    )
)

index_params = client.prepare_index_params()
index_params.add_index(
    field_name="embedding",
    index_type="HNSW",
    metric_type="COSINE",
    params={"M": 16, "efConstruction": 200},
)
client.create_collection(
    collection_name=collection_name,
    schema=schema,
    index_params=index_params,
)

client.insert(
    collection_name,
    [
        {"content": "Milvus Serverless is ideal for building enterprise knowledge bases."},
        {"content": "AI Function can automatically invoke models during data insertion."},
        {"content": "Relational databases are suitable for handling transactional data."},
        {"content": "Vector search can retrieve content based on semantic similarity."},
        {"content": "RAG retrieves external knowledge to assist models in generating answers."},
        {"content": "Semantic search can identify similar meanings across different expressions."},
        {"content": "Documents can be split into chunks and individually embedded."},
        {"content": "Search results can be further optimized using a reranking model."},
        {"content": "Vector indexes can improve query efficiency for large-scale datasets."},
        {"content": "Knowledge bases should regularly update their ingested business content."},
    ],
)
client.flush(collection_name)
client.load_collection(collection_name)

result = client.search(
    collection_name=collection_name,
    data=["How do I build a knowledge base for Q&A?"],
    anns_field="embedding",
    limit=2,
    output_fields=["content"],
)
for hit in result[0]:
    print(f"score={hit['distance']:.4f} content={hit['entity']['content']}")

Example 2: Embed product images (image)

A product image library converts main product images into vectors to support multi-modal queries such as "search for a blue coat." The input is an image URL accessible to the model. The key parameters are model_name=qwen3-vl-embedding, is_multimodal=true, and dim=2560.

REST API

REST API

#!/usr/bin/env bash
set -euo pipefail

MILVUS_REST_BASE_URL="http://c-xxxx.milvus.aliyuncs.com:19530"
MILVUS_AUTH_TOKEN="<yourUsername>:<yourPassword>"

post_json() {
  local path="$1"
  local body="$2"
  curl -X POST "$MILVUS_REST_BASE_URL$path" \
    -H "Authorization: Bearer $MILVUS_AUTH_TOKEN" \
    -H "Content-Type: application/json" \
    -d "$body"
}

MODEL_NAME="qwen3-vl-embedding"
IMAGE_URL="${IMAGE_URL:-https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260415/hynnff/wan-video-edit-clothes.webp}"

BODY=$(cat <<JSON
{
  "model_name": "$MODEL_NAME",
  "texts": ["$IMAGE_URL"],
  "params": {"is_multimodal": true}
}
JSON
)

RESPONSE_BODY="$(post_json "/v2/vectordb/ai/embedding" "$BODY")"
if command -v jq >/dev/null 2>&1; then
  echo "$RESPONSE_BODY" | jq .
  [ "$(echo "$RESPONSE_BODY" | jq -r '.code // -1')" = "0" ] || exit 1
else
  echo "$RESPONSE_BODY"
fi

Python

Python

from __future__ import annotations
import os
from typing import Any

from pymilvus import DataType, Function, FunctionType, MilvusClient

MILVUS_URI = "http://c-xxxx.milvus.aliyuncs.com:19530"
MILVUS_TOKEN = "<yourUsername>:<yourPassword>"

def add_id(schema: Any) -> None:
    schema.add_field("id", DataType.INT64, is_primary=True)

MODEL_NAME = "qwen3-vl-embedding"
VECTOR_DIM = int(os.getenv("AIFUNC_EMBEDDING_DIM", "2560"))
IMAGE_URL = os.getenv("IMAGE_URL", "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260415/hynnff/wan-video-edit-clothes.webp")
client = MilvusClient(uri=MILVUS_URI, token=MILVUS_TOKEN)

collection_name = "simple_ai_embedding_image"
if client.has_collection(collection_name):
    client.drop_collection(collection_name)

schema = MilvusClient.create_schema(auto_id=True, enable_dynamic_field=False)
add_id(schema)
schema.add_field("image_url", DataType.VARCHAR, max_length=4096)
schema.add_field("embedding", DataType.FLOAT_VECTOR, dim=VECTOR_DIM)
schema.add_function(
    Function(
        name="embed_media",
        function_type=FunctionType.TEXTEMBEDDING,
        input_field_names=["image_url"],
        output_field_names=["embedding"],
        params={"provider": "aliyun_milvus", "model_name": MODEL_NAME, "dim": VECTOR_DIM, "is_multimodal": "true"},
    )
)
index_params = client.prepare_index_params()
index_params.add_index(field_name="embedding", index_type="AUTOINDEX", metric_type="COSINE")
client.create_collection(collection_name=collection_name, schema=schema, index_params=index_params)
client.insert(collection_name, [{"image_url": IMAGE_URL}])
client.flush(collection_name)
client.load_collection(collection_name)
for hit in client.search(collection_name=collection_name, data=[IMAGE_URL], anns_field="embedding", limit=1, output_fields=["image_url"])[0]:
    print(f"score={hit['distance']:.4f} image_url={hit['entity']['image_url']}")

The response returns a 2560-dimensional image vector with text_index=0. After writing this vector to the product vector field, you can use the same multi-modal model to convert text or image queries into vectors and perform search.

Example 3: Embed video materials (video)

A video content library generates vectors for short videos to enable semantic search for content operations teams. The input is a video URL accessible to the model. The model is the same as in the image example, and the resource type is identified automatically from the URL.

REST API

REST API

#!/usr/bin/env bash
set -euo pipefail

MILVUS_REST_BASE_URL="http://c-xxxx.milvus.aliyuncs.com:19530"
MILVUS_AUTH_TOKEN="<yourUsername>:<yourPassword>"

post_json() {
  local path="$1"
  local body="$2"
  curl -X POST "$MILVUS_REST_BASE_URL$path" \
    -H "Authorization: Bearer $MILVUS_AUTH_TOKEN" \
    -H "Content-Type: application/json" \
    -d "$body"
}

MODEL_NAME="qwen3-vl-embedding"
VIDEO_URL="${VIDEO_URL:-https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260409/dozxak/Wan_Video_Edit_33_1.mp4}"

BODY=$(cat <<JSON
{
  "model_name": "$MODEL_NAME",
  "texts": ["$VIDEO_URL"],
  "params": {"is_multimodal": true}
}
JSON
)

RESPONSE_BODY="$(post_json "/v2/vectordb/ai/embedding" "$BODY")"
if command -v jq >/dev/null 2>&1; then
  echo "$RESPONSE_BODY" | jq .
  [ "$(echo "$RESPONSE_BODY" | jq -r '.code // -1')" = "0" ] || exit 1
else
  echo "$RESPONSE_BODY"
fi

Python

Python

from __future__ import annotations
import os
from typing import Any

from pymilvus import DataType, Function, FunctionType, MilvusClient

MILVUS_URI = "http://c-xxxx.milvus.aliyuncs.com:19530"
MILVUS_TOKEN = "<yourUsername>:<yourPassword>"

def add_id(schema: Any) -> None:
    schema.add_field("id", DataType.INT64, is_primary=True)

MODEL_NAME = "qwen3-vl-embedding"
VECTOR_DIM = int(os.getenv("AIFUNC_EMBEDDING_DIM", "2560"))
VIDEO_URL = os.getenv("VIDEO_URL", "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260409/dozxak/Wan_Video_Edit_33_1.mp4")
client = MilvusClient(uri=MILVUS_URI, token=MILVUS_TOKEN)

collection_name = "simple_ai_embedding_video"
if client.has_collection(collection_name):
    client.drop_collection(collection_name)

schema = MilvusClient.create_schema(auto_id=True, enable_dynamic_field=False)
add_id(schema)
schema.add_field("video_url", DataType.VARCHAR, max_length=4096)
schema.add_field("embedding", DataType.FLOAT_VECTOR, dim=VECTOR_DIM)
schema.add_function(
    Function(
        name="embed_media",
        function_type=FunctionType.TEXTEMBEDDING,
        input_field_names=["video_url"],
        output_field_names=["embedding"],
        params={"provider": "aliyun_milvus", "model_name": MODEL_NAME, "dim": VECTOR_DIM, "is_multimodal": "true"},
    )
)
index_params = client.prepare_index_params()
index_params.add_index(field_name="embedding", index_type="AUTOINDEX", metric_type="COSINE")
client.create_collection(collection_name=collection_name, schema=schema, index_params=index_params)
client.insert(collection_name, [{"video_url": VIDEO_URL}])
client.flush(collection_name)
client.load_collection(collection_name)
for hit in client.search(collection_name=collection_name, data=[VIDEO_URL], anns_field="embedding", limit=1, output_fields=["video_url"])[0]:
    print(f"score={hit['distance']:.4f} video_url={hit['entity']['video_url']}")

The response returns the embedding vector for the video. By storing the vector together with video_url, you can integrate video search into content operations or media recommendation workflows.