Rerank
AI_RERANK performs relevance reranking (fine-grained ranking) on the results recalled by vector or hybrid retrieval, improving the accuracy of RAG question answering and multimodal search. The system automatically matches a model based on the candidate type: qwen3-rerank for text, and qwen3-vl-rerank for images and videos.
Command format
REST interface
POST /v2/vectordb/ai/rerank
Content-Type: application/json
{
"model_name": "qwen3-rerank",
"query": "<query text>",
"documents": ["<candidate content>"],
"params": {"timeout_sec": 10}
}
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": "text-embedding-v4",
"dim": 1024,
},
)
)
reranker = Function(
name="rerank_content",
function_type=FunctionType.RERANK,
input_field_names=["content"],
params={
"reranker": "model",
"provider": "aliyun_milvus",
"model_name": "qwen3-rerank",
"queries": ["<query text>"],
"timeout_sec": 10,
},
)
In Collection Search scenarios, use FunctionType.RERANK, and set reranker="model", provider="aliyun_milvus", model_name, queries, and the candidate content field. Use qwen3-rerank for text candidates, and qwen3-vl-rerank for image or video candidates.
Multimodal input combinations
qwen3-vl-rerank supports not only querying images or videos by text, but also passing an image URL directly as the query to implement image-based image search or image-based video search. The supported input combinations are as follows.
|
Query |
Candidate content |
Model |
Typical scenario |
|
Text |
Text |
|
RAG document rerank |
|
Text |
Image URL |
|
Text-based image search |
|
Image URL |
Image URL |
|
Image-based image search, similar product recommendation |
|
Text |
Video URL |
|
Text-based video search |
|
Image URL |
Video URL |
|
Image-based video search, material matching |
In the REST interface, both text queries and media URLs are passed in through the query string. In Collection Search, they are passed in through the queries array. Media candidates must be stored as accessible URL strings in documents or in the candidate field of the collection.
Parameters
|
Parameter |
Description |
|
|
Required for REST, and also required for the model rerank Function. Use |
|
|
Required for REST. It can be a non-empty query text, or an accessible image URL for multimodal reranking. |
|
|
Required for REST. At least one candidate content item. The |
|
|
Required only for the model rerank Function. Fixed to |
|
|
Used only by the Function. Set it to |
|
|
Required only for the Search Function. A query array whose elements can be query texts or image URLs. For a single-query search, pass one element. |
|
|
Optional. The maximum number of candidates sent to the model at a time. The default value is |
|
|
Optional. The concurrency, in the range of |
|
|
Optional. The timeout in seconds for a single model call, in the range of |
|
|
Optional and available only for the Search Function. When a model exception occurs, you can select |
|
|
Optional. Set it to |
|
|
Optional. A ranking instruction that clarifies what the model should focus on when ranking. For multimodal reranking, we recommend that you use an English instruction. For example, image reranking can emphasize subject consistency, appearance, composition, and fine-grained visual features, whereas video reranking can emphasize the subject, action, scene, and appearance. |
Response parameters
When a REST call succeeds, data.output.results returns the index and relevance_score of each candidate. The results correspond to the input subscripts, and your application should sort them in descending order of relevance_score. The scores have no fixed threshold, so do not rely on the specific values shown in the examples. The response also contains the usage (such as total_tokens) and request_id fields.
{"code":0,"data":{"output":{"results":[{"index":0,"relevance_score":0.97}]}}}
Example 1: Rerank candidate documents for RAG question answering (text)
The knowledge base has recalled three candidate documents, and the user asks about "typical application scenarios of vector databases". After rescoring with RERANK, the application passes the highest-scoring document to the large model to generate an answer. The key parameters are query, documents, and timeout_sec.
REST interface
#!/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-rerank"
BODY=$(cat <<JSON
{
"model_name": "$MODEL_NAME",
"query": "Typical use cases of vector databases",
"documents": [
"Milvus is an open-source vector database for RAG, recommendation, and image search.",
"MySQL is a relational database for transactional applications.",
"Vector retrieval can be combined with inverted indexes to improve recall."
],
"params": {"max_concurrency": 2, "timeout_sec": 10}
}
JSON
)
RESPONSE_BODY="$(post_json "/v2/vectordb/ai/rerank" "$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
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-rerank"
EMBEDDING_MODEL = os.getenv("AIFUNC_RERANK_EMBEDDING_MODEL", "text-embedding-v4")
client = MilvusClient(uri=MILVUS_URI, token=MILVUS_TOKEN)
collection_name = "simple_ai_rerank_text"
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": EMBEDDING_MODEL, "dim": 1024}))
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, [{"content": "Milvus is an open-source vector database for RAG and recommendation."}, {"content": "MySQL is a relational database for transactional applications."}])
client.flush(collection_name)
client.load_collection(collection_name)
QUERY = "Typical use cases of vector databases"
reranker = Function(name="rerank_content", function_type=FunctionType.RERANK, input_field_names=["content"], params={"reranker": "model", "provider": "aliyun_milvus", "model_name": MODEL_NAME, "queries": [QUERY], "max_concurrency": 2, "timeout_sec": 10})
for hit in client.search(collection_name=collection_name, data=[QUERY], anns_field="embedding", limit=2, output_fields=["content"], ranker=reranker)[0]:
print(f"score={hit['distance']:.4f} content={hit['entity']['content']}")
Documents 0 and 2 are usually more relevant than the MySQL document. Python prints the candidates in descending order of the actual relevance_score, and the application can take the top two as the RAG context.
Example 2: Multimodal rerank of product images (text-based and image-based image search)
Vector retrieval first recalls candidate product images, and then qwen3-vl-rerank performs fine-grained ranking. This example runs two types of queries in sequence against the same batch of candidate images: a text query, and a reference image URL passed directly as the query to implement image-based image search. We recommend that you first truncate the vector retrieval results to at most 40 candidate images and then pass them to the model for reranking. Use an English instruction for instruct that explicitly requires prioritizing comparison of subject identity, appearance, composition, and fine-grained visual features.
REST interface
#!/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-rerank"
QUERY_TEXT="a fashion product matching the query"
QUERY_IMAGE_URL="https://img.alicdn.com/imgextra/i3/O1CN01rdstgY1uiZWt8gqSL_!!6000000006071-0-tps-1970-356.jpg"
CANDIDATE_IMAGE_URL_1="$QUERY_IMAGE_URL"
CANDIDATE_IMAGE_URL_2="https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260415/hynnff/wan-video-edit-clothes.webp"
CANDIDATE_IMAGE_URL_3="https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"
INSTRUCT="Rank the candidate images by relevance to the query, prioritizing subject identity, appearance, composition, and fine-grained visual details."
run_rerank() {
local label="$1"
local query="$2"
local body
body=$(cat <<JSON
{
"model_name": "$MODEL_NAME",
"query": "$query",
"documents": [
"$CANDIDATE_IMAGE_URL_1",
"$CANDIDATE_IMAGE_URL_2",
"$CANDIDATE_IMAGE_URL_3"
],
"params": {
"is_multimodal": true,
"instruct": "$INSTRUCT",
"max_client_batch_size": 40,
"timeout_sec": 10
}
}
JSON
)
echo "=== $label ==="
post_json "/v2/vectordb/ai/rerank" "$body"
}
run_rerank "text query" "$QUERY_TEXT"
run_rerank "image query" "$QUERY_IMAGE_URL"
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-rerank"
EMBEDDING_MODEL = os.getenv("AIFUNC_RERANK_EMBEDDING_MODEL", "qwen3-vl-embedding")
VECTOR_DIM = int(os.getenv("AIFUNC_RERANK_EMBEDDING_DIM", "2560"))
QUERY_TEXT = "a fashion product matching the query"
QUERY_IMAGE_URL = "https://img.alicdn.com/imgextra/i3/O1CN01rdstgY1uiZWt8gqSL_!!6000000006071-0-tps-1970-356.jpg"
CANDIDATE_IMAGE_URLS = [
QUERY_IMAGE_URL,
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260415/hynnff/wan-video-edit-clothes.webp",
"https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg",
]
INSTRUCT = (
"Rank the candidate images by relevance to the query, prioritizing "
"subject identity, appearance, composition, and fine-grained visual details."
)
client = MilvusClient(uri=MILVUS_URI, token=MILVUS_TOKEN)
collection_name = "simple_ai_rerank_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("content", DataType.VARCHAR, max_length=4096)
schema.add_field("embedding", DataType.FLOAT_VECTOR, dim=VECTOR_DIM)
schema.add_function(Function(name="embed_image", function_type=FunctionType.TEXTEMBEDDING, input_field_names=["content"], output_field_names=["embedding"], params={"provider": "aliyun_milvus", "model_name": EMBEDDING_MODEL, "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, [{"content": url} for url in CANDIDATE_IMAGE_URLS[:40]])
client.flush(collection_name)
client.load_collection(collection_name)
for query_label, query in (("text", QUERY_TEXT), ("image", QUERY_IMAGE_URL)):
reranker = Function(name=f"rerank_image_{query_label}_query", function_type=FunctionType.RERANK, input_field_names=["content"], params={"reranker": "model", "provider": "aliyun_milvus", "model_name": MODEL_NAME, "queries": [query], "is_multimodal": "true", "instruct": INSTRUCT, "max_client_batch_size": 40, "timeout_sec": 10})
for hit in client.search(collection_name=collection_name, data=[query], anns_field="embedding", limit=len(CANDIDATE_IMAGE_URLS[:40]), output_fields=["content"], ranker=reranker)[0]:
print(f"{query_label} score={hit['distance']:.4f} content={hit['entity']['content']}")
The expected results are as follows:
-
The text query sorts candidates by the semantic and visual relevance between the text description and the candidate images.
-
The image query performs an image-based image search, and the image identical to the query usually ranks first.
-
The
indexreturned by REST corresponds to the subscript of the originaldocumentsarray. Do not change the order of the original array before mapping back to the candidate content. -
The
hit['distance']returned by Collection Search is the relevance score after reranking, and the results are already sorted by score.
Example 3: Multimodal rerank of video materials (text-based and image-based video search)
Video candidates also use qwen3-vl-rerank. In addition to a text query, you can pass a reference image URL as the query to let the model find the candidate videos whose subject, clothing, action, or scene matches best.
REST interface
#!/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-rerank"
QUERY_TEXT="person wearing a striped sweater"
QUERY_IMAGE_URL="https://img.alicdn.com/imgextra/i3/O1CN01rdstgY1uiZWt8gqSL_!!6000000006071-0-tps-1970-356.jpg"
VIDEO_URL="https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260409/dozxak/Wan_Video_Edit_33_1.mp4"
INSTRUCT="Rank the candidate videos by relevance to the query, prioritizing matching subjects, actions, scenes, appearance, and fine-grained visual details."
run_rerank() {
local label="$1"
local query="$2"
local body
body=$(cat <<JSON
{
"model_name": "$MODEL_NAME",
"query": "$query",
"documents": ["$VIDEO_URL"],
"params": {
"is_multimodal": true,
"instruct": "$INSTRUCT",
"timeout_sec": 10
}
}
JSON
)
echo "=== $label ==="
post_json "/v2/vectordb/ai/rerank" "$body"
}
run_rerank "text query" "$QUERY_TEXT"
run_rerank "image query" "$QUERY_IMAGE_URL"
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-rerank"
EMBEDDING_MODEL = os.getenv("AIFUNC_RERANK_EMBEDDING_MODEL", "qwen3-vl-embedding")
VECTOR_DIM = int(os.getenv("AIFUNC_RERANK_EMBEDDING_DIM", "2560"))
QUERY_TEXT = "person wearing a striped sweater"
QUERY_IMAGE_URL = "https://img.alicdn.com/imgextra/i3/O1CN01rdstgY1uiZWt8gqSL_!!6000000006071-0-tps-1970-356.jpg"
VIDEO_URL = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260409/dozxak/Wan_Video_Edit_33_1.mp4"
INSTRUCT = (
"Rank the candidate videos by relevance to the query, prioritizing matching "
"subjects, actions, scenes, appearance, and fine-grained visual details."
)
client = MilvusClient(uri=MILVUS_URI, token=MILVUS_TOKEN)
collection_name = "simple_ai_rerank_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("content", DataType.VARCHAR, max_length=4096)
schema.add_field("embedding", DataType.FLOAT_VECTOR, dim=VECTOR_DIM)
schema.add_function(Function(name="embed_video", function_type=FunctionType.TEXTEMBEDDING, input_field_names=["content"], output_field_names=["embedding"], params={"provider": "aliyun_milvus", "model_name": EMBEDDING_MODEL, "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, [{"content": VIDEO_URL}])
client.flush(collection_name)
client.load_collection(collection_name)
for query_label, query in (("text", QUERY_TEXT), ("image", QUERY_IMAGE_URL)):
reranker = Function(name=f"rerank_video_{query_label}_query", function_type=FunctionType.RERANK, input_field_names=["content"], params={"reranker": "model", "provider": "aliyun_milvus", "model_name": MODEL_NAME, "queries": [query], "is_multimodal": "true", "instruct": INSTRUCT, "timeout_sec": 10})
for hit in client.search(collection_name=collection_name, data=[query], anns_field="embedding", limit=1, output_fields=["content"], ranker=reranker)[0]:
print(f"{query_label} score={hit['distance']:.4f} content={hit['entity']['content']}")
The expected results are as follows:
-
The text query reranks the video candidates based on the text description.
-
The image query reranks the video candidates based on the subject, appearance, and scene in the reference image.
-
In production environments, we recommend that you truncate the vector recall results before reranking, and maintain a stable mapping between candidate URLs and business primary keys.