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.

198 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. ///
  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::tokenizer::*;
  41. use tantivy::DocAddress;
  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. }
  56. #[derive(Serialize)]
  57. struct Hit {
  58. doc: NamedFieldDocument,
  59. id: u32,
  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_in_dir(path).unwrap();
  69. index.tokenizers()
  70. .register("commoncrawl", SimpleTokenizer
  71. .filter(RemoveLongFilter::limit(40))
  72. .filter(LowerCaser)
  73. .filter(AlphaNumOnlyFilter)
  74. .filter(Stemmer::new())
  75. );
  76. let schema = index.schema();
  77. let default_fields: Vec<Field> = schema
  78. .fields()
  79. .iter()
  80. .enumerate()
  81. .filter(
  82. |&(_, ref field_entry)| {
  83. match *field_entry.field_type() {
  84. FieldType::Str(ref text_field_options) => {
  85. text_field_options.get_indexing_options().is_some()
  86. },
  87. _ => false
  88. }
  89. }
  90. )
  91. .map(|(i, _)| Field(i as u32))
  92. .collect();
  93. let query_parser = QueryParser::new(schema.clone(), default_fields, index.tokenizers().clone());
  94. IndexServer {
  95. index,
  96. query_parser,
  97. schema,
  98. }
  99. }
  100. fn create_hit(&self, doc: &Document, doc_address: &DocAddress) -> Hit {
  101. Hit {
  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.query_parser.parse_query(&q).expect("Parsing the query failed");
  108. let searcher = self.index.searcher();
  109. let mut count_collector = CountCollector::default();
  110. let mut top_collector = TopCollector::with_limit(num_hits);
  111. {
  112. let mut chained_collector = collector::chain()
  113. .push(&mut top_collector)
  114. .push(&mut count_collector);
  115. query.search(&searcher, &mut chained_collector)?;
  116. }
  117. let hits: Vec<Hit> = {
  118. top_collector.docs()
  119. .iter()
  120. .map(|doc_address| {
  121. let doc: Document = searcher.doc(doc_address).unwrap();
  122. self.create_hit(&doc, doc_address)
  123. })
  124. .collect()
  125. };
  126. Ok(Serp {
  127. q,
  128. num_hits: count_collector.count(),
  129. hits,
  130. })
  131. }
  132. }
  133. impl Key for IndexServer {
  134. type Value = IndexServer;
  135. }
  136. #[derive(Debug)]
  137. struct StringError(String);
  138. impl fmt::Display for StringError {
  139. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  140. Debug::fmt(self, f)
  141. }
  142. }
  143. impl Error for StringError {
  144. fn description(&self) -> &str { &*self.0 }
  145. }
  146. fn search(req: &mut Request) -> IronResult<Response> {
  147. let index_server = req.get::<Read<IndexServer>>().unwrap();
  148. req.get_ref::<UrlEncodedQuery>()
  149. .map_err(|_| IronError::new(StringError(String::from("Failed to decode error")), status::BadRequest))
  150. .and_then(|ref qs_map| {
  151. let num_hits: usize = qs_map
  152. .get("nhits")
  153. .and_then(|nhits_str| usize::from_str(&nhits_str[0]).ok())
  154. .unwrap_or(10);
  155. let query = qs_map
  156. .get("q")
  157. .ok_or_else(|| IronError::new(StringError(String::from("Parameter q is missing from the query")), status::BadRequest))?[0].clone();
  158. let serp = index_server.search(query, num_hits).unwrap();
  159. let resp_json = serde_json::to_string_pretty(&serp).unwrap();
  160. let content_type = "application/json".parse::<Mime>().unwrap();
  161. Ok(Response::with((content_type, status::Ok, format!("{}", resp_json))))
  162. })
  163. }
  164. fn run_serve(directory: PathBuf, host: &str) -> tantivy::Result<()> {
  165. let mut mount = Mount::new();
  166. let server = IndexServer::load(&directory);
  167. mount.mount("/api", search);
  168. let mut middleware = Chain::new(mount);
  169. middleware.link(Read::<IndexServer>::both(server));
  170. println!("listening on http://{}", host);
  171. Iron::new(middleware).http(host).unwrap();
  172. Ok(())
  173. }