Skip to content

Instantly share code, notes, and snippets.

@robyoung
Created April 12, 2020 14:20
Show Gist options
  • Save robyoung/075a7fac497ed3c99020090b173afc8f to your computer and use it in GitHub Desktop.
Save robyoung/075a7fac497ed3c99020090b173afc8f to your computer and use it in GitHub Desktop.
Can I tweak score based on facet field and query?
//! This example shows searching for recipes by providing a set of ingredients available.
//! In this example I would like Fried egg to have a higher score than Egg rolls because all
//! of the ingredients required for Fried egg are satisfied.
use tantivy::collector::TopDocs;
use tantivy::query::BooleanQuery;
use tantivy::schema::*;
use tantivy::{doc, Index, DocId, SegmentReader, Score};
fn main() {
let mut schema_builder = Schema::builder();
let title = schema_builder.add_text_field("title", TEXT | STORED);
let ingredient = schema_builder.add_facet_field("ingredient");
let schema = schema_builder.build();
let index = Index::create_in_ram(schema.clone());
let mut index_writer = index.writer(30_000_000).unwrap();
index_writer.add_document(doc!(
title => "Fried egg",
ingredient => Facet::from("/ingredient/egg"),
ingredient => Facet::from("/ingredient/oil"),
));
index_writer.add_document(doc!(
title => "Scrambled egg",
ingredient => Facet::from("/ingredient/egg"),
ingredient => Facet::from("/ingredient/butter"),
ingredient => Facet::from("/ingredient/milk"),
ingredient => Facet::from("/ingredient/salt"),
));
index_writer.add_document(doc!(
title => "Egg rolls",
ingredient => Facet::from("/ingredient/egg"),
ingredient => Facet::from("/ingredient/garlic"),
ingredient => Facet::from("/ingredient/salt"),
ingredient => Facet::from("/ingredient/oil"),
ingredient => Facet::from("/ingredient/tortilla-wrap"),
ingredient => Facet::from("/ingredient/mushroom"),
));
index_writer.commit().unwrap();
let reader = index.reader().unwrap();
let searcher = reader.searcher();
{
let query = BooleanQuery::new_multiterms_query(vec![
Term::from_facet(ingredient, &Facet::from_text("/ingredient/egg")),
Term::from_facet(ingredient, &Facet::from_text("/ingredient/oil")),
Term::from_facet(ingredient, &Facet::from_text("/ingredient/garlic")),
Term::from_facet(ingredient, &Facet::from_text("/ingredient/mushroom")),
]);
let top_docs_collector = TopDocs::with_limit(2);
let top_docs = searcher.search(&query, &top_docs_collector).unwrap();
let titles: Vec<String> = top_docs
.iter()
.map(|(_, doc_id)| {
searcher
.doc(*doc_id)
.unwrap()
.get_first(title)
.unwrap()
.text()
.unwrap()
.to_owned()
})
.collect();
assert_eq!(titles, vec!["Fried egg", "Egg rolls"]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment