Zvec Logo

快速开始

开箱即用,几分钟内轻松上手 Zvec:创建 collection、写入 document、执行向量相似度检索。

想动手试试代码示例?欢迎查看 Jupyter Notebook 教程。它会手把手带你完成一个多模态图片检索的实操示例。

安装

pip install zvec

创建 Collection

Collection 用于存储你的 Document。每个 Document 包含标量字段和向量字段。

定义 Schema 并创建 Collection。Schema 包含两部分:fields 用于标量字段,vectors 用于向量字段。

创建 collection
import zvec

# 定义 collection schema
collection_schema = zvec.CollectionSchema(  
    name="my_collection",
    fields=[
        zvec.FieldSchema(
            name="publish_year",
            data_type=zvec.DataType.INT32,
            index_param=zvec.InvertIndexParam(enable_range_optimization=True),
        ),
    ],
    vectors=[
        zvec.VectorSchema(
            name="embedding",
            data_type=zvec.DataType.VECTOR_FP32,
            dimension=768,
            index_param=zvec.HnswIndexParam(metric_type=zvec.MetricType.COSINE),
        ),
    ],
)

# 创建 collection
collection = zvec.create_and_open(  
    path="./my_collection_data",
    schema=collection_schema,
)

注意:在插入或查询数据时,必须严格使用此处定义的字段名(publish_yearembedding),确保名称完全一致。

添加 Document

插入包含标量和向量字段的 Document:

插入 document
collection.insert(  
    zvec.Doc(
        id="book_1",  # document 的唯一标识
        vectors={"embedding": [0.1] * 768}, # 请替换为你实际的向量数据
        fields={"publish_year": 1936},
    )
)

注意:字段名必须完全匹配。publish_year 字段和 embedding 向量必须与你之前在 Schema 中定义的名称保持一致。

优化 Collection

新插入的向量会先暂存在临时索引。调用 optimize() 构建向量索引以加速检索:

优化 collection
collection.optimize()

按 ID 获取 Document

通过 id 直接 获取 一个 Document:

获取 document
result = collection.fetch(ids="book_1")   
print(result)

获取 document
let result = collection.fetchSync("book_1");  
console.log(result);

向量检索

相似度检索

使用 query() 检索与给定向量最相似的 Documents:

相似度检索
result = collection.query(  
    zvec.VectorQuery(
        field_name="embedding",
        vector=[0.3] * 768,  # 请替换为你实际的向量数据
    ),
    topk=10,
)
print(result)

结果按相似度分数排序。

相似度检索
let result = collection.querySync({   
    fieldName: "embedding",
    vector: Array(768).fill(0.3),     // 请替换为你实际的向量数据
    topk: 10
});
console.log(result);

结果按相似度分数排序。

带条件过滤的相似度检索

将向量检索与条件过滤结合 — 检索时仅考虑满足条件的 documents:

带条件过滤的相似度检索
result = collection.query(        
    zvec.VectorQuery(
        field_name="embedding",
        vector=[0.3] * 768,   # 请替换为你实际的向量数据
    ),
    topk=10,
    filter="publish_year > 1936", 
)
print(result)

带条件过滤的相似度检索
let result = collection.querySync({     
    fieldName: "embedding",
    vector: Array(768).fill(0.3),   // 请替换为你实际的向量数据
    topk: 10,
    filter: "publish_year > 1936"
});
console.log(result);

查看 Collection 信息

查看 collection schema:

查看 collection schema
print(collection.schema)

查看 collection 的统计信息:

查看 collection 的统计信息
print(collection.stats)

删除 Document

通过 id 删除 document:

删除 document
collection.delete(ids="book_1")

按筛选条件删除 document:

按筛选条件删除 document
collection.delete_by_filter(filter="publish_year < 1900")

✨ 您现在已经准备好使用 Zvec 来存储、获取和检索向量数据了!

💙 感谢您对 Zvec 的关注!希望您能尽情探索 Zvec 的强大功能!

目录