meilisearch/src/subcommand/search.rs

86 lines
2.6 KiB
Rust
Raw Normal View History

use std::collections::HashMap;
use std::io::{self, BufRead};
use std::iter::once;
2020-05-31 22:09:34 +08:00
use std::path::PathBuf;
use std::time::Instant;
use anyhow::Context;
2020-05-31 23:48:13 +08:00
use heed::EnvOpenOptions;
2020-07-12 16:55:09 +08:00
use log::debug;
use structopt::StructOpt;
2020-05-31 22:09:34 +08:00
use crate::Index;
2020-05-31 22:09:34 +08:00
#[derive(Debug, StructOpt)]
/// A simple search helper binary for the milli project.
pub struct Opt {
2020-05-31 22:09:34 +08:00
/// The database path where the database is located.
/// It is created if it doesn't already exist.
#[structopt(long = "db", parse(from_os_str))]
database: PathBuf,
/// The maximum size the database can take on disk. It is recommended to specify
/// the whole disk space (value must be a multiple of a page size).
#[structopt(long = "db-size", default_value = "107374182400")] // 100 GB
database_size: usize,
/// Verbose mode (-v, -vv, -vvv, etc.)
#[structopt(short, long, parse(from_occurrences))]
verbose: usize,
2020-05-31 22:09:34 +08:00
/// The query string to search for (doesn't support prefix search yet).
query: Option<String>,
2020-05-31 22:09:34 +08:00
}
pub fn run(opt: Opt) -> anyhow::Result<()> {
stderrlog::new()
.verbosity(opt.verbose)
.show_level(false)
.timestamp(stderrlog::Timestamp::Off)
.init()?;
2020-05-31 22:09:34 +08:00
std::fs::create_dir_all(&opt.database)?;
let env = EnvOpenOptions::new()
.map_size(opt.database_size)
.max_dbs(10)
2020-08-07 19:11:31 +08:00
.open(&opt.database)?;
2020-05-31 22:09:34 +08:00
2020-08-07 19:11:31 +08:00
// Open the LMDB database.
let index = Index::new(&env)?;
2020-05-31 22:09:34 +08:00
let rtxn = env.read_txn()?;
let stdin = io::stdin();
let lines = match opt.query {
Some(query) => Box::new(once(Ok(query.to_string()))),
None => Box::new(stdin.lock().lines()) as Box<dyn Iterator<Item = _>>,
};
for result in lines {
let before = Instant::now();
2020-05-31 22:09:34 +08:00
let query = result?;
2020-08-13 20:15:05 +08:00
let result = index.search(&rtxn).query(query).execute().unwrap();
let mut stdout = io::stdout();
let fields_ids_map = index.fields_ids_map(&rtxn)?.unwrap_or_default();
let documents = index.documents(&rtxn, result.documents_ids.iter().cloned())?;
for (_id, record) in documents {
let document: anyhow::Result<HashMap<_, _>> = record.iter()
.map(|(k, v)| {
let key = fields_ids_map.name(k).context("field id not found")?;
let val = std::str::from_utf8(v)?;
Ok((key, val))
})
.collect();
let document = document?;
serde_json::to_writer(&mut stdout, &document)?;
2020-05-31 22:09:34 +08:00
}
2020-08-13 20:15:05 +08:00
debug!("Took {:.02?} to find {} documents", before.elapsed(), result.documents_ids.len());
}
2020-05-31 22:09:34 +08:00
Ok(())
}