Skip to content

web search done right

More search pages

Mikkel Denker2ea159485253
diff --git a/Cargo.lock b/Cargo.lock
index 11db888f..b9211342 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -651,6 +651,7 @@ dependencies = [
"rocksdb",
"serde",
"serde_json",
+ "serde_urlencoded",
"strum",
"tantivy",
"thiserror",
diff --git a/Cargo.toml b/Cargo.toml
index 6e42ac01..224274a6 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -54,6 +54,7 @@ kuchiki = "0.8.1"
strum = { version = "0.24.1", features = ["derive", "strum_macros"] }
tower-http = { version = "0.3.4", features = ["compression-gzip"] }
lalrpop-util = { version = "0.19.8", features = ["lexer"] }
+serde_urlencoded = "0.7.1"
[dev-dependencies]
maplit = "1.0.2"
diff --git a/src/frontend/search.rs b/src/frontend/search.rs
index 14cf46c3..cc2b5abe 100644
--- a/src/frontend/search.rs
+++ b/src/frontend/search.rs
@@ -246,6 +246,9 @@ struct SearchTemplate {
num_matches: String,
search_duration_sec: String,
all_regions: Vec<RegionSelection>,
+ current_page: usize,
+ next_page_url: String,
+ prev_page_url: Option<String>,
}
enum RegionSelection {
@@ -258,9 +261,12 @@ enum RegionSelection {
pub async fn route(
extract::Query(params): extract::Query<HashMap<String, String>>,
Extension(state): Extension<Arc<State>>,
+ extract::OriginalUri(uri): extract::OriginalUri,
) -> impl IntoResponse {
let query = params.get("q").cloned().unwrap_or_default();
+ let skip_pages = params.get("p").and_then(|p| p.parse().ok());
+
let selected_region = params.get("gl").and_then(|gl| {
if let Ok(region) = Region::from_gl(gl) {
Some(region)
@@ -269,7 +275,10 @@ pub async fn route(
}
});
- match state.searcher.search(query.as_str(), selected_region, None) {
+ match state
+ .searcher
+ .search(query.as_str(), selected_region, None, skip_pages)
+ {
Ok(result) => match result {
SearchResult::Websites(result) => {
let search_result = result
@@ -318,6 +327,31 @@ pub async fn route(
})
.collect();
+ let current_page = skip_pages.unwrap_or(0) + 1;
+
+ let mut next_page_params = params.clone();
+ next_page_params.insert("p".to_string(), (skip_pages.unwrap_or(0) + 1).to_string());
+ let next_page_url = uri.path().to_string()
+ + "?"
+ + serde_urlencoded::to_string(&next_page_params)
+ .unwrap()
+ .as_str();
+
+ let prev_page_url = if current_page > 1 {
+ let mut prev_page_params = params;
+ prev_page_params
+ .insert("p".to_string(), (skip_pages.unwrap_or(0) - 1).to_string());
+ Some(
+ uri.path().to_string()
+ + "?"
+ + serde_urlencoded::to_string(&prev_page_params)
+ .unwrap()
+ .as_str(),
+ )
+ } else {
+ None
+ };
+
let template = SearchTemplate {
search_result,
query,
@@ -326,6 +360,9 @@ pub async fn route(
num_matches,
search_duration_sec,
all_regions,
+ current_page,
+ next_page_url,
+ prev_page_url,
};
HtmlTemplate(template).into_response()
diff --git a/src/ranking/mod.rs b/src/ranking/mod.rs
index ca3cc98c..fa6a8100 100644
--- a/src/ranking/mod.rs
+++ b/src/ranking/mod.rs
@@ -23,13 +23,17 @@ use std::sync::Arc;
use initial::InitialScoreTweaker;
use tantivy::collector::{Collector, TopDocs};
-use crate::webpage::region::{Region, RegionCount};
+use crate::{
+ searcher::NUM_RESULTS_PER_PAGE,
+ webpage::region::{Region, RegionCount},
+};
use self::signal_aggregator::SignalAggregator;
pub struct Ranker {
region_count: Arc<RegionCount>,
selected_region: Option<Region>,
+ offset: Option<usize>,
aggregator: SignalAggregator,
}
@@ -38,6 +42,7 @@ impl Ranker {
Ranker {
region_count: Arc::new(region_count),
selected_region: None,
+ offset: None,
aggregator,
}
}
@@ -47,13 +52,25 @@ impl Ranker {
self
}
+ pub fn with_offset(mut self, offset: usize) -> Self {
+ self.offset = Some(offset);
+ self
+ }
+
pub fn collector(&self) -> impl Collector<Fruit = Vec<(f64, tantivy::DocAddress)>> {
let score_tweaker = InitialScoreTweaker::new(
Arc::clone(&self.region_count),
self.selected_region,
SignalAggregator::new_like(&self.aggregator),
);
- TopDocs::with_limit(20).tweak_score(score_tweaker)
+
+ let mut collector = TopDocs::with_limit(NUM_RESULTS_PER_PAGE);
+
+ if let Some(offset) = self.offset {
+ collector = collector.and_offset(offset);
+ }
+
+ collector.tweak_score(score_tweaker)
}
}
@@ -116,7 +133,7 @@ mod tests {
index.commit().expect("failed to commit index");
let searcher = Searcher::from(index);
let result = searcher
- .search("example", None, None)
+ .search("example", None, None, None)
.expect("Search failed")
.into_websites()
.unwrap();
@@ -191,7 +208,7 @@ mod tests {
index.commit().expect("failed to commit index");
let searcher = Searcher::from(index);
let result = searcher
- .search("dr dk", None, None)
+ .search("dr dk", None, None, None)
.expect("Search failed")
.into_websites()
.unwrap();
@@ -250,7 +267,7 @@ mod tests {
index.commit().expect("failed to commit index");
let searcher = Searcher::from(index);
let result = searcher
- .search("title", None, None)
+ .search("title", None, None, None)
.expect("Search failed")
.into_websites()
.unwrap();
@@ -316,7 +333,7 @@ mod tests {
index.commit().expect("failed to commit index");
let searcher = Searcher::from(index);
let result = searcher
- .search("test", None, None)
+ .search("test", None, None, None)
.expect("Search failed")
.into_websites()
.unwrap();
@@ -373,7 +390,7 @@ mod tests {
index.commit().expect("failed to commit index");
let searcher = Searcher::from(index);
let result = searcher
- .search("test", None, None)
+ .search("test", None, None, None)
.expect("Search failed")
.into_websites()
.unwrap();
diff --git a/src/searcher.rs b/src/searcher.rs
index dd25c03b..4d3975c1 100644
--- a/src/searcher.rs
+++ b/src/searcher.rs
@@ -31,6 +31,8 @@ use crate::webpage::region::Region;
use crate::webpage::Url;
use crate::{Error, Result};
+pub const NUM_RESULTS_PER_PAGE: usize = 20;
+
#[derive(Debug)]
pub struct WebsitesResult {
pub spell_corrected_query: Option<String>,
@@ -65,14 +67,13 @@ impl Searcher {
bangs,
}
}
-}
-impl Searcher {
pub fn search(
&self,
query: &str,
selected_region: Option<Region>,
goggle_program: Option<&str>,
+ skip_pages: Option<usize>,
) -> Result<SearchResult> {
let start = Instant::now();
@@ -81,8 +82,6 @@ impl Searcher {
.and_then(|program| signal_aggregator::parse(program).ok())
.unwrap_or_default();
- dbg!(&aggregator);
-
let query = Query::parse(
query,
self.index.schema(),
@@ -102,6 +101,10 @@ impl Searcher {
let mut ranker = Ranker::new(self.index.region_count.clone(), aggregator);
+ if let Some(skip_pages) = skip_pages {
+ ranker = ranker.with_offset(NUM_RESULTS_PER_PAGE * skip_pages);
+ }
+
if let Some(region) = selected_region {
if region != Region::All {
ranker = ranker.with_region(region);
@@ -241,6 +244,7 @@ mod tests {
@host_centrality = 0
"#,
),
+ None,
)
.unwrap()
.into_websites()
@@ -259,6 +263,7 @@ mod tests {
@host_centrality = 0
"#,
),
+ None,
)
.unwrap()
.into_websites()
@@ -268,7 +273,7 @@ mod tests {
assert_eq!(&res.webpages.documents[0].url, "https://www.body.com");
let res = searcher
- .search("example", None, Some("@host_centrality= 2000000"))
+ .search("example", None, Some("@host_centrality= 2000000"), None)
.unwrap()
.into_websites()
.unwrap();
@@ -276,4 +281,56 @@ mod tests {
assert_eq!(res.webpages.num_docs, 3);
assert_eq!(&res.webpages.documents[0].url, "https://www.centrality.com");
}
+
+ #[test]
+ fn offset_page() {
+ const NUM_PAGES: usize = 10;
+ const NUM_WEBSITES: usize = NUM_PAGES * NUM_RESULTS_PER_PAGE;
+
+ let mut index = Index::temporary().expect("Unable to open index");
+
+ for i in 0..NUM_WEBSITES {
+ index
+ .insert(Webpage::new(
+ r#"
+ <html>
+ <head>
+ <title>Example website</title>
+ </head>
+ <body>
+ test
+ </body>
+ </html>
+ "#,
+ &format!("https://www.{i}.com"),
+ vec![],
+ (NUM_WEBSITES - i) as f64,
+ 500,
+ ))
+ .expect("failed to parse webpage");
+ }
+
+ index.commit().unwrap();
+
+ let searcher = Searcher::new(index, None, None);
+
+ for p in 0..NUM_PAGES {
+ let urls = searcher
+ .search("test", None, None, Some(p))
+ .unwrap()
+ .into_websites()
+ .unwrap()
+ .webpages
+ .documents
+ .into_iter()
+ .map(|page| page.url);
+
+ for (i, url) in urls.enumerate() {
+ assert_eq!(
+ url,
+ format!("https://www.{}.com", i + (p * NUM_RESULTS_PER_PAGE))
+ )
+ }
+ }
+ }
}
diff --git a/src/snippet.rs b/src/snippet.rs
index 769a1311..1ee8081e 100644
--- a/src/snippet.rs
+++ b/src/snippet.rs
@@ -347,7 +347,7 @@ Survey in 2016, 2017, and 2018."#;
let searcher = Searcher::from(index);
let result = searcher
- .search("rust language", None, None)
+ .search("rust language", None, None, None)
.expect("Search failed")
.into_websites()
.unwrap();
@@ -387,7 +387,7 @@ Survey in 2016, 2017, and 2018."#;
let searcher = Searcher::from(index);
let result = searcher
- .search("describe", None, None)
+ .search("describe", None, None, None)
.expect("Search failed")
.into_websites()
.unwrap();
diff --git a/templates/search.html b/templates/search.html
index 68f375d1..eeb7a437 100644
--- a/templates/search.html
+++ b/templates/search.html
@@ -90,6 +90,30 @@
</div>
{% endfor %}
</div>
+ <div class="flex w-full justify-center items-center pr-24 mt-5">
+ {% if current_page == 1 %}
+ <div class="prev-page gray-arrow">
+ </div>
+ {% else %}
+ {% match prev_page_url %}
+ {% when Some with (url) %}
+ <a href="{{ url }}">
+ <div class="prev-page cuely-color-arrow">
+ </div>
+ </a>
+ {% when None %}
+ <div class="prev-page gray-arrow">
+ </div>
+ {% endmatch %}
+ {% endif %}
+ <div class="mr-2 ml-2">
+ Page {{ current_page }}
+ </div>
+ <a href="{{ next_page_url }}">
+ <div class="next-page cuely-color-arrow">
+ </div>
+ </a>
+ </div>
</div>
</div>
@@ -105,6 +129,31 @@
{% call footer::footer() %}
<style>
+ .prev-page {
+ width: 16px;
+ height: 16px;
+ -webkit-mask: url(/static/images/arrow.svg) no-repeat center;
+ mask: url(/static/images/arrow.svg) no-repeat center;
+ mask-size: contain;
+ transform: rotate(180deg);
+ }
+
+ .next-page {
+ width: 16px;
+ height: 16px;
+ -webkit-mask: url(/static/images/arrow.svg) no-repeat center;
+ mask: url(/static/images/arrow.svg) no-repeat center;
+ mask-size: contain;
+ }
+
+ .gray-arrow {
+ background-color: gray;
+ }
+
+ .cuely-color-arrow {
+ background-color: #0b7bff;
+ }
+
.title-link {
color: #1a0dab;
}
diff --git a/templates/searchbar.html b/templates/searchbar.html
index af45b306..07b54d9a 100644
--- a/templates/searchbar.html
+++ b/templates/searchbar.html
@@ -170,6 +170,7 @@
var searchParams = new URLSearchParams(window.location.search);
searchParams.set("q", suggestion);
+ searchParams.set("p", "0");
window.location = "/search?" + searchParams.toString();
return;