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.

196 lines
5.8KB

  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. /// - `explain=` : if true returns some information about the score.
  9. ///
  10. ///
  11. /// For instance, the following call should return the 20 most relevant
  12. /// hits for fulmicoton.
  13. ///
  14. /// http://localhost:3000/api/?q=fulmicoton&explain=false&nhits=20
  15. ///
  16. use clap::ArgMatches;
  17. use iron::mime::Mime;
  18. use iron::prelude::*;
  19. use iron::status;
  20. use iron::typemap::Key;
  21. use mount::Mount;
  22. use persistent::Read;
  23. use rustc_serialize::json::as_pretty_json;
  24. use std::convert::From;
  25. use std::error::Error;
  26. use std::fmt::{self, Debug};
  27. use std::path::Path;
  28. use std::path::PathBuf;
  29. use std::str::FromStr;
  30. use tantivy;
  31. use tantivy::collector;
  32. use tantivy::collector::CountCollector;
  33. use tantivy::collector::TopCollector;
  34. use tantivy::Document;
  35. use tantivy::Index;
  36. use tantivy::query::QueryParser;
  37. use tantivy::schema::Field;
  38. use tantivy::schema::FieldType;
  39. use tantivy::schema::NamedFieldDocument;
  40. use tantivy::schema::Schema;
  41. use tantivy::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(RustcEncodable)]
  51. struct Serp {
  52. q: String,
  53. num_hits: usize,
  54. hits: Vec<Hit>,
  55. timings: TimerTree,
  56. }
  57. #[derive(RustcEncodable)]
  58. struct Hit {
  59. doc: NamedFieldDocument,
  60. }
  61. struct IndexServer {
  62. index: Index,
  63. query_parser: QueryParser,
  64. schema: Schema,
  65. }
  66. impl IndexServer {
  67. fn load(path: &Path) -> IndexServer {
  68. let index = Index::open(path).unwrap();
  69. let schema = index.schema();
  70. let default_fields: Vec<Field> = schema
  71. .fields()
  72. .iter()
  73. .enumerate()
  74. .filter(
  75. |&(_, ref field_entry)| {
  76. match *field_entry.field_type() {
  77. FieldType::Str(_) => true,
  78. FieldType::U32(_) => false
  79. }
  80. }
  81. )
  82. .map(|(i, _)| Field(i as u8))
  83. .collect();
  84. let query_parser = QueryParser::new(schema.clone(), default_fields);
  85. IndexServer {
  86. index: index,
  87. query_parser: query_parser,
  88. schema: schema,
  89. }
  90. }
  91. fn create_hit(&self, doc: &Document) -> Hit {
  92. Hit {
  93. doc: self.schema.to_named_doc(&doc)
  94. }
  95. }
  96. fn search(&self, q: String, num_hits: usize, explain: bool) -> tantivy::Result<Serp> {
  97. let query = self.query_parser.parse_query(&q).unwrap();
  98. let searcher = self.index.searcher();
  99. let mut count_collector = CountCollector::default();
  100. let mut top_collector = TopCollector::with_limit(num_hits);
  101. let mut timer_tree = TimerTree::default();
  102. {
  103. let _search_timer = timer_tree.open("search");
  104. let mut chained_collector = collector::chain()
  105. .push(&mut top_collector)
  106. .push(&mut count_collector);
  107. try!(query.search(&searcher, &mut chained_collector));
  108. }
  109. let hits: Vec<Hit> = {
  110. let _fetching_timer = timer_tree.open("fetching docs");
  111. top_collector.docs()
  112. .iter()
  113. .map(|doc_address| {
  114. let doc: Document = searcher.doc(doc_address).unwrap();
  115. self.create_hit(&doc)
  116. })
  117. .collect()
  118. };
  119. Ok(Serp {
  120. q: q,
  121. num_hits: count_collector.count(),
  122. hits: hits,
  123. timings: timer_tree,
  124. })
  125. }
  126. }
  127. impl Key for IndexServer {
  128. type Value = IndexServer;
  129. }
  130. #[derive(Debug)]
  131. struct StringError(String);
  132. impl fmt::Display for StringError {
  133. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  134. Debug::fmt(self, f)
  135. }
  136. }
  137. impl Error for StringError {
  138. fn description(&self) -> &str { &*self.0 }
  139. }
  140. fn search(req: &mut Request) -> IronResult<Response> {
  141. let index_server = req.get::<Read<IndexServer>>().unwrap();
  142. req.get_ref::<UrlEncodedQuery>()
  143. .map_err(|_| IronError::new(StringError(String::from("Failed to decode error")), status::BadRequest))
  144. .and_then(|ref qs_map| {
  145. let num_hits: usize = qs_map
  146. .get("nhits")
  147. .and_then(|nhits_str| usize::from_str(&nhits_str[0]).ok())
  148. .unwrap_or(10);
  149. let explain: bool = qs_map
  150. .get("explain")
  151. .map(|s| &s[0] == &"true")
  152. .unwrap_or(false);
  153. let query = try!(qs_map
  154. .get("q")
  155. .ok_or_else(|| IronError::new(StringError(String::from("Parameter q is missing from the query")), status::BadRequest)))[0].clone();
  156. let serp = index_server.search(query, num_hits, explain).unwrap();
  157. let resp_json = as_pretty_json(&serp).indent(4);
  158. let content_type = "application/json".parse::<Mime>().unwrap();
  159. Ok(Response::with((content_type, status::Ok, format!("{}", resp_json))))
  160. })
  161. }
  162. fn run_serve(directory: PathBuf, host: &str) -> tantivy::Result<()> {
  163. let mut mount = Mount::new();
  164. let server = IndexServer::load(&directory);
  165. mount.mount("/api", search);
  166. let mut middleware = Chain::new(mount);
  167. middleware.link(Read::<IndexServer>::both(server));
  168. println!("listening on http://{}", host);
  169. Iron::new(middleware).http(host).unwrap();
  170. Ok(())
  171. }