Rank by score in BTreeMap

main
~erin 2023-07-25 22:50:23 -04:00
parent 450e6092a0
commit 88381113cd
Signed by: erin
GPG Key ID: 0FEDEAFF1C14847E
1 changed files with 26 additions and 16 deletions

View File

@ -16,6 +16,7 @@ use fuzzy_matcher::FuzzyMatcher;
use scraper::{Html, Selector};
use serde::{Deserialize, Serialize};
use sqlx::sqlite::SqlitePool;
use std::collections::BTreeMap;
use std::env;
use std::net::SocketAddr;
use std::sync::Arc;
@ -73,7 +74,7 @@ struct SearchResult {
async fn search(
State(state): State<Arc<AppState>>,
Json(query): Json<SearchQuery>,
) -> Json<Vec<SearchResult>> {
) -> Json<BTreeMap<i64, SearchResult>> {
let mut conn = state.pool.acquire().await.unwrap();
let list = sqlx::query!(
r#"
@ -88,29 +89,38 @@ async fn search(
.await
.unwrap();
let mut results = Vec::new();
let mut results = BTreeMap::new();
let matcher = SkimMatcherV2::default();
for res in list {
let mut is_match = false;
if matcher.fuzzy_match(&res.title, &query.include).is_some() {
is_match = true;
} else if matcher.fuzzy_match(&res.summary, &query.include).is_some() {
is_match = true;
} else if matcher.fuzzy_match(&res.url, &query.include).is_some() {
is_match = true;
let mut score = 0;
let t_match = matcher.fuzzy_match(&res.title, &query.include);
let s_match = matcher.fuzzy_match(&res.summary, &query.include);
let u_match = matcher.fuzzy_match(&res.url, &query.include);
if t_match.is_some() {
score += t_match.unwrap();
}
if is_match {
if s_match.is_some() {
score += s_match.unwrap() / 2;
}
if u_match.is_some() {
score += u_match.unwrap() / 2;
}
if score > 5 {
let timestamp = DateTime::<Utc>::from_utc(
NaiveDateTime::from_timestamp_opt(res.last_updated, 0).unwrap(),
Utc,
);
results.push(SearchResult {
url: Url::parse(&res.url).unwrap(),
size: res.size,
title: res.title,
summary: res.summary,
last_updated: timestamp,
});
results.insert(
score,
SearchResult {
url: Url::parse(&res.url).unwrap(),
size: res.size,
title: res.title,
summary: res.summary,
last_updated: timestamp,
},
);
}
}
return Json(results);