|
| 1 | +use std::fs::File; |
| 2 | +use std::io::{stdin, Cursor, Read}; |
| 3 | +use std::path::PathBuf; |
| 4 | +use std::str::FromStr; |
| 5 | + |
| 6 | +use byte_unit::Byte; |
| 7 | +use eyre::Result; |
| 8 | +use indicatif::{MultiProgress, ProgressBar, ProgressStyle}; |
| 9 | +use milli::update::UpdateIndexingStep::{ |
| 10 | + ComputeIdsAndMergeDocuments, IndexDocuments, MergeDataIntoFinalDatabase, RemapDocumentAddition, |
| 11 | +}; |
| 12 | +use serde_json::{Map, Value}; |
| 13 | +use structopt::StructOpt; |
| 14 | + |
| 15 | +#[cfg(target_os = "linux")] |
| 16 | +#[global_allocator] |
| 17 | +static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc; |
| 18 | + |
| 19 | +#[derive(Debug, StructOpt)] |
| 20 | +#[structopt(name = "Milli CLI", about = "A simple CLI to manipulate a milli index.")] |
| 21 | +struct Cli { |
| 22 | + #[structopt(short, long)] |
| 23 | + index_path: PathBuf, |
| 24 | + #[structopt(short = "s", long, default_value = "100GiB")] |
| 25 | + index_size: Byte, |
| 26 | + /// Verbose mode (-v, -vv, -vvv, etc.) |
| 27 | + #[structopt(short, long, parse(from_occurrences))] |
| 28 | + verbose: usize, |
| 29 | + #[structopt(subcommand)] |
| 30 | + subcommand: Command, |
| 31 | +} |
| 32 | + |
| 33 | +#[derive(Debug, StructOpt)] |
| 34 | +enum Command { |
| 35 | + DocumentAddition(DocumentAddition), |
| 36 | + Search(Search), |
| 37 | + SettingsUpdate(SettingsUpdate), |
| 38 | +} |
| 39 | + |
| 40 | +fn setup(opt: &Cli) -> Result<()> { |
| 41 | + color_eyre::install()?; |
| 42 | + stderrlog::new() |
| 43 | + .verbosity(opt.verbose) |
| 44 | + .show_level(false) |
| 45 | + .timestamp(stderrlog::Timestamp::Off) |
| 46 | + .init()?; |
| 47 | + Ok(()) |
| 48 | +} |
| 49 | + |
| 50 | +fn main() -> Result<()> { |
| 51 | + let command = Cli::from_args(); |
| 52 | + |
| 53 | + setup(&command)?; |
| 54 | + |
| 55 | + let mut options = heed::EnvOpenOptions::new(); |
| 56 | + options.map_size(command.index_size.get_bytes() as usize); |
| 57 | + let index = milli::Index::new(options, command.index_path)?; |
| 58 | + |
| 59 | + match command.subcommand { |
| 60 | + Command::DocumentAddition(addition) => addition.perform(index)?, |
| 61 | + Command::Search(search) => search.perform(index)?, |
| 62 | + Command::SettingsUpdate(update) => update.perform(index)?, |
| 63 | + } |
| 64 | + |
| 65 | + Ok(()) |
| 66 | +} |
| 67 | + |
| 68 | +#[derive(Debug)] |
| 69 | +enum DocumentAdditionFormat { |
| 70 | + Csv, |
| 71 | + Json, |
| 72 | + Jsonl, |
| 73 | +} |
| 74 | + |
| 75 | +impl FromStr for DocumentAdditionFormat { |
| 76 | + type Err = eyre::Error; |
| 77 | + |
| 78 | + fn from_str(s: &str) -> Result<Self, Self::Err> { |
| 79 | + match s { |
| 80 | + "csv" => Ok(Self::Csv), |
| 81 | + "jsonl" => Ok(Self::Jsonl), |
| 82 | + "json" => Ok(Self::Json), |
| 83 | + other => eyre::bail!("invalid format: {}", other), |
| 84 | + } |
| 85 | + } |
| 86 | +} |
| 87 | + |
| 88 | +#[derive(Debug, StructOpt)] |
| 89 | +struct DocumentAddition { |
| 90 | + #[structopt(short, long, default_value = "json", possible_values = &["csv", "jsonl", "json"])] |
| 91 | + format: DocumentAdditionFormat, |
| 92 | + /// Path to the update file, if not present, will read from stdin. |
| 93 | + #[structopt(short, long)] |
| 94 | + path: Option<PathBuf>, |
| 95 | + /// Whether to generate missing document ids. |
| 96 | + #[structopt(short, long)] |
| 97 | + autogen_docids: bool, |
| 98 | + /// Whether to update or replace the documents if they already exist. |
| 99 | + #[structopt(short, long)] |
| 100 | + update_documents: bool, |
| 101 | +} |
| 102 | + |
| 103 | +impl DocumentAddition { |
| 104 | + fn perform(&self, index: milli::Index) -> Result<()> { |
| 105 | + let reader: Box<dyn Read> = match self.path { |
| 106 | + Some(ref path) => { |
| 107 | + let file = File::open(path)?; |
| 108 | + Box::new(file) |
| 109 | + } |
| 110 | + None => Box::new(stdin()), |
| 111 | + }; |
| 112 | + |
| 113 | + println!("parsing documents..."); |
| 114 | + |
| 115 | + let documents = match self.format { |
| 116 | + DocumentAdditionFormat::Csv => documents_from_csv(reader)?, |
| 117 | + DocumentAdditionFormat::Json => documents_from_json(reader)?, |
| 118 | + DocumentAdditionFormat::Jsonl => documents_from_jsonl(reader)?, |
| 119 | + }; |
| 120 | + |
| 121 | + let reader = milli::documents::DocumentBatchReader::from_reader(Cursor::new(documents))?; |
| 122 | + |
| 123 | + println!("Adding {} documents to the index.", reader.len()); |
| 124 | + |
| 125 | + let mut txn = index.env.write_txn()?; |
| 126 | + let mut addition = milli::update::IndexDocuments::new(&mut txn, &index, 0); |
| 127 | + |
| 128 | + if self.update_documents { |
| 129 | + addition.index_documents_method(milli::update::IndexDocumentsMethod::UpdateDocuments); |
| 130 | + } |
| 131 | + |
| 132 | + addition.log_every_n(100); |
| 133 | + |
| 134 | + if self.autogen_docids { |
| 135 | + addition.enable_autogenerate_docids() |
| 136 | + } |
| 137 | + |
| 138 | + let mut bars = Vec::new(); |
| 139 | + let progesses = MultiProgress::new(); |
| 140 | + for _ in 0..4 { |
| 141 | + let bar = ProgressBar::hidden(); |
| 142 | + let bar = progesses.add(bar); |
| 143 | + bars.push(bar); |
| 144 | + } |
| 145 | + |
| 146 | + std::thread::spawn(move || { |
| 147 | + progesses.join().unwrap(); |
| 148 | + }); |
| 149 | + |
| 150 | + let result = addition.execute(reader, |step, _| indexing_callback(step, &bars))?; |
| 151 | + |
| 152 | + txn.commit()?; |
| 153 | + |
| 154 | + println!("{:?}", result); |
| 155 | + Ok(()) |
| 156 | + } |
| 157 | +} |
| 158 | + |
| 159 | +fn indexing_callback(step: milli::update::UpdateIndexingStep, bars: &[ProgressBar]) { |
| 160 | + let step_index = step.step(); |
| 161 | + let bar = &bars[step_index]; |
| 162 | + if step_index > 0 { |
| 163 | + let prev = &bars[step_index - 1]; |
| 164 | + if !prev.is_finished() { |
| 165 | + prev.disable_steady_tick(); |
| 166 | + prev.finish_at_current_pos(); |
| 167 | + } |
| 168 | + } |
| 169 | + |
| 170 | + let style = ProgressStyle::default_bar() |
| 171 | + .template("[eta: {eta_precise}] {bar:40.cyan/blue} {pos:>7}/{len:7} {msg}") |
| 172 | + .progress_chars("##-"); |
| 173 | + |
| 174 | + match step { |
| 175 | + RemapDocumentAddition { documents_seen } => { |
| 176 | + bar.set_style(ProgressStyle::default_spinner()); |
| 177 | + bar.set_message(format!("remaped {} documents so far.", documents_seen)); |
| 178 | + } |
| 179 | + ComputeIdsAndMergeDocuments { documents_seen, total_documents } => { |
| 180 | + bar.set_style(style); |
| 181 | + bar.set_length(total_documents as u64); |
| 182 | + bar.set_message("Merging documents..."); |
| 183 | + bar.set_position(documents_seen as u64); |
| 184 | + } |
| 185 | + IndexDocuments { documents_seen, total_documents } => { |
| 186 | + bar.set_style(style); |
| 187 | + bar.set_length(total_documents as u64); |
| 188 | + bar.set_message("Indexing documents..."); |
| 189 | + bar.set_position(documents_seen as u64); |
| 190 | + } |
| 191 | + MergeDataIntoFinalDatabase { databases_seen, total_databases } => { |
| 192 | + bar.set_style(style); |
| 193 | + bar.set_length(total_databases as u64); |
| 194 | + bar.set_message("Merging databases..."); |
| 195 | + bar.set_position(databases_seen as u64); |
| 196 | + } |
| 197 | + } |
| 198 | + bar.enable_steady_tick(200); |
| 199 | +} |
| 200 | + |
| 201 | +fn documents_from_jsonl(reader: impl Read) -> Result<Vec<u8>> { |
| 202 | + let mut writer = Cursor::new(Vec::new()); |
| 203 | + let mut documents = milli::documents::DocumentBatchBuilder::new(&mut writer)?; |
| 204 | + |
| 205 | + let values = serde_json::Deserializer::from_reader(reader) |
| 206 | + .into_iter::<serde_json::Map<String, serde_json::Value>>(); |
| 207 | + for document in values { |
| 208 | + let document = document?; |
| 209 | + documents.add_documents(document)?; |
| 210 | + } |
| 211 | + documents.finish()?; |
| 212 | + |
| 213 | + Ok(writer.into_inner()) |
| 214 | +} |
| 215 | + |
| 216 | +fn documents_from_json(reader: impl Read) -> Result<Vec<u8>> { |
| 217 | + let mut writer = Cursor::new(Vec::new()); |
| 218 | + let mut documents = milli::documents::DocumentBatchBuilder::new(&mut writer)?; |
| 219 | + |
| 220 | + let json: serde_json::Value = serde_json::from_reader(reader)?; |
| 221 | + documents.add_documents(json)?; |
| 222 | + documents.finish()?; |
| 223 | + |
| 224 | + Ok(writer.into_inner()) |
| 225 | +} |
| 226 | + |
| 227 | +fn documents_from_csv(reader: impl Read) -> Result<Vec<u8>> { |
| 228 | + let mut writer = Cursor::new(Vec::new()); |
| 229 | + let mut documents = milli::documents::DocumentBatchBuilder::new(&mut writer)?; |
| 230 | + |
| 231 | + let mut records = csv::Reader::from_reader(reader); |
| 232 | + let iter = records.deserialize::<Map<String, Value>>(); |
| 233 | + |
| 234 | + for doc in iter { |
| 235 | + let doc = doc?; |
| 236 | + documents.add_documents(doc)?; |
| 237 | + } |
| 238 | + |
| 239 | + documents.finish()?; |
| 240 | + |
| 241 | + Ok(writer.into_inner()) |
| 242 | +} |
| 243 | + |
| 244 | +#[derive(Debug, StructOpt)] |
| 245 | +struct Search { |
| 246 | + query: Option<String>, |
| 247 | + #[structopt(short, long)] |
| 248 | + filter: Option<String>, |
| 249 | + #[structopt(short, long)] |
| 250 | + offset: Option<usize>, |
| 251 | + #[structopt(short, long)] |
| 252 | + limit: Option<usize>, |
| 253 | +} |
| 254 | + |
| 255 | +impl Search { |
| 256 | + fn perform(&self, index: milli::Index) -> Result<()> { |
| 257 | + let txn = index.env.read_txn()?; |
| 258 | + let mut search = index.search(&txn); |
| 259 | + |
| 260 | + if let Some(ref query) = self.query { |
| 261 | + search.query(query); |
| 262 | + } |
| 263 | + |
| 264 | + if let Some(ref filter) = self.filter { |
| 265 | + let condition = milli::FilterCondition::from_str(&txn, &index, filter)?; |
| 266 | + search.filter(condition); |
| 267 | + } |
| 268 | + |
| 269 | + if let Some(offset) = self.offset { |
| 270 | + search.offset(offset); |
| 271 | + } |
| 272 | + |
| 273 | + if let Some(limit) = self.limit { |
| 274 | + search.limit(limit); |
| 275 | + } |
| 276 | + |
| 277 | + let result = search.execute()?; |
| 278 | + |
| 279 | + let fields_ids_map = index.fields_ids_map(&txn)?; |
| 280 | + let displayed_fields = |
| 281 | + index.displayed_fields_ids(&txn)?.unwrap_or_else(|| fields_ids_map.ids().collect()); |
| 282 | + let documents = index.documents(&txn, result.documents_ids)?; |
| 283 | + let mut jsons = Vec::new(); |
| 284 | + for (_, obkv) in documents { |
| 285 | + let json = milli::obkv_to_json(&displayed_fields, &fields_ids_map, obkv)?; |
| 286 | + jsons.push(json); |
| 287 | + } |
| 288 | + |
| 289 | + let hits = serde_json::to_string_pretty(&jsons)?; |
| 290 | + |
| 291 | + println!("{}", hits); |
| 292 | + |
| 293 | + Ok(()) |
| 294 | + } |
| 295 | +} |
| 296 | + |
| 297 | +#[derive(Debug, StructOpt)] |
| 298 | +struct SettingsUpdate { |
| 299 | + #[structopt(short, long)] |
| 300 | + filterable_attributes: Option<Vec<String>>, |
| 301 | +} |
| 302 | + |
| 303 | +impl SettingsUpdate { |
| 304 | + fn perform(&self, index: milli::Index) -> Result<()> { |
| 305 | + let mut txn = index.env.write_txn()?; |
| 306 | + |
| 307 | + let mut update = milli::update::Settings::new(&mut txn, &index, 0); |
| 308 | + update.log_every_n(100); |
| 309 | + |
| 310 | + if let Some(ref filterable_attributes) = self.filterable_attributes { |
| 311 | + if !filterable_attributes.is_empty() { |
| 312 | + update.set_filterable_fields(filterable_attributes.iter().cloned().collect()); |
| 313 | + } else { |
| 314 | + update.reset_filterable_fields(); |
| 315 | + } |
| 316 | + } |
| 317 | + |
| 318 | + let mut bars = Vec::new(); |
| 319 | + let progesses = MultiProgress::new(); |
| 320 | + for _ in 0..4 { |
| 321 | + let bar = ProgressBar::hidden(); |
| 322 | + let bar = progesses.add(bar); |
| 323 | + bars.push(bar); |
| 324 | + } |
| 325 | + |
| 326 | + std::thread::spawn(move || { |
| 327 | + progesses.join().unwrap(); |
| 328 | + }); |
| 329 | + |
| 330 | + update.execute(|step, _| indexing_callback(step, &bars))?; |
| 331 | + |
| 332 | + txn.commit()?; |
| 333 | + Ok(()) |
| 334 | + } |
| 335 | +} |
0 commit comments