本文介紹如何使用DashVector的多向量檢索功能。
在某些AI檢索的場景,會涉及一個實體對應多個向量,在檢索時希望通過多個向量檢索來找到最可能的實體,例如:
- 在自然語言處理中,標題和文檔分別抽取為不同的向量特徵,需要根據標題向量和文檔向量同時做檢索。
- 在商品檢索時,商品的圖片和文字分別抽取為不同的向量特徵,需要根據圖片向量和文字向量同時做檢索。
為了滿足這些需求,DashVector支持了多向量檢索。
使用示例
前提條件
- 已創建Cluster
- 已獲得API-KEY
- 已安裝最新版SDK
創建多向量集合
説明
需要使用您的api-key替換示例中的 YOUR_API_KEY、您的Cluster Endpoint替換示例中的YOUR_CLUSTER_ENDPOINT,代碼才能正常運行。
import dashvector
import numpy as np
from dashvector import VectorParam, Doc, WeightedRanker, VectorQuery, RrfRanker
client = dashvector.Client(
api_key='YOUR_API_KEY',
endpoint='YOUR_CLUSTER_ENDPOINT'
)
ret = client.create(
'multi_vector_demo',
vectors={
"title": VectorParam(4),
"content": VectorParam(6, metric="euclidean"),
},
fields_schema={
'author': str,
}
)
assert ret
插入數據
説明
insert/upsert要求至少一個向量字段有值。
collection = client.get(name='multi_vector_demo')
docs = []
for i in range(10):
docs.append(Doc(id=str(i),
vectors={"title": np.random.random(4),
"content": np.random.random(6)
},
)
)
ret = collection.insert(docs)
print(ret)
執行檢索
説明
- 檢索時採用的策略為多個向量分別執行檢索後融合排序。
- VectorQuery 支持的其他參數見 向量檢索高級參數。
title_vector = [0.1, 0.2, 0.3, 0.4]
content_vector = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6]
vectors = {
"title": VectorQuery(vector=title_vector, num_candidates=10),
"content": VectorQuery(vector=content_vector),
}
ret = collection.query(
vector=vectors,
include_vector=False,
# 使用RRF融合排序
# rerank=RrfRanker(rank_constant=100)
# 使用加權融合排序
rerank=WeightedRanker(weights={"title": 1.0, "content": 1.0}),
topk=20
)
assert ret
print(ret.output)
# 使用單個向量執行檢索
ret = collection.query(vector={"title": VectorQuery(vector=title_vector)})
assert ret
print(ret.output)
# 使用單個向量執行分組向量檢索
ret = collection.query_group_by(title_vector, group_by_field='author', vector_field='title')
assert ret
print(ret)
限制説明
重要
- 當前單個集合最多支持4個向量字段。
- 隨向量字段的個數增加,Cluster中可插入的Doc條數會減少,插入和檢索的性能會下降。
- 檢索時允許只對部分向量做檢索,集合中包含n個向量字段時,允許使用1-n個向量字段做向量檢索,允許使用其中的任意一個向量字段做分組向量檢索。