-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdb_demo.rs
More file actions
248 lines (224 loc) · 7.79 KB
/
Copy pathdb_demo.rs
File metadata and controls
248 lines (224 loc) · 7.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
use anda_db::{
collection::{Collection, CollectionConfig},
database::{AndaDB, DBConfig},
error::DBError,
index::HnswConfig,
query::{Filter, Query, RangeQuery, Search},
schema::{AndaDBSchema, Fv, Json, Resource, Vector, vector_from_f32},
storage::StorageConfig,
};
use anda_db_tfs::jieba_tokenizer;
use anda_object_store::MetaStoreBuilder;
use ic_auth_types::Xid;
use object_store::local::LocalFileSystem;
use serde::{Deserialize, Serialize};
use std::{collections::BTreeMap, sync::Arc};
use structured_logger::unix_ms;
#[derive(Debug, Clone, Serialize, Deserialize, AndaDBSchema)]
pub struct Knowledge {
pub _id: u64,
// thread ID, thread is a conversation that multi agents can join.
#[field_type = "Bytes"]
pub thread: Xid,
// seconds since epoch
pub created_at: u64,
// knowledge authors
pub authors: Vec<String>,
// knowledge description
pub description: String,
// knowledge embedding for vector search
pub embedding: Vector,
// knowledge metadata
pub metadata: BTreeMap<String, Json>,
// Data source
pub source: Option<Resource>,
// confidence score
pub score: Option<i64>,
// verification hash
pub hash: Option<[u8; 32]>,
}
// cargo run --example db_demo --features=full
#[tokio::main]
async fn main() -> Result<(), DBError> {
// init structured logger
structured_logger::init();
// let object_store = InMemory::new();
let object_store = MetaStoreBuilder::new(
LocalFileSystem::new_with_prefix("./debug/metastore")?,
10000,
)
.build();
let db_config = DBConfig {
name: "anda_db_demo".to_string(),
description: "Anda DB demo".to_string(),
storage: StorageConfig {
compress_level: 0, // no compression
..Default::default()
},
lock: None, // no lock for demo
};
// connect to the database (create if it doesn't exist)
let db = AndaDB::connect(Arc::new(object_store), db_config).await?;
log::info!(
action = "connect",
database = db.name();
"connected to database"
);
// knowledge schema
let schema = Knowledge::schema()?;
println!("-----> Schema: {:#?}", schema);
let collection_config = CollectionConfig {
name: "knowledges".to_string(),
description: "My knowledges".to_string(),
};
let collection = db
.open_or_create_collection(schema, collection_config, async |collection| {
// set tokenizer
collection.set_tokenizer(jieba_tokenizer());
// create BTree indexes if not exists
collection.create_btree_index_nx(&["thread"]).await?;
collection.create_btree_index_nx(&["created_at"]).await?;
collection.create_btree_index_nx(&["authors"]).await?;
collection.create_btree_index_nx(&["score"]).await?;
// create BM25 & HNSW indexes if not exists
collection
.create_bm25_index_nx(&["authors", "description", "metadata", "source"])
.await?;
collection
.create_hnsw_index_nx(
"embedding",
HnswConfig {
dimension: 10,
..Default::default()
},
)
.await?;
Ok::<(), DBError>(())
})
.await?;
log::info!(
action = "open_or_create_collection",
collection = collection.name();
"opened or created collection"
);
add_knowledges_and_query(&collection).await?;
db.close().await?;
Ok(())
}
async fn add_knowledges_and_query(collection: &Arc<Collection>) -> Result<(), DBError> {
let mut thread = Xid::new();
let knowledges = vec![
Knowledge {
_id: 0,
thread: thread.clone(),
created_at: unix_ms() / 1000,
authors: vec!["Anda".to_string(), "Bill".to_string()],
metadata: BTreeMap::new(),
description: "Rust 是一门系统级编程语言,专注于安全性、并发性和性能。Rust 的所有权系统是其最独特的特性之一,它在编译时确保内存安全。".to_string(),
embedding: vector_from_f32(vec![0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]),
source: None,
score: None,
hash: None,
},
Knowledge {
_id: 0,
thread: thread.clone(),
created_at: unix_ms() / 1000,
authors: vec!["Charlie".to_string()],
metadata: BTreeMap::new(),
description: "向量数据库是一种特殊类型的数据库,专门用于存储和检索向量嵌入,与传统数据库相比,向量数据库能够高效地进行相似性搜索。".to_string(),
embedding: vector_from_f32(vec![0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2]),
source: None,
score: None,
hash: None,
},
];
let metadata = collection.metadata();
println!("-----> Collection metadata: {:?}", metadata);
println!("-----> Add knowledges");
if metadata.stats.num_documents == 0 {
for knowledge in knowledges {
let id = collection.add_from(&knowledge).await?;
println!("Knowledge id: {id}");
}
collection.flush(unix_ms()).await?;
}
println!("-----> Search: id = 1");
let result: Vec<Knowledge> = collection
.search_as(Query {
filter: Some(Filter::Field((
"_id".to_string(),
RangeQuery::Eq(Fv::U64(1)),
))),
..Default::default()
})
.await?;
assert_eq!(result.len(), 1);
// set thread id to the first knowledge for next search
thread = result[0].thread.clone();
for doc in &result {
println!("Find knowledge: {:?}\n", doc);
}
println!("-----> Search: thread = xxx");
let result: Vec<Knowledge> = collection
.search_as(Query {
filter: Some(Filter::Field((
"thread".to_string(),
RangeQuery::Eq(Fv::Bytes(thread.as_slice().into())),
))),
..Default::default()
})
.await?;
assert_eq!(result.len(), 2);
for doc in &result {
println!("Find knowledge: {:?}\n", doc);
}
println!("-----> Search: text = Rust");
let result: Vec<Knowledge> = collection
.search_as(Query {
search: Some(Search {
text: Some("rust".to_string()),
..Default::default()
}),
..Default::default()
})
.await?;
assert_eq!(result.len(), 1);
for doc in &result {
println!("Find knowledge: {:?}\n", doc);
}
println!("-----> Search: vector search");
let result: Vec<Knowledge> = collection
.search_as(Query {
search: Some(Search {
vector: Some(vec![0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2]),
..Default::default()
}),
..Default::default()
})
.await?;
assert_eq!(result.len(), 2);
for doc in &result {
println!("Find knowledge: {:?}\n", doc);
}
println!("-----> Search: compound query");
let result: Vec<Knowledge> = collection
.search_as(Query {
search: Some(Search {
text: Some("数据库".to_string()),
vector: Some(vec![0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2]),
..Default::default()
}),
filter: Some(Filter::Field((
"_id".to_string(),
RangeQuery::Gt(Fv::U64(1)),
))),
..Default::default()
})
.await?;
assert_eq!(result.len(), 1);
for doc in &result {
println!("Find knowledge: {:?}\n", doc);
}
Ok(())
}