快速开始
想要交互式地探索代码示例?查看我们的 Jupyter Notebook 教程,演示 Zvec 的实际应用 — 包含一个多模态图片搜索的动手示例。
安装
pip install zvec创建 Collection
Collection 用于存储你的 Document。每个 Document 包含标量字段和向量 Embedding。
定义一个 Schema 并创建 Collection。Schema 包含两部分:fields 用于标量数据,vectors 用于向量 Embedding。
import zvec
# Define a 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),
),
],
)
# Create a collection
collection = zvec.create_and_open(
path="./my_collection_data",
schema=collection_schema,
)注意:此处定义的字段名(publish_year、embedding)在插入或查询数据时必须完全一致。
添加 Document
插入 包含标量字段和向量 Embedding 的 Document:
collection.insert(
zvec.Doc(
id="book_1", # Unique document ID
vectors={"embedding": [0.1] * 768}, # Replace with your actual vector
fields={"publish_year": 1936},
)
)注意:字段名必须完全匹配。publish_year 字段和 embedding 向量必须使用你在 Schema 中定义的相同名称。
优化 Collection
新插入的向量会先被缓冲。调用 optimize() 构建向量索引以加速搜索:
collection.optimize()按 ID 检索 Document
通过 id 直接 Fetch 一个 Document:
result = collection.fetch(ids="book_1")
print(result)let result = collection.fetchSync("book_1");
console.log(result);向量搜索
基本相似度搜索
使用 query() 查找与给定向量 Embedding 最相似的 Document:
result = collection.query(
zvec.VectorQuery(
field_name="embedding",
vector=[0.3] * 768, # Replace with your actual vector
),
topk=10,
)
print(result)结果按相似度分数排序。
let result = collection.querySync({
fieldName: "embedding",
vector: Array(768).fill(0.3), // Replace with your actual vector
topk: 10
});
console.log(result);结果按相似度分数排序。
带过滤的相似度搜索
将向量搜索与条件过滤结合 — 搜索时仅考虑满足条件的 Document:
result = collection.query(
zvec.VectorQuery(
field_name="embedding",
vector=[0.3] * 768, # Replace with your actual vector
),
topk=10,
filter="publish_year > 1936",
)
print(result)let result = collection.querySync({
fieldName: "embedding",
vector: Array(768).fill(0.3), // Replace with your actual vector
topk: 10,
filter: "publish_year > 1936"
});
console.log(result);查看 Collection 信息
查看 Collection 的 Schema:
print(collection.schema)查看 Collection 的统计信息:
print(collection.stats)删除 Document
通过 ID 删除一个 Document:
collection.delete(ids="book_1")通过过滤条件删除 Document:
collection.delete_by_filter(filter="publish_year < 1900")✨ 你已准备好使用 Zvec 存储、检索和搜索向量数据了!
💙 感谢你对 Zvec 的关注!希望你享受探索 Zvec 的过程!