Spencer neon_arch commited on
Commit
bb50e8b
1 Parent(s): c584a7d

✨ Ranking of aggregated search results based on relevancy of the search result to the user's search query (#549)

Browse files

* add sorting by relevance and merge new changes

* fix conflicts

* Update src/models/aggregation_models.rs

Co-authored-by: neon_arch <[email protected]>

* Update src/models/aggregation_models.rs

Co-authored-by: neon_arch <[email protected]>

* Update Cargo.toml

Co-authored-by: neon_arch <[email protected]>

* Update Cargo.toml

Co-authored-by: neon_arch <[email protected]>

* Update Cargo.toml

Co-authored-by: neon_arch <[email protected]>

* enable non-static-synonyms features

---------

Co-authored-by: neon_arch <[email protected]>

Cargo.lock CHANGED
@@ -245,6 +245,12 @@ version = "1.0.2"
245
  source = "registry+https://github.com/rust-lang/crates.io-index"
246
  checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe"
247
 
 
 
 
 
 
 
248
  [[package]]
249
  name = "aead"
250
  version = "0.5.2"
@@ -1840,6 +1846,16 @@ dependencies = [
1840
  "winapi-build",
1841
  ]
1842
 
 
 
 
 
 
 
 
 
 
 
1843
  [[package]]
1844
  name = "language-tags"
1845
  version = "0.3.2"
@@ -1858,6 +1874,26 @@ version = "0.2.153"
1858
  source = "registry+https://github.com/rust-lang/crates.io-index"
1859
  checksum = "9c198f91728a82281a64e1f4f9eeb25d82cb32a5de251c6bd1b5154d63a8e7bd"
1860
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1861
  [[package]]
1862
  name = "libmimalloc-sys"
1863
  version = "0.1.35"
@@ -3029,6 +3065,12 @@ dependencies = [
3029
  "windows-sys 0.52.0",
3030
  ]
3031
 
 
 
 
 
 
 
3032
  [[package]]
3033
  name = "rustc-demangle"
3034
  version = "0.1.23"
@@ -3431,6 +3473,15 @@ version = "1.2.0"
3431
  source = "registry+https://github.com/rust-lang/crates.io-index"
3432
  checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3"
3433
 
 
 
 
 
 
 
 
 
 
3434
  [[package]]
3435
  name = "string"
3436
  version = "0.2.1"
@@ -3607,6 +3658,25 @@ dependencies = [
3607
  "utf-8",
3608
  ]
3609
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3610
  [[package]]
3611
  name = "thousands"
3612
  version = "0.2.0"
@@ -3984,6 +4054,12 @@ dependencies = [
3984
  "tinyvec",
3985
  ]
3986
 
 
 
 
 
 
 
3987
  [[package]]
3988
  name = "unicode-width"
3989
  version = "0.1.11"
@@ -4219,6 +4295,7 @@ dependencies = [
4219
  "error-stack",
4220
  "fake-useragent",
4221
  "futures 0.3.30",
 
4222
  "lightningcss",
4223
  "log",
4224
  "maud",
@@ -4234,7 +4311,9 @@ dependencies = [
4234
  "serde",
4235
  "serde_json",
4236
  "smallvec 1.13.1",
 
4237
  "tempfile",
 
4238
  "tokio 1.36.0",
4239
  ]
4240
 
 
245
  source = "registry+https://github.com/rust-lang/crates.io-index"
246
  checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe"
247
 
248
+ [[package]]
249
+ name = "adler32"
250
+ version = "1.2.0"
251
+ source = "registry+https://github.com/rust-lang/crates.io-index"
252
+ checksum = "aae1277d39aeec15cb388266ecc24b11c80469deae6067e17a1a7aa9e5c1f234"
253
+
254
  [[package]]
255
  name = "aead"
256
  version = "0.5.2"
 
1846
  "winapi-build",
1847
  ]
1848
 
1849
+ [[package]]
1850
+ name = "keyword_extraction"
1851
+ version = "1.3.0"
1852
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1853
+ checksum = "c25710ba2c50e4762b267b7387a989d8d1a8235f5cf26cd84e34aac30b263140"
1854
+ dependencies = [
1855
+ "regex",
1856
+ "unicode-segmentation",
1857
+ ]
1858
+
1859
  [[package]]
1860
  name = "language-tags"
1861
  version = "0.3.2"
 
1874
  source = "registry+https://github.com/rust-lang/crates.io-index"
1875
  checksum = "9c198f91728a82281a64e1f4f9eeb25d82cb32a5de251c6bd1b5154d63a8e7bd"
1876
 
1877
+ [[package]]
1878
+ name = "libflate"
1879
+ version = "1.4.0"
1880
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1881
+ checksum = "5ff4ae71b685bbad2f2f391fe74f6b7659a34871c08b210fdc039e43bee07d18"
1882
+ dependencies = [
1883
+ "adler32",
1884
+ "crc32fast",
1885
+ "libflate_lz77",
1886
+ ]
1887
+
1888
+ [[package]]
1889
+ name = "libflate_lz77"
1890
+ version = "1.2.0"
1891
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1892
+ checksum = "a52d3a8bfc85f250440e4424db7d857e241a3aebbbe301f3eb606ab15c39acbf"
1893
+ dependencies = [
1894
+ "rle-decode-fast",
1895
+ ]
1896
+
1897
  [[package]]
1898
  name = "libmimalloc-sys"
1899
  version = "0.1.35"
 
3065
  "windows-sys 0.52.0",
3066
  ]
3067
 
3068
+ [[package]]
3069
+ name = "rle-decode-fast"
3070
+ version = "1.0.3"
3071
+ source = "registry+https://github.com/rust-lang/crates.io-index"
3072
+ checksum = "3582f63211428f83597b51b2ddb88e2a91a9d52d12831f9d08f5e624e8977422"
3073
+
3074
  [[package]]
3075
  name = "rustc-demangle"
3076
  version = "0.1.23"
 
3473
  source = "registry+https://github.com/rust-lang/crates.io-index"
3474
  checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3"
3475
 
3476
+ [[package]]
3477
+ name = "stop-words"
3478
+ version = "0.8.0"
3479
+ source = "registry+https://github.com/rust-lang/crates.io-index"
3480
+ checksum = "8500024d809de02ecbf998472b7bed3c4fca380df2be68917f6a473bdb28ddcc"
3481
+ dependencies = [
3482
+ "serde_json",
3483
+ ]
3484
+
3485
  [[package]]
3486
  name = "string"
3487
  version = "0.2.1"
 
3658
  "utf-8",
3659
  ]
3660
 
3661
+ [[package]]
3662
+ name = "thesaurus"
3663
+ version = "0.5.2"
3664
+ source = "registry+https://github.com/rust-lang/crates.io-index"
3665
+ checksum = "3e33ea271e53da683cd3439c04ff3b734f3d6052ea33a65ec9e0fa89a4f96369"
3666
+ dependencies = [
3667
+ "lazy_static",
3668
+ "thesaurus-moby",
3669
+ ]
3670
+
3671
+ [[package]]
3672
+ name = "thesaurus-moby"
3673
+ version = "0.2.0"
3674
+ source = "registry+https://github.com/rust-lang/crates.io-index"
3675
+ checksum = "28f7806d5dbe7d9b627e332f88269a014a6a1d40ec411d4ea66cb702aabce4cf"
3676
+ dependencies = [
3677
+ "libflate",
3678
+ ]
3679
+
3680
  [[package]]
3681
  name = "thousands"
3682
  version = "0.2.0"
 
4054
  "tinyvec",
4055
  ]
4056
 
4057
+ [[package]]
4058
+ name = "unicode-segmentation"
4059
+ version = "1.11.0"
4060
+ source = "registry+https://github.com/rust-lang/crates.io-index"
4061
+ checksum = "d4c87d22b6e3f4a18d4d40ef354e97c90fcb14dd91d7dc0aa9d8a1172ebf7202"
4062
+
4063
  [[package]]
4064
  name = "unicode-width"
4065
  version = "0.1.11"
 
4295
  "error-stack",
4296
  "fake-useragent",
4297
  "futures 0.3.30",
4298
+ "keyword_extraction",
4299
  "lightningcss",
4300
  "log",
4301
  "maud",
 
4311
  "serde",
4312
  "serde_json",
4313
  "smallvec 1.13.1",
4314
+ "stop-words",
4315
  "tempfile",
4316
+ "thesaurus",
4317
  "tokio 1.36.0",
4318
  ]
4319
 
Cargo.toml CHANGED
@@ -13,45 +13,93 @@ bench = false
13
  path = "src/bin/websurfx.rs"
14
 
15
  [dependencies]
16
- reqwest = {version="0.11.24", default-features=false, features=["rustls-tls","brotli", "gzip"]}
17
- tokio = {version="1.32.0",features=["rt-multi-thread","macros", "fs", "io-util"], default-features = false}
18
- serde = {version="1.0.196", default-features=false, features=["derive"]}
19
- serde_json = {version="1.0.109", default-features=false}
20
- maud = {version="0.25.0", default-features=false, features=["actix-web"]}
21
- scraper = {version="0.18.1", default-features = false}
22
- actix-web = {version="4.4.0", features = ["cookies", "macros", "compress-brotli"], default-features=false}
23
- actix-files = {version="0.6.5", default-features=false}
24
- actix-cors = {version="0.7.0", default-features=false}
25
- fake-useragent = {version="0.1.3", default-features=false}
26
- env_logger = {version="0.11.1", default-features=false}
27
- log = {version="0.4.21", default-features=false}
28
- mlua = {version="0.9.1", features=["luajit", "vendored"], default-features=false}
29
- redis = {version="0.24.0", features=["tokio-comp","connection-manager"], default-features = false, optional = true}
30
- blake3 = {version="1.5.0", default-features=false}
31
- error-stack = {version="0.4.0", default-features=false, features=["std"]}
32
- async-trait = {version="0.1.76", default-features=false}
33
- regex = {version="1.9.4", features=["perf"], default-features = false}
34
- smallvec = {version="1.13.1", features=["union", "serde"], default-features=false}
35
- futures = {version="0.3.30", default-features=false, features=["alloc"]}
36
- dhat = {version="0.3.2", optional = true, default-features=false}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  mimalloc = { version = "0.1.38", default-features = false }
38
- async-once-cell = {version="0.5.3", default-features=false}
39
- actix-governor = {version="0.5.0", default-features=false}
40
- mini-moka = { version="0.10", optional = true, default-features=false, features=["sync"]}
41
- async-compression = { version = "0.4.6", default-features = false, features=["brotli","tokio"], optional=true}
42
- chacha20poly1305={version="0.10.1", default-features=false, features=["alloc","getrandom"], optional=true}
43
- chacha20 = {version="0.9.1", default-features=false, optional=true}
44
- base64 = {version="0.21.5", default-features=false, features=["std"], optional=true}
45
- cfg-if = {version="1.0.0", default-features=false,optional=true}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
 
47
  [dev-dependencies]
48
- rusty-hook = {version="^0.11.2", default-features=false}
49
- criterion = {version="0.5.1", default-features=false}
50
- tempfile = {version="3.10.1", default-features=false}
51
 
52
  [build-dependencies]
53
- lightningcss = {version="1.0.0-alpha.52", default-features=false, features=["grid"]}
54
- minify-js = {version="0.6.0", default-features=false}
 
 
55
 
56
  [profile.dev]
57
  opt-level = 0
@@ -80,11 +128,13 @@ rpath = false
80
  strip = "symbols"
81
 
82
  [features]
 
83
  default = ["memory-cache"]
84
- dhat-heap = ["dep:dhat"]
85
  memory-cache = ["dep:mini-moka"]
86
- redis-cache = ["dep:redis","dep:base64"]
87
- compress-cache-results = ["dep:async-compression","dep:cfg-if"]
88
- encrypt-cache-results = ["dep:chacha20poly1305","dep:chacha20"]
89
- cec-cache-results = ["compress-cache-results","encrypt-cache-results"]
90
  experimental-io-uring = ["actix-web/experimental-io-uring"]
 
 
13
  path = "src/bin/websurfx.rs"
14
 
15
  [dependencies]
16
+ reqwest = { version = "0.11.24", default-features = false, features = [
17
+ "rustls-tls",
18
+ "brotli",
19
+ "gzip",
20
+ ] }
21
+ tokio = { version = "1.32.0", features = [
22
+ "rt-multi-thread",
23
+ "macros",
24
+ "fs",
25
+ "io-util",
26
+ ], default-features = false }
27
+ serde = { version = "1.0.196", default-features = false, features = ["derive"] }
28
+ serde_json = { version = "1.0.109", default-features = false }
29
+ maud = { version = "0.25.0", default-features = false, features = [
30
+ "actix-web",
31
+ ] }
32
+ scraper = { version = "0.18.1", default-features = false }
33
+ actix-web = { version = "4.4.0", features = [
34
+ "cookies",
35
+ "macros",
36
+ "compress-brotli",
37
+ ], default-features = false }
38
+ actix-files = { version = "0.6.5", default-features = false }
39
+ actix-cors = { version = "0.7.0", default-features = false }
40
+ fake-useragent = { version = "0.1.3", default-features = false }
41
+ env_logger = { version = "0.11.1", default-features = false }
42
+ log = { version = "0.4.21", default-features = false }
43
+ mlua = { version = "0.9.1", features = [
44
+ "luajit",
45
+ "vendored",
46
+ ], default-features = false }
47
+ redis = { version = "0.24.0", features = [
48
+ "tokio-comp",
49
+ "connection-manager",
50
+ ], default-features = false, optional = true }
51
+ blake3 = { version = "1.5.0", default-features = false }
52
+ error-stack = { version = "0.4.0", default-features = false, features = [
53
+ "std",
54
+ ] }
55
+ async-trait = { version = "0.1.76", default-features = false }
56
+ regex = { version = "1.9.4", features = ["perf"], default-features = false }
57
+ smallvec = { version = "1.13.1", features = [
58
+ "union",
59
+ "serde",
60
+ ], default-features = false }
61
+ futures = { version = "0.3.30", default-features = false, features = ["alloc"] }
62
+ dhat = { version = "0.3.2", optional = true, default-features = false }
63
  mimalloc = { version = "0.1.38", default-features = false }
64
+ async-once-cell = { version = "0.5.3", default-features = false }
65
+ actix-governor = { version = "0.5.0", default-features = false }
66
+ mini-moka = { version = "0.10", optional = true, default-features = false, features = [
67
+ "sync",
68
+ ] }
69
+ async-compression = { version = "0.4.6", default-features = false, features = [
70
+ "brotli",
71
+ "tokio",
72
+ ], optional = true }
73
+ chacha20poly1305 = { version = "0.10.1", default-features = false, features = [
74
+ "alloc",
75
+ "getrandom",
76
+ ], optional = true }
77
+ chacha20 = { version = "0.9.1", default-features = false, optional = true }
78
+ base64 = { version = "0.21.5", default-features = false, features = [
79
+ "std",
80
+ ], optional = true }
81
+ cfg-if = { version = "1.0.0", default-features = false, optional = true }
82
+ keyword_extraction = { version = "1.3.0", default-features = false, features = [
83
+ "tf_idf",
84
+
85
+
86
+ ] }
87
+
88
+ stop-words = { version = "0.8.0", default-features = false, features = ["iso"] }
89
+ thesaurus = { version = "0.5.2", default-features = false, optional = true, features = [
90
+ "moby",
91
+ ] }
92
 
93
  [dev-dependencies]
94
+ rusty-hook = { version = "^0.11.2", default-features = false }
95
+ criterion = { version = "0.5.1", default-features = false }
96
+ tempfile = { version = "3.10.1", default-features = false }
97
 
98
  [build-dependencies]
99
+ lightningcss = { version = "1.0.0-alpha.52", default-features = false, features = [
100
+ "grid",
101
+ ] }
102
+ minify-js = { version = "0.6.0", default-features = false }
103
 
104
  [profile.dev]
105
  opt-level = 0
 
128
  strip = "symbols"
129
 
130
  [features]
131
+ use-synonyms-search = ["thesaurus/static"]
132
  default = ["memory-cache"]
133
+ dhat-heap = ["dep:dhat"]
134
  memory-cache = ["dep:mini-moka"]
135
+ redis-cache = ["dep:redis", "dep:base64"]
136
+ compress-cache-results = ["dep:async-compression", "dep:cfg-if"]
137
+ encrypt-cache-results = ["dep:chacha20poly1305", "dep:chacha20"]
138
+ cec-cache-results = ["compress-cache-results", "encrypt-cache-results"]
139
  experimental-io-uring = ["actix-web/experimental-io-uring"]
140
+ use-non-static-synonyms-search = ["thesaurus"]
src/models/aggregation_models.rs CHANGED
@@ -4,7 +4,11 @@
4
  use super::engine_models::EngineError;
5
  use serde::{Deserialize, Serialize};
6
  use smallvec::SmallVec;
7
-
 
 
 
 
8
  /// A named struct to store the raw scraped search results scraped search results from the
9
  /// upstream search engines before aggregating it.It derives the Clone trait which is needed
10
  /// to write idiomatic rust using `Iterators`.
@@ -20,6 +24,8 @@ pub struct SearchResult {
20
  pub description: String,
21
  /// The names of the upstream engines from which this results were provided.
22
  pub engine: SmallVec<[String; 0]>,
 
 
23
  }
24
 
25
  impl SearchResult {
@@ -37,9 +43,49 @@ impl SearchResult {
37
  title: title.to_owned(),
38
  url: url.to_owned(),
39
  description: description.to_owned(),
 
40
  engine: engine.iter().map(|name| name.to_string()).collect(),
41
  }
42
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
  /// A function which adds the engine name provided as a string into a vector of strings.
45
  ///
@@ -182,3 +228,53 @@ impl SearchResults {
182
  self.no_engines_selected = true;
183
  }
184
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  use super::engine_models::EngineError;
5
  use serde::{Deserialize, Serialize};
6
  use smallvec::SmallVec;
7
+ #[cfg(any(
8
+ feature = "use-synonyms-search",
9
+ feature = "use-non-static-synonyms-search"
10
+ ))]
11
+ use thesaurus::synonyms;
12
  /// A named struct to store the raw scraped search results scraped search results from the
13
  /// upstream search engines before aggregating it.It derives the Clone trait which is needed
14
  /// to write idiomatic rust using `Iterators`.
 
24
  pub description: String,
25
  /// The names of the upstream engines from which this results were provided.
26
  pub engine: SmallVec<[String; 0]>,
27
+ /// The td-tdf score of the result in regards to the title, url and description and the user's query
28
+ pub relevance_score: f32,
29
  }
30
 
31
  impl SearchResult {
 
43
  title: title.to_owned(),
44
  url: url.to_owned(),
45
  description: description.to_owned(),
46
+ relevance_score: 0.0,
47
  engine: engine.iter().map(|name| name.to_string()).collect(),
48
  }
49
  }
50
+ /// calculates and update the relevance score of the current search.
51
+
52
+ /// # Arguments
53
+ ///
54
+ /// * query - the query string used to obtain the results
55
+ ///
56
+ ///
57
+
58
+ pub fn calculate_relevance(&mut self, query: &str) {
59
+ use stop_words::{get, LANGUAGE};
60
+ // when language settings can change to any of the ones supported on this crate: https://docs.rs/crate/stop-words/0.8.0
61
+ let documents = [
62
+ self.title.clone(),
63
+ self.url.clone(),
64
+ self.description.clone(),
65
+ ];
66
+
67
+ let stop_words = get(LANGUAGE::English);
68
+ let punctuation = [
69
+ ".".to_owned(),
70
+ ",".to_owned(),
71
+ ":".to_owned(),
72
+ ";".to_owned(),
73
+ "!".to_owned(),
74
+ "?".to_owned(),
75
+ "(".to_owned(),
76
+ ")".to_owned(),
77
+ "[".to_owned(),
78
+ "]".to_owned(),
79
+ "{".to_owned(),
80
+ "}".to_owned(),
81
+ "\"".to_owned(),
82
+ "'".to_owned(),
83
+ "<".to_owned(),
84
+ ">".to_owned(),
85
+ ];
86
+
87
+ self.relevance_score = calculate_tf_idf(query, &documents, &stop_words, &punctuation);
88
+ }
89
 
90
  /// A function which adds the engine name provided as a string into a vector of strings.
91
  ///
 
228
  self.no_engines_selected = true;
229
  }
230
  }
231
+
232
+ /// Helper function to calculate the tf-idf for the search query.
233
+ /// <br> The approach is as [`as`](https://en.wikipedia.org/wiki/Tf%E2%80%93idf).
234
+ /// <br> Find a sample article about TF-IDF [`here`](https://medium.com/analytics-vidhya/tf-idf-term-frequency-technique-easiest-explanation-for-text-classification-in-nlp-with-code-8ca3912e58c3)
235
+ /// ### Arguments
236
+ /// * `query` - a user's search query
237
+ /// * `documents` - a list of text used for comparision (url, title, description)
238
+ /// * `stop_words` - A list of language specific stop words.
239
+ /// * `punctuation` - list of punctuation symbols.
240
+ /// ### Returns
241
+ /// * `score` - The average tf-idf score of the word tokens (and synonyms) in the query
242
+ fn calculate_tf_idf(
243
+ query: &str,
244
+ documents: &[String],
245
+ stop_words: &[String],
246
+ punctuation: &[String],
247
+ ) -> f32 {
248
+ use keyword_extraction::{
249
+ tf_idf::{TfIdf, TfIdfParams},
250
+ tokenizer::Tokenizer,
251
+ };
252
+
253
+ let params = TfIdfParams::UnprocessedDocuments(documents, stop_words, Some(punctuation));
254
+ let tf_idf = TfIdf::new(params);
255
+ let tokener = Tokenizer::new(query, stop_words, Some(punctuation));
256
+ let query_tokens = tokener.split_into_words();
257
+ let mut search_tokens = vec![];
258
+
259
+ for token in query_tokens {
260
+ #[cfg(any(
261
+ feature = "use-synonyms-search",
262
+ feature = "use-non-static-synonyms-search"
263
+ ))]
264
+ {
265
+ // find some synonyms and add them to the search (from wordnet or moby if feature is enabled)
266
+ let synonyms = synonyms(&token);
267
+ search_tokens.extend(synonyms)
268
+ }
269
+ search_tokens.push(token);
270
+ }
271
+
272
+ let mut total_score = 0.0f32;
273
+ for token in search_tokens.iter() {
274
+ total_score += tf_idf.get_score(token);
275
+ }
276
+
277
+ let result = total_score / (search_tokens.len() as f32);
278
+
279
+ f32::from(!result.is_nan()) * result
280
+ }
src/results/aggregator.rs CHANGED
@@ -8,6 +8,7 @@ use crate::models::{
8
  aggregation_models::{EngineErrorInfo, SearchResult, SearchResults},
9
  engine_models::{EngineError, EngineHandler},
10
  };
 
11
  use error_stack::Report;
12
  use futures::stream::FuturesUnordered;
13
  use regex::Regex;
@@ -184,7 +185,17 @@ pub async fn aggregate(
184
  drop(blacklist_map);
185
  }
186
 
187
- let results: Vec<SearchResult> = result_map.iter().map(|(_, value)| value.clone()).collect();
 
 
 
 
 
 
 
 
 
 
188
 
189
  Ok(SearchResults::new(results, &engine_errors_info))
190
  }
@@ -233,7 +244,21 @@ pub async fn filter_with_lists(
233
 
234
  Ok(())
235
  }
236
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
237
  #[cfg(test)]
238
  mod tests {
239
  use super::*;
@@ -252,6 +277,7 @@ mod tests {
252
  url: "https://www.example.com".to_owned(),
253
  description: "This domain is for use in illustrative examples in documents."
254
  .to_owned(),
 
255
  engine: smallvec!["Google".to_owned(), "Bing".to_owned()],
256
  },
257
  ));
@@ -262,6 +288,7 @@ mod tests {
262
  url: "https://www.rust-lang.org/".to_owned(),
263
  description: "A systems programming language that runs blazingly fast, prevents segfaults, and guarantees thread safety.".to_owned(),
264
  engine: smallvec!["Google".to_owned(), "DuckDuckGo".to_owned()],
 
265
  },)
266
  );
267
 
@@ -302,6 +329,7 @@ mod tests {
302
  description: "This domain is for use in illustrative examples in documents."
303
  .to_owned(),
304
  engine: smallvec!["Google".to_owned(), "Bing".to_owned()],
 
305
  },
306
  ));
307
  map_to_be_filtered.push((
@@ -311,6 +339,7 @@ mod tests {
311
  url: "https://www.rust-lang.org/".to_owned(),
312
  description: "A systems programming language that runs blazingly fast, prevents segfaults, and guarantees thread safety.".to_owned(),
313
  engine: smallvec!["Google".to_owned(), "DuckDuckGo".to_owned()],
 
314
  },
315
  ));
316
 
@@ -367,6 +396,7 @@ mod tests {
367
  description: "This domain is for use in illustrative examples in documents."
368
  .to_owned(),
369
  engine: smallvec!["Google".to_owned(), "Bing".to_owned()],
 
370
  },
371
  ));
372
 
 
8
  aggregation_models::{EngineErrorInfo, SearchResult, SearchResults},
9
  engine_models::{EngineError, EngineHandler},
10
  };
11
+
12
  use error_stack::Report;
13
  use futures::stream::FuturesUnordered;
14
  use regex::Regex;
 
185
  drop(blacklist_map);
186
  }
187
 
188
+ let mut results: Vec<SearchResult> = result_map
189
+ .iter()
190
+ .map(|(_, value)| {
191
+ let mut copy = value.clone();
192
+ if !copy.url.contains("temu.com") {
193
+ copy.calculate_relevance(query.as_str())
194
+ }
195
+ copy
196
+ })
197
+ .collect();
198
+ sort_search_results(&mut results);
199
 
200
  Ok(SearchResults::new(results, &engine_errors_info))
201
  }
 
244
 
245
  Ok(())
246
  }
247
+ /// Sorts SearchResults by relevance score.
248
+ /// <br> sort_unstable is used as its faster,stability is not an issue on our side.
249
+ /// For reasons why, check out [`this`](https://rust-lang.github.io/rfcs/1884-unstable-sort.html)
250
+ /// # Arguments
251
+ /// * `results` - A mutable slice or Vec of SearchResults
252
+ ///
253
+ fn sort_search_results(results: &mut [SearchResult]) {
254
+ results.sort_unstable_by(|a, b| {
255
+ use std::cmp::Ordering;
256
+
257
+ b.relevance_score
258
+ .partial_cmp(&a.relevance_score)
259
+ .unwrap_or(Ordering::Less)
260
+ })
261
+ }
262
  #[cfg(test)]
263
  mod tests {
264
  use super::*;
 
277
  url: "https://www.example.com".to_owned(),
278
  description: "This domain is for use in illustrative examples in documents."
279
  .to_owned(),
280
+ relevance_score: 0.0,
281
  engine: smallvec!["Google".to_owned(), "Bing".to_owned()],
282
  },
283
  ));
 
288
  url: "https://www.rust-lang.org/".to_owned(),
289
  description: "A systems programming language that runs blazingly fast, prevents segfaults, and guarantees thread safety.".to_owned(),
290
  engine: smallvec!["Google".to_owned(), "DuckDuckGo".to_owned()],
291
+ relevance_score:0.0
292
  },)
293
  );
294
 
 
329
  description: "This domain is for use in illustrative examples in documents."
330
  .to_owned(),
331
  engine: smallvec!["Google".to_owned(), "Bing".to_owned()],
332
+ relevance_score: 0.0,
333
  },
334
  ));
335
  map_to_be_filtered.push((
 
339
  url: "https://www.rust-lang.org/".to_owned(),
340
  description: "A systems programming language that runs blazingly fast, prevents segfaults, and guarantees thread safety.".to_owned(),
341
  engine: smallvec!["Google".to_owned(), "DuckDuckGo".to_owned()],
342
+ relevance_score:0.0
343
  },
344
  ));
345
 
 
396
  description: "This domain is for use in illustrative examples in documents."
397
  .to_owned(),
398
  engine: smallvec!["Google".to_owned(), "Bing".to_owned()],
399
+ relevance_score: 0.0,
400
  },
401
  ));
402