Skip to content

Save search events #1373

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 36 additions & 15 deletions pgml-dashboard/src/api/cms.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use std::str::FromStr;
use comrak::{format_html_with_plugins, parse_document, Arena, ComrakPlugins};
use lazy_static::lazy_static;
use markdown::mdast::Node;
use rocket::form::Form;
use rocket::{fs::NamedFile, http::uri::Origin, route::Route, State};
use yaml_rust::YamlLoader;

Expand Down Expand Up @@ -646,9 +647,26 @@ impl Collection {
}
}

#[post("/search_event", data = "<search_event>")]
async fn search_event(
search_event: Form<crate::forms::SearchEvent>,
site_search: &State<crate::utils::markdown::SiteSearch>,
) -> ResponseOk {
match site_search
.add_search_event(search_event.search_id, search_event.clicked)
.await
{
Ok(_) => ResponseOk("ok".to_string()),
Err(e) => {
eprintln!("{:?}", e);
ResponseOk("error".to_string())
}
}
}

#[get("/search?<query>", rank = 20)]
async fn search(query: &str, site_search: &State<crate::utils::markdown::SiteSearch>) -> ResponseOk {
let results = site_search
let (search_id, results) = site_search
.search(query, None, None)
.await
.expect("Error performing search");
Expand Down Expand Up @@ -688,6 +706,7 @@ async fn search(query: &str, site_search: &State<crate::utils::markdown::SiteSea

ResponseOk(
Template(Search {
search_id,
query: query.to_string(),
results,
})
Expand All @@ -697,25 +716,26 @@ async fn search(query: &str, site_search: &State<crate::utils::markdown::SiteSea

#[get("/search_blog?<query>&<tag>", rank = 20)]
async fn search_blog(query: &str, tag: &str, site_search: &State<crate::utils::markdown::SiteSearch>) -> ResponseOk {
let tag = if tag.len() > 0 {
let tag = if !tag.is_empty() {
Some(Vec::from([tag.to_string()]))
} else {
None
};

// If user is not making a search return all blogs in default design.
let results = if query.len() > 0 || tag.clone().is_some() {
let (search_id, results) = if !query.is_empty() || tag.clone().is_some() {
let results = site_search.search(query, Some(DocType::Blog), tag.clone()).await;

let results = match results {
Ok(results) => results
.into_iter()
.map(|document| article_preview::DocMeta::from_document(document))
.collect::<Vec<article_preview::DocMeta>>(),
Err(_) => Vec::new(),
};

results
match results {
Ok((search_id, results)) => (
Some(search_id),
results
.into_iter()
.map(article_preview::DocMeta::from_document)
.collect::<Vec<article_preview::DocMeta>>(),
),
Err(_) => (None, Vec::new()),
}
} else {
let mut results = Vec::new();

Expand All @@ -725,13 +745,13 @@ async fn search_blog(query: &str, tag: &str, site_search: &State<crate::utils::m
results.push(article_preview::DocMeta::from_document(doc));
}

results
(None, results)
};

let is_search = query.len() > 0 || tag.is_some();
let is_search = !query.is_empty() || tag.is_some();

ResponseOk(
crate::components::pages::blog::blog_search::Response::new()
crate::components::pages::blog::blog_search::Response::new(search_id)
.pattern(results, is_search)
.render_once()
.unwrap(),
Expand Down Expand Up @@ -896,6 +916,7 @@ pub fn routes() -> Vec<Route> {
get_docs_asset,
get_user_guides,
search,
search_event,
search_blog
]
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,17 @@ impl DocMeta {
pub struct ArticlePreview {
card_type: String,
meta: DocMeta,
search_id: Option<i64>,
search_result_index: Option<i64>,
}

impl ArticlePreview {
pub fn new(meta: &DocMeta) -> ArticlePreview {
pub fn new(meta: &DocMeta, search_id: Option<i64>, search_result_index: Option<i64>) -> ArticlePreview {
ArticlePreview {
card_type: String::from("default"),
meta: meta.to_owned(),
search_id,
search_result_index,
}
}

Expand Down Expand Up @@ -76,7 +80,7 @@ impl ArticlePreview {
pub async fn from_path(path: &str) -> ArticlePreview {
let doc = Document::from_path(&PathBuf::from(path)).await.unwrap();
let meta = DocMeta::from_document(doc);
ArticlePreview::new(&meta)
ArticlePreview::new(&meta, None, None)
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,12 @@ <h4 style="color: inherit">{}</h4>
);
%>

<%
if let (Some(search_id), Some(search_result_index)) = (search_id, search_result_index) { %>
<div data-controller="cards-blog-article-preview" class="blog-search-result" data-search-id="<%- search_id %>" data-result-index="<%- search_result_index %>">
<% } else { %>
<div data-controller="cards-blog-article-preview">
<% } %>
<% if card_type == String::from("featured") {%>
<a class="doc-card feature-card d-flex flex-column flex-xxl-row" href="<%- meta.path %>">
<div class="cover-image-container">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,23 @@ export default class extends Controller {
connect() {
this.timer;
this.tags = "";

document.addEventListener("click", this.handle_search_click);
}

handle_search_click(e) {
const target = e.target.closest(".blog-search-result");
if (target) {
const resultIndex = target.getAttribute("data-result-index");
const searchId = target.getAttribute("data-search-id");
const formData = new FormData();
formData.append("search_id", searchId);
formData.append("clicked", resultIndex);
fetch('/search_event', {
method: 'POST',
body: formData,
});
}
}

search() {
Expand Down Expand Up @@ -49,4 +66,8 @@ export default class extends Controller {
this.tags = "";
this.search();
}

disconnect() {
document.removeEventListener("click", this.handle_search_click);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,15 @@ use sailfish::TemplateOnce;
#[template(path = "pages/blog/blog_search/response/template.html")]
pub struct Response {
html: Vec<String>,
search_id: Option<i64>,
}

impl Response {
pub fn new() -> Response {
Response { html: Vec::new() }
pub fn new(search_id: Option<i64>) -> Response {
Response {
html: Vec::new(),
search_id,
}
}

pub fn pattern(mut self, mut articles: Vec<DocMeta>, is_search: bool) -> Response {
Expand Down Expand Up @@ -53,7 +57,8 @@ impl Response {
};

articles.reverse();
while articles.len() > 0 {
let mut search_result_index = 0;
while !articles.is_empty() {
// Get the row pattern or repeat the last two row patterns.
let pattern = match layout.get(cycle) {
Some(pattern) => pattern,
Expand All @@ -74,11 +79,12 @@ impl Response {
for (i, doc) in row.into_iter().enumerate() {
let template = pattern[i];
html.push(
ArticlePreview::new(&doc.unwrap())
ArticlePreview::new(&doc.unwrap(), self.search_id, Some(search_result_index))
.card_type(template)
.render_once()
.unwrap(),
)
);
search_result_index += 1;
}
} else {
html.push(format!(
Expand All @@ -101,24 +107,36 @@ impl Response {
{}
</div>
"#,
ArticlePreview::new(&row[0].clone().unwrap())
ArticlePreview::new(&row[0].clone().unwrap(), self.search_id, Some(search_result_index))
.big()
.render_once()
.unwrap(),
ArticlePreview::new(&row[1].clone().unwrap()).render_once().unwrap(),
ArticlePreview::new(&row[2].clone().unwrap()).render_once().unwrap(),
ArticlePreview::new(&row[0].clone().unwrap()).render_once().unwrap(),
ArticlePreview::new(&row[1].clone().unwrap()).render_once().unwrap(),
ArticlePreview::new(&row[2].clone().unwrap()).render_once().unwrap()
))
ArticlePreview::new(&row[1].clone().unwrap(), self.search_id, Some(search_result_index + 1))
.render_once()
.unwrap(),
ArticlePreview::new(&row[2].clone().unwrap(), self.search_id, Some(search_result_index + 2))
.render_once()
.unwrap(),
ArticlePreview::new(&row[0].clone().unwrap(), self.search_id, Some(search_result_index + 3))
.render_once()
.unwrap(),
ArticlePreview::new(&row[1].clone().unwrap(), self.search_id, Some(search_result_index + 4))
.render_once()
.unwrap(),
ArticlePreview::new(&row[2].clone().unwrap(), self.search_id, Some(search_result_index + 5))
.render_once()
.unwrap()
));
search_result_index += 6;
}
} else {
html.push(
ArticlePreview::new(&articles.pop().unwrap())
ArticlePreview::new(&articles.pop().unwrap(), self.search_id, Some(search_result_index))
.card_type("default")
.render_once()
.unwrap(),
)
);
search_result_index += 1;
}
cycle += 1;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
use crate::utils::config::standalone_dashboard;

let cards = featured_cards.iter().map(|card| {
ArticlePreview::new(card).featured().render_once().unwrap()
ArticlePreview::new(card, None, None).featured().render_once().unwrap()
}).collect::<Vec<String>>();
%>

Expand Down
6 changes: 6 additions & 0 deletions pgml-dashboard/src/forms.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,9 @@ pub struct ChatbotPostData {
#[serde(rename = "knowledgeBase")]
pub knowledge_base: u8,
}

#[derive(FromForm)]
pub struct SearchEvent {
pub search_id: i64,
pub clicked: i64
}
1 change: 1 addition & 0 deletions pgml-dashboard/src/templates/docs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use crate::utils::markdown::SearchResult;
#[derive(TemplateOnce)]
#[template(path = "components/search.html")]
pub struct Search {
pub search_id: i64,
pub query: String,
pub results: Vec<SearchResult>,
}
Expand Down
34 changes: 24 additions & 10 deletions pgml-dashboard/src/utils/markdown.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1286,12 +1286,19 @@ impl SiteSearch {
.collect()
}

pub async fn add_search_event(&self, search_id: i64, search_result: i64) -> anyhow::Result<()> {
self.collection.add_search_event(search_id, search_result + 1, serde_json::json!({
"clicked": true
}).into(), &self.pipeline).await?;
Ok(())
}

pub async fn search(
&self,
query: &str,
doc_type: Option<DocType>,
doc_tags: Option<Vec<String>>,
) -> anyhow::Result<Vec<Document>> {
) -> anyhow::Result<(i64, Vec<Document>)> {
let mut search = serde_json::json!({
"query": {
// "full_text_search": {
Expand Down Expand Up @@ -1335,15 +1342,22 @@ impl SiteSearch {
}
let results = self.collection.search_local(search.into(), &self.pipeline).await?;

results["results"]
.as_array()
.context("Error getting results from search")?
.iter()
.map(|r| {
let document: Document = serde_json::from_value(r["document"].clone())?;
Ok(document)
})
.collect()
let search_id = results["search_id"]
.as_i64()
.context("Error getting search_id from search")?;

Ok((
search_id,
results["results"]
.as_array()
.context("Error getting results from search")?
.iter()
.map(|r| {
let document: Document = serde_json::from_value(r["document"].clone())?;
anyhow::Ok(document)
})
.collect::<anyhow::Result<Vec<Document>>>()?,
))
}

pub async fn build(&mut self) -> anyhow::Result<()> {
Expand Down
Loading