You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Milvus中DataType.BINARY_VECTOR搜索时遇错误求助

问题排查与解决方案

Milvus中DataType.BINARY_VECTOR类型的向量要求以bytes格式存储和查询,原代码直接传入np.bool_数组会导致格式不匹配错误,以下是修正方案:

关键修改点

  • 插入数据时:将布尔数组通过np.packbits()打包为字节数组,再转为bytes类型
  • 搜索查询时:对查询向量执行同样的格式转换操作

修正后的完整代码

from pymilvus import MilvusClient, DataType
from pathlib import Path
import numpy as np


DB_FILE = 'demo.db'
DIM = 4096  # 需为8的倍数,若不是需补位处理
COLLECTION_NAME = 'dim_reduction'
METRIC_TYPE = 'HAMMING'
INDEX_TYPE = 'BIN_FLAT'
DATATYPE = DataType.BINARY_VECTOR
DTYPE = np.bool_


# Remove DB_FILE if exists
db_path = Path(DB_FILE)
if db_path.exists():
    db_path.unlink()

# Build client
client = MilvusClient(DB_FILE)

# Create schema
schema = MilvusClient.create_schema()
schema.add_field(field_name="id", datatype=DataType.INT64, is_primary=True)
schema.add_field(field_name='text', datatype=DataType.VARCHAR, max_length=1024)
schema.add_field(field_name='vector', datatype=DATATYPE, dim=DIM)

# Create collection
client.create_collection(
    collection_name=COLLECTION_NAME,
    schema=schema,
)

# Insert data:转换向量为bytes格式
data = [
    {'id': i, 
     'vector': np.packbits(np.array([1] * DIM, dtype=DTYPE)).tobytes(), 
     'text': f'doc {i}'}
    for i in range(100)
]
client.insert(collection_name=COLLECTION_NAME, data=data)

# Create index
index_params = MilvusClient.prepare_index_params()
index_params.add_index(
    field_name='vector',
    metric_type=METRIC_TYPE,
    index_type=INDEX_TYPE,
)
client.create_index(
    collection_name=COLLECTION_NAME,
    index_params=index_params,
)

# Search:转换查询向量为bytes格式
search_params = {
    'metric_type': METRIC_TYPE,
    'params': {},
}

query_vector = np.packbits(np.array([1] * DIM, dtype=DTYPE)).tobytes()
result = client.search(
    collection_name=COLLECTION_NAME,
    data=[query_vector],
    limit=2,
    search_params=search_params,
)
print(result)

额外说明

如果向量维度不是8的倍数,需要先对数组补0至最近的8的倍数,再执行np.packbits()转换,否则会触发维度不匹配错误。

内容的提问来源于stack exchange,提问作者Trevor Miller

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 06:53:17