tcvectordb-rust 0.1.0

Rust SDK for Tencent Cloud VectorDB
Documentation

Tencent VectorDB Rust SDK

Rust SDK for Tencent Cloud VectorDB.

功能特性

  • 数据库和集合管理
  • 文档的增删改查操作
  • 向量相似性搜索
  • 索引管理
  • 过滤器支持
  • 异步API设计
  • 类型安全的Rust接口

安装

在你的 Cargo.toml 文件中添加:

[dependencies]
tcvectordb-rust = "0.1.0"
tokio = { version = "1.0", features = ["full"] }

快速开始

use tcvectordb_rust::{
    VectorDBClient, Document, Index, VectorIndex, FilterIndex,
    enums::{IndexType, MetricType, FieldType, ReadConsistency},
};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 创建客户端
    let client = VectorDBClient::new(
        "http://localhost:8100",
        "root",
        "your-api-key",
        ReadConsistency::EventualConsistency,
        30,
    )?;

    // 创建数据库
    let db = client.create_database("test_db").await?;

    // 创建索引
    let mut index = Index::new();
    index.add_vector_index(VectorIndex::new(
        "vector",
        3,
        IndexType::HNSW,
        MetricType::COSINE,
        None,
    ))?;
    index.add_filter_index(FilterIndex::new(
        "id",
        FieldType::String,
        IndexType::PRIMARY_KEY,
    ))?;

    // 创建集合
    let collection = db.create_collection(
        "test_collection",
        3,
        2,
        Some("Test collection".to_string()),
        Some(index),
        None,
        None,
    ).await?;

    // 插入文档
    let documents = vec![
        Document::new()
            .with_id("doc1")
            .with_vector(vec![0.1, 0.2, 0.3])
            .with_field("title", "Document 1"),
    ];

    collection.upsert(documents, None, true).await?;

    // 搜索相似向量
    let results = collection.search(
        vec![vec![0.1, 0.2, 0.3]],
        None,
        None,
        false,
        10,
        None,
        None,
        None,
    ).await?;

    println!("Search results: {:?}", results);

    Ok(())
}

主要组件

VectorDBClient

客户端是与VectorDB服务交互的入口点:

let client = VectorDBClient::new(
    "http://localhost:8100",  // 服务地址
    "root",                   // 用户名
    "your-api-key",          // API密钥
    ReadConsistency::EventualConsistency,  // 读一致性
    30,                      // 超时时间(秒)
)?;

Database

数据库管理操作:

// 创建数据库
let db = client.create_database("my_database").await?;

// 列出所有数据库
let databases = client.list_databases().await?;

// 删除数据库
client.drop_database("my_database").await?;

Collection

集合管理和文档操作:

// 创建集合
let collection = db.create_collection(
    "my_collection",
    3,    // 分片数
    2,    // 副本数
    Some("Description".to_string()),
    Some(index),
    None,
    None,
).await?;

// 插入文档
collection.upsert(documents, None, true).await?;

// 查询文档
let results = collection.query(
    Some(vec!["doc1".to_string()]),
    true,
    Some(10),
    None,
    None,
    None,
    None,
).await?;

// 向量搜索
let search_results = collection.search(
    vec![vec![0.1, 0.2, 0.3]],
    None,
    None,
    false,
    10,
    None,
    None,
    None,
).await?;

Index

索引定义:

let mut index = Index::new();

// 向量索引
index.add_vector_index(VectorIndex::new(
    "vector",
    768,  // 维度
    IndexType::HNSW,
    MetricType::COSINE,
    Some(IndexParams::HNSW(HNSWParams::new(16, 200))),
))?;

// 过滤索引
index.add_filter_index(FilterIndex::new(
    "category",
    FieldType::String,
    IndexType::FILTER,
))?;

// 主键索引
index.add_filter_index(FilterIndex::new(
    "id",
    FieldType::String,
    IndexType::PRIMARY_KEY,
))?;

Document

文档操作:

let doc = Document::new()
    .with_id("doc1")
    .with_vector(vec![0.1, 0.2, 0.3])
    .with_field("title", "My Document")
    .with_field("category", "tech")
    .with_field("score", 0.95);

// 获取字段值
let id = doc.get_id();
let vector = doc.get_vector();
let title = doc.get("title");

Filter

过滤条件:

use tcvectordb_rust::Filter;

// 基本过滤
let filter = Filter::new("category=\"tech\"");

// 组合过滤
let filter = Filter::new("category=\"tech\"")
    .and("score > 0.8")
    .or("priority=\"high\"");

// 使用辅助方法
let filter_str = Filter::include("tags", vec!["rust", "database"]);
let filter_str = Filter::in_values("status", vec!["active", "pending"]);

索引类型

向量索引类型

  • FLAT: 暴力搜索,精确但较慢
  • HNSW: 分层导航小世界图,平衡精度和速度
  • IVF_FLAT: 倒排文件索引
  • IVF_PQ: 乘积量化的倒排文件索引
  • IVF_SQ8/SQ4/SQ16: 标量量化的倒排文件索引

标量索引类型

  • PRIMARY_KEY: 主键索引
  • FILTER: 过滤索引
  • SPARSE_INVERTED: 稀疏向量倒排索引

度量类型

  • L2: 欧几里得距离
  • IP: 内积
  • COSINE: 余弦相似度
  • HAMMING: 汉明距离(用于二进制向量)

字段类型

标量字段类型

  • Uint64: 64位无符号整数
  • String: 字符串
  • Array: 数组
  • Json: JSON对象

向量字段类型

  • Vector: 浮点向量
  • Float16Vector: 16位浮点向量
  • BFloat16Vector: BFloat16向量
  • BinaryVector: 二进制向量
  • SparseVector: 稀疏向量

错误处理

SDK使用 Result<T, VectorDBError> 进行错误处理:

use tcvectordb_rust::error::VectorDBError;

match collection.upsert(documents, None, true).await {
    Ok(result) => println!("Success: {:?}", result),
    Err(VectorDBError::ParamError { code, message }) => {
        eprintln!("Parameter error {}: {}", code, message);
    }
    Err(VectorDBError::ConnectError { code, message }) => {
        eprintln!("Connection error {}: {}", code, message);
    }
    Err(e) => eprintln!("Other error: {}", e),
}

示例

查看 examples/ 目录中的完整示例:

cargo run --example basic_usage

与Python SDK的对应关系

Python Rust
tcvectordb.VectorDBClient VectorDBClient
tcvectordb.model.database.Database Database
tcvectordb.model.collection.Collection Collection
tcvectordb.model.document.Document Document
tcvectordb.model.index.Index Index
tcvectordb.model.document.Filter Filter

许可证

MIT License

贡献

欢迎提交问题和拉取请求!