1813: Apply highlight tags on numbers in the formatted search result output r=irevoire a=Jhnbrn90

This is my first ever Rust related PR. 

As described in #1758, I've attempted to highlighting numbers correctly under the `_formatted` key.

Additionally, I added a test which should assert appropriate highlighting. 

I'm open to suggestions and improvements. 


Co-authored-by: John Braun <john@brn.email>
This commit is contained in:
bors[bot] 2021-10-18 09:05:01 +00:00 committed by GitHub
commit 79817bd465
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -554,6 +554,11 @@ impl<'a, A: AsRef<[u8]>> Formatter<'a, A> {
}) })
.collect(), .collect(),
), ),
Value::Number(number) => {
let number_string_value =
self.format_string(number.to_string(), matcher, format_options);
Value::String(number_string_value)
}
value => value, value => value,
} }
} }
@ -788,6 +793,92 @@ mod test {
assert_eq!(value["author"], "J. R. R. Tolkien"); assert_eq!(value["author"], "J. R. R. Tolkien");
} }
#[test]
fn formatted_with_highlight_in_number() {
let stop_words = fst::Set::default();
let mut config = AnalyzerConfig::default();
config.stop_words(&stop_words);
let analyzer = Analyzer::new(config);
let formatter = Formatter::new(&analyzer, (String::from("<em>"), String::from("</em>")));
let mut fields = FieldsIdsMap::new();
let title = fields.insert("title").unwrap();
let author = fields.insert("author").unwrap();
let publication_year = fields.insert("publication_year").unwrap();
let mut buf = Vec::new();
let mut obkv = obkv::KvWriter::new(&mut buf);
obkv.insert(
title,
Value::String("The Hobbit".into()).to_string().as_bytes(),
)
.unwrap();
obkv.finish().unwrap();
obkv = obkv::KvWriter::new(&mut buf);
obkv.insert(
author,
Value::String("J. R. R. Tolkien".into())
.to_string()
.as_bytes(),
)
.unwrap();
obkv.finish().unwrap();
obkv = obkv::KvWriter::new(&mut buf);
obkv.insert(
publication_year,
Value::Number(1937.into()).to_string().as_bytes(),
)
.unwrap();
obkv.finish().unwrap();
let obkv = obkv::KvReader::new(&buf);
let mut formatted_options = BTreeMap::new();
formatted_options.insert(
title,
FormatOptions {
highlight: false,
crop: None,
},
);
formatted_options.insert(
author,
FormatOptions {
highlight: false,
crop: None,
},
);
formatted_options.insert(
publication_year,
FormatOptions {
highlight: true,
crop: None,
},
);
let mut matching_words = BTreeMap::new();
matching_words.insert("1937", Some(4));
let value = format_fields(
&fields,
obkv,
&formatter,
&matching_words,
&formatted_options,
)
.unwrap();
assert_eq!(value["title"], "The Hobbit");
assert_eq!(value["author"], "J. R. R. Tolkien");
assert_eq!(value["publication_year"], "<em>1937</em>");
}
/// https://github.com/meilisearch/MeiliSearch/issues/1368 /// https://github.com/meilisearch/MeiliSearch/issues/1368
#[test] #[test]
fn formatted_with_highlight_emoji() { fn formatted_with_highlight_emoji() {