|
| 1 | +use async_trait::async_trait; |
| 2 | +use meilisearch_sdk::errors::Error; |
| 3 | +use meilisearch_sdk::request::{parse_response, HttpClient, Method}; |
| 4 | +use meilisearch_sdk::{client::*, settings::Settings}; |
| 5 | +use serde::de::DeserializeOwned; |
| 6 | +use serde::{Deserialize, Serialize}; |
| 7 | +use std::fmt; |
| 8 | +use std::io::stdin; |
| 9 | + |
| 10 | +#[derive(Debug, Clone)] |
| 11 | +pub struct AwcClient { |
| 12 | + api_key: Option<String>, |
| 13 | +} |
| 14 | + |
| 15 | +impl AwcClient { |
| 16 | + pub fn new(api_key: Option<&str>) -> Result<Self, Error> { |
| 17 | + Ok(AwcClient { |
| 18 | + api_key: api_key.map(|key| key.to_string()), |
| 19 | + }) |
| 20 | + } |
| 21 | +} |
| 22 | + |
| 23 | +#[async_trait(?Send)] |
| 24 | +impl HttpClient for AwcClient { |
| 25 | + async fn stream_request< |
| 26 | + Query: Serialize + Send + Sync, |
| 27 | + Body: futures::AsyncRead + Send + Sync + 'static, |
| 28 | + Output: DeserializeOwned + 'static, |
| 29 | + >( |
| 30 | + &self, |
| 31 | + url: &str, |
| 32 | + method: Method<Query, Body>, |
| 33 | + content_type: &str, |
| 34 | + expected_status_code: u16, |
| 35 | + ) -> Result<Output, Error> { |
| 36 | + let mut builder = awc::ClientBuilder::new(); |
| 37 | + if let Some(ref api_key) = self.api_key { |
| 38 | + builder = builder.bearer_auth(api_key); |
| 39 | + } |
| 40 | + builder = builder.add_default_header(("User-Agent", "Rust client with Awc")); |
| 41 | + let client = builder.finish(); |
| 42 | + |
| 43 | + let query = method.query(); |
| 44 | + let query = yaup::to_string(query)?; |
| 45 | + |
| 46 | + let url = if query.is_empty() { |
| 47 | + url.to_string() |
| 48 | + } else { |
| 49 | + format!("{url}?{query}") |
| 50 | + }; |
| 51 | + |
| 52 | + let url = add_query_parameters(&url, method.query())?; |
| 53 | + let request = client.request(verb(&method), &url); |
| 54 | + |
| 55 | + let mut response = if let Some(body) = method.into_body() { |
| 56 | + let reader = tokio_util::compat::FuturesAsyncReadCompatExt::compat(body); |
| 57 | + let stream = tokio_util::io::ReaderStream::new(reader); |
| 58 | + request |
| 59 | + .content_type(content_type) |
| 60 | + .send_stream(stream) |
| 61 | + .await |
| 62 | + .map_err(|err| Error::Other(Box::new(err)))? |
| 63 | + } else { |
| 64 | + request |
| 65 | + .send() |
| 66 | + .await |
| 67 | + .map_err(|err| Error::Other(Box::new(err)))? |
| 68 | + }; |
| 69 | + |
| 70 | + let status = response.status().as_u16(); |
| 71 | + let mut body = String::from_utf8( |
| 72 | + response |
| 73 | + .body() |
| 74 | + .await |
| 75 | + .map_err(|err| Error::Other(Box::new(err)))? |
| 76 | + .to_vec(), |
| 77 | + ) |
| 78 | + .map_err(|err| Error::Other(Box::new(err)))?; |
| 79 | + |
| 80 | + if body.is_empty() { |
| 81 | + body = "null".to_string(); |
| 82 | + } |
| 83 | + |
| 84 | + parse_response(status, expected_status_code, &body, url.to_string()) |
| 85 | + } |
| 86 | +} |
| 87 | + |
| 88 | +#[actix_rt::main] |
| 89 | +async fn main() { |
| 90 | + let http_client = AwcClient::new(Some("masterKey")).unwrap(); |
| 91 | + let client = Client::new_with_client("http://localhost:7700", Some("masterKey"), http_client); |
| 92 | + |
| 93 | + // build the index |
| 94 | + build_index(&client).await; |
| 95 | + |
| 96 | + // enter in search queries or quit |
| 97 | + loop { |
| 98 | + println!("Enter a search query or type \"q\" or \"quit\" to quit:"); |
| 99 | + let mut input_string = String::new(); |
| 100 | + stdin() |
| 101 | + .read_line(&mut input_string) |
| 102 | + .expect("Failed to read line"); |
| 103 | + match input_string.trim() { |
| 104 | + "quit" | "q" | "" => { |
| 105 | + println!("exiting..."); |
| 106 | + break; |
| 107 | + } |
| 108 | + _ => { |
| 109 | + search(&client, input_string.trim()).await; |
| 110 | + } |
| 111 | + } |
| 112 | + } |
| 113 | + // get rid of the index at the end, doing this only so users don't have the index without knowing |
| 114 | + let _ = client.delete_index("clothes").await.unwrap(); |
| 115 | +} |
| 116 | + |
| 117 | +async fn search(client: &Client<AwcClient>, query: &str) { |
| 118 | + // make the search query, which excutes and serializes hits into the |
| 119 | + // ClothesDisplay struct |
| 120 | + let query_results = client |
| 121 | + .index("clothes") |
| 122 | + .search() |
| 123 | + .with_query(query) |
| 124 | + .execute::<ClothesDisplay>() |
| 125 | + .await |
| 126 | + .unwrap() |
| 127 | + .hits; |
| 128 | + |
| 129 | + // display the query results |
| 130 | + if query_results.is_empty() { |
| 131 | + println!("no results..."); |
| 132 | + } else { |
| 133 | + for clothes in query_results { |
| 134 | + let display = clothes.result; |
| 135 | + println!("{}", format_args!("{}", display)); |
| 136 | + } |
| 137 | + } |
| 138 | +} |
| 139 | + |
| 140 | +async fn build_index(client: &Client<AwcClient>) { |
| 141 | + // reading and parsing the file |
| 142 | + let content = include_str!("../assets/clothes.json"); |
| 143 | + |
| 144 | + // serialize the string to clothes objects |
| 145 | + let clothes: Vec<Clothes> = serde_json::from_str(content).unwrap(); |
| 146 | + |
| 147 | + //create displayed attributes |
| 148 | + let displayed_attributes = ["article", "cost", "size", "pattern"]; |
| 149 | + |
| 150 | + // Create ranking rules |
| 151 | + let ranking_rules = ["words", "typo", "attribute", "exactness", "cost:asc"]; |
| 152 | + |
| 153 | + //create searchable attributes |
| 154 | + let searchable_attributes = ["seaon", "article", "size", "pattern"]; |
| 155 | + |
| 156 | + // create the synonyms hashmap |
| 157 | + let mut synonyms = std::collections::HashMap::new(); |
| 158 | + synonyms.insert("sweater", vec!["cardigan", "long-sleeve"]); |
| 159 | + synonyms.insert("sweat pants", vec!["joggers", "gym pants"]); |
| 160 | + synonyms.insert("t-shirt", vec!["tees", "tshirt"]); |
| 161 | + |
| 162 | + //create the settings struct |
| 163 | + let settings = Settings::new() |
| 164 | + .with_ranking_rules(ranking_rules) |
| 165 | + .with_searchable_attributes(searchable_attributes) |
| 166 | + .with_displayed_attributes(displayed_attributes) |
| 167 | + .with_synonyms(synonyms); |
| 168 | + |
| 169 | + //add the settings to the index |
| 170 | + let result = client |
| 171 | + .index("clothes") |
| 172 | + .set_settings(&settings) |
| 173 | + .await |
| 174 | + .unwrap() |
| 175 | + .wait_for_completion(client, None, None) |
| 176 | + .await |
| 177 | + .unwrap(); |
| 178 | + |
| 179 | + if result.is_failure() { |
| 180 | + panic!( |
| 181 | + "Encountered an error while setting settings for index: {:?}", |
| 182 | + result.unwrap_failure() |
| 183 | + ); |
| 184 | + } |
| 185 | + |
| 186 | + // add the documents |
| 187 | + let result = client |
| 188 | + .index("clothes") |
| 189 | + .add_or_update(&clothes, Some("id")) |
| 190 | + .await |
| 191 | + .unwrap() |
| 192 | + .wait_for_completion(client, None, None) |
| 193 | + .await |
| 194 | + .unwrap(); |
| 195 | + |
| 196 | + if result.is_failure() { |
| 197 | + panic!( |
| 198 | + "Encountered an error while sending the documents: {:?}", |
| 199 | + result.unwrap_failure() |
| 200 | + ); |
| 201 | + } |
| 202 | +} |
| 203 | + |
| 204 | +/// Base search object. |
| 205 | +#[derive(Serialize, Deserialize, Debug)] |
| 206 | +pub struct Clothes { |
| 207 | + id: usize, |
| 208 | + seaon: String, |
| 209 | + article: String, |
| 210 | + cost: f32, |
| 211 | + size: String, |
| 212 | + pattern: String, |
| 213 | +} |
| 214 | + |
| 215 | +/// Search results get serialized to this struct |
| 216 | +#[derive(Serialize, Deserialize, Debug)] |
| 217 | +pub struct ClothesDisplay { |
| 218 | + article: String, |
| 219 | + cost: f32, |
| 220 | + size: String, |
| 221 | + pattern: String, |
| 222 | +} |
| 223 | + |
| 224 | +impl fmt::Display for ClothesDisplay { |
| 225 | + // This trait requires `fmt` with this exact signature. |
| 226 | + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 227 | + // Write strictly the first element into the supplied output |
| 228 | + // stream: `f`. Returns `fmt::Result` which indicates whether the |
| 229 | + // operation succeeded or failed. Note that `write!` uses syntax which |
| 230 | + // is very similar to `println!`. |
| 231 | + write!( |
| 232 | + f, |
| 233 | + "result\n article: {},\n price: {},\n size: {},\n pattern: {}\n", |
| 234 | + self.article, self.cost, self.size, self.pattern |
| 235 | + ) |
| 236 | + } |
| 237 | +} |
| 238 | + |
| 239 | +fn add_query_parameters<Query: Serialize>(url: &str, query: &Query) -> Result<String, Error> { |
| 240 | + let query = yaup::to_string(query)?; |
| 241 | + |
| 242 | + if query.is_empty() { |
| 243 | + Ok(url.to_string()) |
| 244 | + } else { |
| 245 | + Ok(format!("{url}?{query}")) |
| 246 | + } |
| 247 | +} |
| 248 | + |
| 249 | +fn verb<Q, B>(method: &Method<Q, B>) -> awc::http::Method { |
| 250 | + match method { |
| 251 | + Method::Get { .. } => awc::http::Method::GET, |
| 252 | + Method::Delete { .. } => awc::http::Method::DELETE, |
| 253 | + Method::Post { .. } => awc::http::Method::POST, |
| 254 | + Method::Put { .. } => awc::http::Method::PUT, |
| 255 | + Method::Patch { .. } => awc::http::Method::PATCH, |
| 256 | + } |
| 257 | +} |
0 commit comments