-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathcollection.rs
More file actions
83 lines (71 loc) · 2.53 KB
/
collection.rs
File metadata and controls
83 lines (71 loc) · 2.53 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
use milvus::index::{IndexParams, IndexType};
use milvus::options::LoadOptions;
use milvus::proto::schema::DataType;
use milvus::query::QueryOptions;
use milvus::schema::{CollectionSchema, CollectionSchemaBuilder, FieldSchemaBuilder};
use milvus::{
client::Client, data::FieldColumn, error::Error,
};
use std::collections::HashMap;
use rand::prelude::*;
const DEFAULT_VEC_FIELD: &str = "embed";
const DIM: i64 = 256;
#[tokio::main]
async fn main() -> Result<(), Error> {
const URL: &str = "http://localhost:19530";
let client = Client::new(URL).await?;
let schema =
CollectionSchemaBuilder::new("hello_milvus", "a guide example for milvus rust SDK")
.add_field(FieldSchemaBuilder::new()
.with_name("id").with_dtype(DataType::Int64)
.with_description("primary key field")
.with_primary(true)
.build()
)
.add_field(FieldSchemaBuilder::new()
.with_name(DEFAULT_VEC_FIELD)
.with_dtype(DataType::FloatVector)
.with_dim(DIM)
.build()
)
.build()?;
client.create_collection(schema.clone(), None).await?;
if let Err(err) = hello_milvus(&client, &schema).await {
println!("failed to run hello milvus: {:?}", err);
}
client.drop_collection(schema.name()).await?;
Ok(())
}
async fn hello_milvus(client: &Client, collection: &CollectionSchema) -> Result<(), Error> {
let mut embed_data = Vec::<f32>::new();
for _ in 1..=DIM * 1000 {
let mut rng = rand::thread_rng();
let embed = rng.gen();
embed_data.push(embed);
}
let embed_column =
FieldColumn::new(collection.get_field(DEFAULT_VEC_FIELD).unwrap(), embed_data);
client
.insert(collection.name(), vec![embed_column], None)
.await?;
client.flush(collection.name()).await?;
let index_params = IndexParams::new(
"feature_index".to_owned(),
IndexType::IvfFlat,
milvus::index::MetricType::L2,
HashMap::from([("nlist".to_owned(), "32".to_owned())]),
);
client
.create_index(collection.name(), DEFAULT_VEC_FIELD, index_params)
.await?;
client
.load_collection(collection.name(), Some(LoadOptions::default()))
.await?;
let options = QueryOptions::default();
let result = client.query(collection.name(), "id > 0", &options).await?;
println!(
"result num: {}",
result.first().map(|c| c.len()).unwrap_or(0),
);
Ok(())
}