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.

204 lines
6.1KB

  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 serde_json;
  20. use iron::typemap::Key;
  21. use mount::Mount;
  22. use persistent::Read;
  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;
  31. use tantivy::collector::CountCollector;
  32. use tantivy::collector::TopCollector;
  33. use tantivy::Document;
  34. use tantivy::Index;
  35. use tantivy::query::QueryParser;
  36. use tantivy::schema::Field;
  37. use tantivy::schema::FieldType;
  38. use tantivy::schema::NamedFieldDocument;
  39. use tantivy::schema::Schema;
  40. use tantivy::TimerTree;
  41. use tantivy::tokenizer::*;
  42. use tantivy::DocAddress;
  43. use urlencoded::UrlEncodedQuery;
  44. pub fn run_serve_cli(matches: &ArgMatches) -> Result<(), String> {
  45. let index_directory = PathBuf::from(matches.value_of("index").unwrap());
  46. let port = value_t!(matches, "port", u16).unwrap_or(3000u16);
  47. let host_str = matches.value_of("host").unwrap_or("localhost");
  48. let host = format!("{}:{}", host_str, port);
  49. run_serve(index_directory, &host).map_err(|e| format!("{:?}", e))
  50. }
  51. #[derive(Serialize)]
  52. struct Serp {
  53. q: String,
  54. num_hits: usize,
  55. hits: Vec<Hit>,
  56. timings: TimerTree,
  57. }
  58. #[derive(Serialize)]
  59. struct Hit {
  60. doc: NamedFieldDocument,
  61. id: u32,
  62. }
  63. struct IndexServer {
  64. index: Index,
  65. query_parser: QueryParser,
  66. schema: Schema,
  67. }
  68. impl IndexServer {
  69. fn load(path: &Path) -> IndexServer {
  70. let index = Index::open(path).unwrap();
  71. index.tokenizers()
  72. .register("commoncrawl", SimpleTokenizer
  73. .filter(RemoveLongFilter::limit(40))
  74. .filter(LowerCaser)
  75. .filter(AlphaNumOnlyFilter)
  76. .filter(Stemmer::new())
  77. );
  78. let schema = index.schema();
  79. let default_fields: Vec<Field> = schema
  80. .fields()
  81. .iter()
  82. .enumerate()
  83. .filter(
  84. |&(_, ref field_entry)| {
  85. match *field_entry.field_type() {
  86. FieldType::Str(ref text_field_options) => {
  87. text_field_options.get_indexing_options().is_some()
  88. },
  89. _ => false
  90. }
  91. }
  92. )
  93. .map(|(i, _)| Field(i as u32))
  94. .collect();
  95. let query_parser = QueryParser::new(schema.clone(), default_fields, index.tokenizers().clone());
  96. IndexServer {
  97. index,
  98. query_parser,
  99. schema,
  100. }
  101. }
  102. fn create_hit(&self, doc: &Document, doc_address: &DocAddress) -> Hit {
  103. Hit {
  104. doc: self.schema.to_named_doc(&doc),
  105. id: doc_address.doc(),
  106. }
  107. }
  108. fn search(&self, q: String, num_hits: usize) -> tantivy::Result<Serp> {
  109. let query = self.query_parser.parse_query(&q).expect("Parsing the query failed");
  110. let searcher = self.index.searcher();
  111. let mut count_collector = CountCollector::default();
  112. let mut top_collector = TopCollector::with_limit(num_hits);
  113. let mut timer_tree = TimerTree::default();
  114. {
  115. let _search_timer = timer_tree.open("search");
  116. let mut chained_collector = collector::chain()
  117. .push(&mut top_collector)
  118. .push(&mut count_collector);
  119. query.search(&searcher, &mut chained_collector)?;
  120. }
  121. let hits: Vec<Hit> = {
  122. let _fetching_timer = timer_tree.open("fetching docs");
  123. top_collector.docs()
  124. .iter()
  125. .map(|doc_address| {
  126. let doc: Document = searcher.doc(doc_address).unwrap();
  127. self.create_hit(&doc, doc_address)
  128. })
  129. .collect()
  130. };
  131. Ok(Serp {
  132. q,
  133. num_hits: count_collector.count(),
  134. hits,
  135. timings: timer_tree,
  136. })
  137. }
  138. }
  139. impl Key for IndexServer {
  140. type Value = IndexServer;
  141. }
  142. #[derive(Debug)]
  143. struct StringError(String);
  144. impl fmt::Display for StringError {
  145. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  146. Debug::fmt(self, f)
  147. }
  148. }
  149. impl Error for StringError {
  150. fn description(&self) -> &str { &*self.0 }
  151. }
  152. fn search(req: &mut Request) -> IronResult<Response> {
  153. let index_server = req.get::<Read<IndexServer>>().unwrap();
  154. req.get_ref::<UrlEncodedQuery>()
  155. .map_err(|_| IronError::new(StringError(String::from("Failed to decode error")), status::BadRequest))
  156. .and_then(|ref qs_map| {
  157. let num_hits: usize = qs_map
  158. .get("nhits")
  159. .and_then(|nhits_str| usize::from_str(&nhits_str[0]).ok())
  160. .unwrap_or(10);
  161. let query = qs_map
  162. .get("q")
  163. .ok_or_else(|| IronError::new(StringError(String::from("Parameter q is missing from the query")), status::BadRequest))?[0].clone();
  164. let serp = index_server.search(query, num_hits).unwrap();
  165. let resp_json = serde_json::to_string_pretty(&serp).unwrap();
  166. let content_type = "application/json".parse::<Mime>().unwrap();
  167. Ok(Response::with((content_type, status::Ok, format!("{}", resp_json))))
  168. })
  169. }
  170. fn run_serve(directory: PathBuf, host: &str) -> tantivy::Result<()> {
  171. let mut mount = Mount::new();
  172. let server = IndexServer::load(&directory);
  173. mount.mount("/api", search);
  174. let mut middleware = Chain::new(mount);
  175. middleware.link(Read::<IndexServer>::both(server));
  176. println!("listening on http://{}", host);
  177. Iron::new(middleware).http(host).unwrap();
  178. Ok(())
  179. }