MeiliSearch/examples/query-database.rs

74 lines
1.9 KiB
Rust
Raw Normal View History

2018-12-10 15:13:25 +01:00
use std::io::{self, Write};
use std::path::PathBuf;
use std::error::Error;
use serde_derive::{Serialize, Deserialize};
use structopt::StructOpt;
use meilidb::database::Database;
#[derive(Debug, StructOpt)]
pub struct Opt {
/// The destination where the database must be created
#[structopt(parse(from_os_str))]
pub database_path: PathBuf,
2018-12-10 15:30:28 +01:00
/// The number of returned results
#[structopt(short = "n", long = "number-results", default_value = "10")]
pub number_results: usize,
2018-12-10 15:13:25 +01:00
}
#[derive(Debug, Serialize, Deserialize)]
#[allow(non_snake_case)]
struct Document {
skuId: String,
2018-12-10 15:30:28 +01:00
productGroup: String,
2018-12-10 15:13:25 +01:00
fr_FR_commercialName: String,
en_GB_commercialName: String,
maketingColorInternalName: String,
materialInternalName: String,
fr_FR_description: String,
en_GB_description: String,
}
fn main() -> Result<(), Box<Error>> {
let opt = Opt::from_args();
let (elapsed, result) = elapsed::measure_time(|| Database::open(&opt.database_path));
let database = result?;
2018-12-10 15:30:28 +01:00
println!("database prepared for you in {}", elapsed);
2018-12-10 15:13:25 +01:00
let mut buffer = String::new();
let input = io::stdin();
loop {
2018-12-10 15:30:28 +01:00
print!("Searching for: ");
2018-12-10 15:13:25 +01:00
io::stdout().flush()?;
if input.read_line(&mut buffer)? == 0 { break }
let view = database.view();
let (elapsed, documents) = elapsed::measure_time(|| {
let builder = view.query_builder().unwrap();
2018-12-10 15:30:28 +01:00
builder.query(&buffer, opt.number_results)
2018-12-10 15:13:25 +01:00
});
let mut full_documents = Vec::with_capacity(documents.len());
for document in documents {
match view.retrieve_document::<Document>(document.id) {
Ok(document) => full_documents.push(document),
Err(e) => eprintln!("{}", e),
}
}
println!("{:#?}", full_documents);
2018-12-10 15:30:28 +01:00
println!("Found {} results in {}", full_documents.len(), elapsed);
2018-12-10 15:13:25 +01:00
buffer.clear();
}
Ok(())
}