Pinecone 兼容向量搜索

MatrixOne Python SDK 提供 Pinecone 兼容接口,可用相近的调用方式执行向量相似度查询、元数据过滤、写入和删除。接口操作的是 MatrixOne 表,不会连接 Pinecone 云端服务。

前提条件

  • MatrixOne 实例正在运行,且已安装 matrixone-python-sdk。

  • 向量列使用 f32;写入和查询向量的维度必须与列定义一致。

  • 使用兼容接口前,先在目标向量列上创建 IVF 索引。

安装 SDK:

pip3 install matrixone-python-sdk

创建 IVF 索引并获取接口

先创建并写入表数据,再创建 IVF 索引。以下片段假定 client 已连接,且表中已有向量数据;示例使用教程中的表名和列名:

client.vector_ops.create_ivf(
    "pinecone_demo_docs",
    "idx_embedding_ivf",
    "embedding",
    lists=2,
    op_type="vector_l2_ops",
)
pinecone_index = client.get_pinecone_index("pinecone_demo_docs", "embedding")

get_pinecone_index() 要求目标表和 IVF 索引已存在。列表数 lists 应结合数据规模评估;示例值 2 不是通用生产配置。

查询与过滤

query() 返回结果中的 matches。需要读取元数据时,显式设置 include_metadata=True:

results = pinecone_index.query(
    vector=query_vector,
    top_k=10,
    include_metadata=True,
    filter={"category": {"$eq": "AI"}},
)

for match in results.matches:
    print(match.id, match.score, match.metadata)

支持的字段操作符包括 $eq、$ne、$lt、$gt、$lte、$gte、$in、$nin;逻辑操作符包括 $and 和 $or。相等比较也使用显式操作符,例如 {“category”: {“$eq”: “AI”}};不要把 {“category”: “AI”} 当作等值过滤语法。

如果需要在查询结果中返回向量值,再设置 include_values=True。默认情况下不返回元数据和向量值。

写入、删除和统计

pinecone_index.upsert([
    {"id": 10, "category": "AI", "embedding": embedding_10},
])
pinecone_index.delete([10])
stats = pinecone_index.describe_index_stats()

upsert() 按 ID 插入或更新记录;delete() 可按 ID 批量删除。统计结果可用于查看向量总数和维度。

常见问题

  • 维度不匹配:检查表中向量列维度,并确保每次 upsert 和 query 使用相同维度。

  • 查询没有结果:先去掉过滤条件,确认索引中有向量,再逐步加回过滤条件。

  • 没有返回元数据:在 query() 中设置 include_metadata=True。

  • 无法获取兼容接口:确认表、向量列和 IVF 索引均已创建。

相关文档