You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

207 lines
6.0KB

  1. /// This tantivy command starts a http server (by default on port 3000)
  2. ///
  3. /// Currently the only entrypoint is /api/
  4. /// and it takes the following query string argument
  5. ///
  6. /// - `q=` : your query
  7. /// - `nhits`: the number of hits that should be returned. (default to 10)
  8. ///
  9. ///
  10. /// For instance, the following call should return the 20 most relevant
  11. /// hits for fulmicoton.
  12. ///
  13. /// http://localhost:3000/api/?q=fulmicoton&&nhits=20
  14. ///
  15. use clap::ArgMatches;
  16. use iron::mime::Mime;
  17. use iron::prelude::*;
  18. use iron::status;
  19. use iron::typemap::Key;
  20. use mount::Mount;
  21. use persistent::Read;
  22. use serde_json;
  23. use std::convert::From;
  24. use std::error::Error;
  25. use std::fmt::{self, Debug};
  26. use std::path::Path;
  27. use std::path::PathBuf;
  28. use std::str::FromStr;
  29. use tantivy;
  30. use tantivy::collector::{Count, TopDocs};
  31. use tantivy::query::QueryParser;
  32. use tantivy::schema::Field;
  33. use tantivy::schema::FieldType;
  34. use tantivy::schema::NamedFieldDocument;
  35. use tantivy::schema::Schema;
  36. use tantivy::tokenizer::*;
  37. use tantivy::{DocAddress, Score};
  38. use tantivy::Document;
  39. use tantivy::Index;
  40. use tantivy::IndexReader;
  41. use crate::timer::TimerTree;
  42. use urlencoded::UrlEncodedQuery;
  43. pub fn run_serve_cli(matches: &ArgMatches) -> Result<(), String> {
  44. let index_directory = PathBuf::from(matches.value_of("index").unwrap());
  45. let port = value_t!(matches, "port", u16).unwrap_or(3000u16);
  46. let host_str = matches.value_of("host").unwrap_or("localhost");
  47. let host = format!("{}:{}", host_str, port);
  48. run_serve(index_directory, &host).map_err(|e| format!("{:?}", e))
  49. }
  50. #[derive(Serialize)]
  51. struct Serp {
  52. q: String,
  53. num_hits: usize,
  54. hits: Vec<Hit>,
  55. timings: TimerTree,
  56. }
  57. #[derive(Serialize)]
  58. struct Hit {
  59. score: Score,
  60. doc: NamedFieldDocument,
  61. id: u32,
  62. }
  63. struct IndexServer {
  64. reader: IndexReader,
  65. query_parser: QueryParser,
  66. schema: Schema,
  67. }
  68. impl IndexServer {
  69. fn load(path: &Path) -> IndexServer {
  70. let index = Index::open_in_dir(path).unwrap();
  71. index.tokenizers().register(
  72. "commoncrawl",
  73. TextAnalyzer::from(SimpleTokenizer)
  74. .filter(RemoveLongFilter::limit(40))
  75. .filter(LowerCaser)
  76. .filter(AlphaNumOnlyFilter)
  77. .filter(Stemmer::new(Language::English)),
  78. );
  79. let schema = index.schema();
  80. let default_fields: Vec<Field> = schema
  81. .fields()
  82. .filter(|&(_, ref field_entry)| match *field_entry.field_type() {
  83. FieldType::Str(ref text_field_options) => {
  84. text_field_options.get_indexing_options().is_some()
  85. }
  86. _ => false,
  87. })
  88. .map(|(field, _)| field)
  89. .collect();
  90. let query_parser =
  91. QueryParser::new(schema.clone(), default_fields, index.tokenizers().clone());
  92. let reader = index.reader().unwrap();
  93. IndexServer {
  94. reader,
  95. query_parser,
  96. schema,
  97. }
  98. }
  99. fn create_hit(&self, score: Score, doc: &Document, doc_address: DocAddress) -> Hit {
  100. Hit {
  101. score,
  102. doc: self.schema.to_named_doc(&doc),
  103. id: doc_address.doc(),
  104. }
  105. }
  106. fn search(&self, q: String, num_hits: usize) -> tantivy::Result<Serp> {
  107. let query = self
  108. .query_parser
  109. .parse_query(&q)
  110. .expect("Parsing the query failed");
  111. let searcher = self.reader.searcher();
  112. let mut timer_tree = TimerTree::default();
  113. let (top_docs, num_hits) = {
  114. let _search_timer = timer_tree.open("search");
  115. searcher.search(&query, &(TopDocs::with_limit(num_hits), Count))?
  116. };
  117. let hits: Vec<Hit> = {
  118. let _fetching_timer = timer_tree.open("fetching docs");
  119. top_docs
  120. .iter()
  121. .map(|(score, doc_address)| {
  122. let doc: Document = searcher.doc(*doc_address).unwrap();
  123. self.create_hit(*score, &doc, *doc_address)
  124. })
  125. .collect()
  126. };
  127. Ok(Serp {
  128. q,
  129. num_hits,
  130. hits,
  131. timings: timer_tree,
  132. })
  133. }
  134. }
  135. impl Key for IndexServer {
  136. type Value = IndexServer;
  137. }
  138. #[derive(Debug)]
  139. struct StringError(String);
  140. impl fmt::Display for StringError {
  141. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  142. Debug::fmt(self, f)
  143. }
  144. }
  145. impl Error for StringError {
  146. fn description(&self) -> &str {
  147. &*self.0
  148. }
  149. }
  150. fn search(req: &mut Request) -> IronResult<Response> {
  151. let index_server = req.get::<Read<IndexServer>>().unwrap();
  152. req.get_ref::<UrlEncodedQuery>()
  153. .map_err(|_| {
  154. IronError::new(
  155. StringError(String::from("Failed to decode error")),
  156. status::BadRequest,
  157. )
  158. })
  159. .and_then(|ref qs_map| {
  160. let num_hits: usize = qs_map
  161. .get("nhits")
  162. .and_then(|nhits_str| usize::from_str(&nhits_str[0]).ok())
  163. .unwrap_or(10);
  164. let query = qs_map.get("q").ok_or_else(|| {
  165. IronError::new(
  166. StringError(String::from("Parameter q is missing from the query")),
  167. status::BadRequest,
  168. )
  169. })?[0]
  170. .clone();
  171. let serp = index_server.search(query, num_hits).unwrap();
  172. let resp_json = serde_json::to_string_pretty(&serp).unwrap();
  173. let content_type = "application/json".parse::<Mime>().unwrap();
  174. Ok(Response::with((
  175. content_type,
  176. status::Ok,
  177. format!("{}", resp_json),
  178. )))
  179. })
  180. }
  181. fn run_serve(directory: PathBuf, host: &str) -> tantivy::Result<()> {
  182. let mut mount = Mount::new();
  183. let server = IndexServer::load(&directory);
  184. mount.mount("/api", search);
  185. let mut middleware = Chain::new(mount);
  186. middleware.link(Read::<IndexServer>::both(server));
  187. println!("listening on http://{}", host);
  188. Iron::new(middleware).http(host).unwrap();
  189. Ok(())
  190. }