pub struct Database { /* private fields */ }Expand description
MoteDB 数据库实例
§快速开始
use motedb::Database;
// 打开数据库
let db = Database::open("data.mote")?;
// SQL 操作
db.execute("CREATE TABLE users (id INT, name TEXT, email TEXT)")?;
db.execute("INSERT INTO users VALUES (1, 'Alice', 'alice@example.com')")?;
let results = db.query("SELECT * FROM users WHERE id = 1")?;
// 多模态索引
db.execute("CREATE INDEX users_email ON users(email)")?; // 列索引
db.execute("CREATE VECTOR INDEX docs_vec ON docs(embedding)")?; // 向量索引
```ignore///
# 1. SQL 操作
- `query()` / `execute()`: 执行 SQL 语句
# 2. 事务管理
- `begin_transaction()`: 开始事务
- `commit_transaction()`: 提交事务
- `rollback_transaction()`: 回滚事务
- `savepoint()`: 创建保存点
# 3. 批量操作
- `batch_insert()`: 批量插入行
- `batch_insert_with_vectors()`: 批量插入向量数据
# 4. 索引管理
- `create_column_index()`: 创建列索引(快速等值/范围查询)
- `create_vector_index()`: 创建向量索引(KNN搜索)
- `create_text_index()`: 创建全文索引(BM25搜索)
- `create_ioctree_index()`: 创建i-Octree 3D空间索引
# 5. 查询API
- `query_by_column()`: 按列值查询(使用索引)
- `vector_search()`: 向量KNN搜索
- `text_search()`: 全文搜索(BM25)
- `query_timestamp_range()`: 时间序列查询
# 6. 统计信息
- `stats()`: 数据库统计信息
- `vector_index_stats()`: 向量索引统计
- `transaction_stats()`: 事务统计
# 7. 持久化
- `flush()`: 刷新数据到磁盘
- `checkpoint()`: 创建检查点
- `close()`: 关闭数据库Implementations§
Source§impl Database
impl Database
Sourcepub fn open_with_config<P: AsRef<Path>>(
path: P,
config: DBConfig,
) -> Result<Self>
pub fn open_with_config<P: AsRef<Path>>( path: P, config: DBConfig, ) -> Result<Self>
Open an existing database with custom configuration
Use this to apply edge-optimized settings when reopening:
let config = DBConfig::for_edge();
let db = Database::open_with_config("data.mote", config)?;Sourcepub fn wait_for_indexes_ready(&self) -> bool
pub fn wait_for_indexes_ready(&self) -> bool
Wait until all pending index build batches have been processed.
Call after flush() to ensure indexes are fully built before querying.
Returns true if all batches completed, false on timeout.
Sourcepub fn columnar_store(&self) -> &ColumnarStore
pub fn columnar_store(&self) -> &ColumnarStore
Access the columnar segment store (for TimeSeries tables).
Sourcepub fn checkpoint(&self) -> Result<()>
pub fn checkpoint(&self) -> Result<()>
Checkpoint: flush data + persist indexes + truncate WAL
Stronger durability guarantee than flush() alone. Use before closing to ensure full recoverability.
Sourcepub fn checkpoint_full(&self) -> Result<()>
pub fn checkpoint_full(&self) -> Result<()>
Full checkpoint with index rebuild (slower but thorough). Used internally on shutdown to ensure index completeness.
Sourcepub fn vacuum(&self) -> Result<()>
pub fn vacuum(&self) -> Result<()>
VACUUM: reclaim space by forcing compaction and dropping tombstones.
This runs a full compaction cycle across all LSM levels, dropping tombstone entries and reclaiming disk space. Also flushes column indexes to disk and ensures they are consistent.
§Cost
- Blocks writes during compaction (may take seconds to minutes).
- Rewrites all SSTables.
§When to use
- After bulk DELETE operations
- Before taking a backup
- Periodically in long-running deployments (e.g., weekly)
Sourcepub fn max_result_rows(&self) -> Option<usize>
pub fn max_result_rows(&self) -> Option<usize>
🚀 执行 SQL 查询(流式零内存开销)
返回流式结果,支持:
- 流式遍历(零内存开销)
- 物化为 Vec(等同于旧的 execute)
§Examples
// 方式 1: 流式处理大结果集(推荐)
let result = db.execute("SELECT * FROM users WHERE age > 18")?;
result.for_each(|columns, row| {
println!("{:?}: {:?}", columns, row);
Ok(())
})?;
// 方式 2: 物化为 Vec(兼容旧 API)
let result = db.execute("SELECT * FROM users")?;
let materialized = result.materialize()?;
match materialized {
QueryResult::Select { columns, rows } => {
println!("Found {} rows", rows.len());
}
_ => {}
}
// 其他语句(INSERT/UPDATE/DELETE/CREATE/DROP)
db.execute("CREATE TABLE users (id INT, name TEXT, email TEXT)")?;
db.execute("INSERT INTO users VALUES (1, 'Alice', 'alice@example.com')")?;
db.execute("UPDATE users SET email = 'new@example.com' WHERE id = 1")?;
db.execute("DELETE FROM users WHERE id = 1")?;
db.execute("CREATE INDEX users_email ON users(email)")?;
db.execute("CREATE VECTOR INDEX docs_vec ON docs(embedding)")?;Returns the configured max_result_rows limit, if any.
Use with for_each() or materialize_with_limit() for bounded queries.
Sourcepub fn row_count(&self, table_name: &str) -> Result<usize>
pub fn row_count(&self, table_name: &str) -> Result<usize>
Get the approximate row count for a table without executing SQL. Returns the live row count from the ColSegmentStore if available, otherwise falls back to the LSM row counter.
pub fn execute(&self, sql: &str) -> Result<StreamingQueryResult>
Sourcepub fn execute_prepared(
&self,
sql: &str,
params: Vec<Value>,
) -> Result<StreamingQueryResult>
pub fn execute_prepared( &self, sql: &str, params: Vec<Value>, ) -> Result<StreamingQueryResult>
Execute a parameterized query.
The SQL string is parsed once and cached (by the same LRU statement cache
as execute()). On subsequent calls with the same SQL text, the cached
AST is reused — only the bind values change. This eliminates the
Lexer → Parser overhead for repeated queries.
Use ? for positional parameters:
// First call: parses + caches
let result = db.execute_prepared("SELECT * FROM users WHERE id = ?", vec![Value::Integer(42)])?;
// Second call: cache hit, skips parser
let result = db.execute_prepared("SELECT * FROM users WHERE id = ?", vec![Value::Integer(99)])?;Sourcepub fn begin_transaction(&self) -> Result<u64>
pub fn begin_transaction(&self) -> Result<u64>
Sourcepub fn commit_transaction(&self, tx_id: u64) -> Result<()>
pub fn commit_transaction(&self, tx_id: u64) -> Result<()>
Sourcepub fn rollback_transaction(&self, tx_id: u64) -> Result<()>
pub fn rollback_transaction(&self, tx_id: u64) -> Result<()>
Sourcepub fn batch_insert(
&self,
table_name: &str,
rows: Vec<Row>,
) -> Result<Vec<RowId>>
pub fn batch_insert( &self, table_name: &str, rows: Vec<Row>, ) -> Result<Vec<RowId>>
批量插入行(比逐行插入快10-20倍)
注意: 此方法接受底层 Row 类型(Vec<Value>),如果需要使用 HashMap,请使用 batch_insert_map()。
§Examples
use motedb::types::{Value, Row};
let mut rows = Vec::new();
for i in 0..1000 {
let row = vec![
Value::Integer(i),
Value::Text(format!("User{}", i)),
];
rows.push(row);
}
let row_ids = db.batch_insert("users", rows)?;
println!("Inserted {} rows", row_ids.len());Sourcepub fn batch_insert_map(
&self,
table_name: &str,
sql_rows: Vec<SqlRow>,
) -> Result<Vec<RowId>>
pub fn batch_insert_map( &self, table_name: &str, sql_rows: Vec<SqlRow>, ) -> Result<Vec<RowId>>
批量插入行(使用 HashMap,比逐行插入快10-20倍)
这是 batch_insert() 的友好版本,接受 HashMap<String, Value> 格式的行数据。
§Examples
use motedb::types::{Value, SqlRow};
use std::collections::HashMap;
let mut rows = Vec::new();
for i in 0..1000 {
let mut row = HashMap::new();
row.insert("id".to_string(), Value::Integer(i));
row.insert("name".to_string(), Value::Text(format!("User{}", i)));
rows.push(row);
}
let row_ids = db.batch_insert_map("users", rows)?;
println!("Inserted {} rows", row_ids.len());pub fn batch_insert_with_vectors_map( &self, table_name: &str, sql_rows: Vec<SqlRow>, vector_columns: &[&str], ) -> Result<Vec<RowId>>
Sourcepub fn batch_insert_with_vectors(
&self,
table_name: &str,
rows: Vec<Row>,
_vector_columns: &[&str],
) -> Result<Vec<RowId>>
pub fn batch_insert_with_vectors( &self, table_name: &str, rows: Vec<Row>, _vector_columns: &[&str], ) -> Result<Vec<RowId>>
批量插入带向量的数据(自动构建向量索引)
注意: 此方法接受底层 Row 类型(Vec<Value>),如果需要使用 HashMap,请使用 batch_insert_with_vectors_map()。
§Examples
use motedb::types::{Value, Row};
let mut rows = Vec::new();
for i in 0..1000 {
let row = vec![
Value::Integer(i),
Value::Vector(vec![0.1; 128]),
];
rows.push(row);
}
let row_ids = db.batch_insert_with_vectors("documents", rows, &["embedding"])?;Sourcepub fn create_column_index(
&self,
table_name: &str,
column_name: &str,
) -> Result<()>
pub fn create_column_index( &self, table_name: &str, column_name: &str, ) -> Result<()>
批量插入带向量的数据(使用 HashMap,自动构建向量索引)
§Examples
use motedb::types::{Value, SqlRow};
use std::collections::HashMap;
let mut rows = Vec::new();
for i in 0..1000 {
let mut row = HashMap::new();
row.insert("id".to_string(), Value::Integer(i));
row.insert("embedding".to_string(), Value::Vector(vec![0.1; 128]));
rows.push(row);
}
let row_ids = db.batch_insert_with_vectors_map("documents", rows, &["embedding"])?;创建列索引(用于快速等值/范围查询)
§Examples
// 创建列索引后,WHERE email = '...' 查询速度提升40倍
db.create_column_index("users", "email")?;
// 查询会自动使用索引
let results = db.query("SELECT * FROM users WHERE email = 'alice@example.com'")?;Sourcepub fn create_text_index(&self, index_name: &str) -> Result<()>
pub fn create_text_index(&self, index_name: &str) -> Result<()>
Sourcepub fn query_by_column(
&self,
table_name: &str,
column_name: &str,
value: &Value,
) -> Result<Vec<RowId>>
pub fn query_by_column( &self, table_name: &str, column_name: &str, value: &Value, ) -> Result<Vec<RowId>>
Sourcepub fn query_by_column_range(
&self,
table_name: &str,
column_name: &str,
start: &Value,
end: &Value,
) -> Result<Vec<RowId>>
pub fn query_by_column_range( &self, table_name: &str, column_name: &str, start: &Value, end: &Value, ) -> Result<Vec<RowId>>
Sourcepub fn query_by_column_between(
&self,
table_name: &str,
column_name: &str,
start: &Value,
start_inclusive: bool,
end: &Value,
end_inclusive: bool,
) -> Result<Vec<RowId>>
pub fn query_by_column_between( &self, table_name: &str, column_name: &str, start: &Value, start_inclusive: bool, end: &Value, end_inclusive: bool, ) -> Result<Vec<RowId>>
Sourcepub fn vector_search(
&self,
index_name: &str,
query: &[f32],
k: usize,
) -> Result<Vec<(RowId, f32)>>
pub fn vector_search( &self, index_name: &str, query: &[f32], k: usize, ) -> Result<Vec<(RowId, f32)>>
Sourcepub fn text_search_ranked(
&self,
index_name: &str,
query: &str,
top_k: usize,
) -> Result<Vec<(RowId, f32)>>
pub fn text_search_ranked( &self, index_name: &str, query: &str, top_k: usize, ) -> Result<Vec<(RowId, f32)>>
Sourcepub fn vector_index_stats(&self, index_name: &str) -> Result<VectorIndexStats>
pub fn vector_index_stats(&self, index_name: &str) -> Result<VectorIndexStats>
Sourcepub fn create_ioctree_index(&self, index_name: &str) -> Result<()>
pub fn create_ioctree_index(&self, index_name: &str) -> Result<()>
Create an i-Octree 3D spatial index for point cloud data
Use for SLAM, robotics, and 3D perception workloads.
Sourcepub fn ioctree_knn_search(
&self,
index_name: &str,
point: &Point3D,
k: usize,
) -> Result<Vec<(RowId, f64)>>
pub fn ioctree_knn_search( &self, index_name: &str, point: &Point3D, k: usize, ) -> Result<Vec<(RowId, f64)>>
3D KNN query: find k nearest neighbors
Returns (row_id, distance) pairs sorted by distance.
Sourcepub fn transaction_stats(&self) -> TransactionStats
pub fn transaction_stats(&self) -> TransactionStats
Sourcepub fn insert_row_with_txn(
&self,
table_name: &str,
txn_id: u64,
row: Row,
) -> Result<RowId>
pub fn insert_row_with_txn( &self, table_name: &str, txn_id: u64, row: Row, ) -> Result<RowId>
Insert a row within a transaction. The row is buffered and only written
to storage when the transaction commits. Use this instead of insert_row
when operating inside a transaction.
Sourcepub fn insert_row_map(&self, table_name: &str, sql_row: SqlRow) -> Result<RowId>
pub fn insert_row_map(&self, table_name: &str, sql_row: SqlRow) -> Result<RowId>
插入行(使用 HashMap)
这是 insert_row() 的友好版本,接受 HashMap<String, Value> 格式的行数据。
§Examples
use motedb::types::{Value, SqlRow};
use std::collections::HashMap;
let mut row = HashMap::new();
row.insert("id".to_string(), Value::Integer(1));
row.insert("name".to_string(), Value::Text("Alice".into()));
let row_id = db.insert_row_map("users", row)?;Sourcepub fn get_row(&self, table_name: &str, row_id: RowId) -> Result<Option<Row>>
pub fn get_row(&self, table_name: &str, row_id: RowId) -> Result<Option<Row>>
获取行(底层API,推荐使用 SQL SELECT)
Trait Implementations§
Auto Trait Implementations§
impl !Freeze for Database
impl !RefUnwindSafe for Database
impl !UnwindSafe for Database
impl Send for Database
impl Sync for Database
impl Unpin for Database
impl UnsafeUnpin for Database
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more