Open Source alternative to Algolia + Pinecone and an Easier-to-Use alternative to ElasticSearch ⚡ 🔍 ✨ Fast, typo tolerant, in-memory fuzzy Search Engine for building delightful search experiences
C++ algoliadatastoreelasticsearchenterprise-searchfacetingfull-text-searchfuzzy-searchgeosearchin-memoryinstantsearchmerchandisingpineconesearchsearch-enginesemantic-searchsimilarity-searchsite-searchsynonymstypo-tolerancevector-search
Fix unicode character boundary highlighting.
Kishore Nallan11d157463c5b
diff --git a/include/collection.h b/include/collection.hindex 3c1d4158..9b42ece0 100644--- a/include/collection.h+++ b/include/collection.h@@ -128,7 +128,6 @@ private:const field &search_field,const size_t search_field_index,const tsl::htrie_map<char, token_leaf>& qtoken_leaves,- const std::vector<std::string>& q_tokens,const KV* field_order_kv, const nlohmann::json &document,nlohmann::json& highlight_doc,nlohmann::json& highlight_full_doc,@@ -221,7 +220,7 @@ private:const size_t highlight_affix_num_tokens,const tsl::htrie_map<char, token_leaf>& qtoken_leaves,int last_valid_offset_index, const Match& match,- const std::string& last_raw_q_token, bool highlight_fully, const size_t snippet_threshold,+ const size_t prefix_token_num_chars, bool highlight_fully, const size_t snippet_threshold,bool is_infix_search, std::vector<std::string>& raw_query_tokens, size_t last_valid_offset,const std::string& highlight_start_tag, const std::string& highlight_end_tag,const uint8_t* index_symbols, const match_index_t& match_index) const;@@ -478,12 +477,13 @@ bool highlight_nested_field(const nlohmann::json& hdoc, nlohmann::json& hobj,bool resolved = false;for(size_t i = 0; i < it.value().size(); i++) {auto& h_ele = it.value().at(i);- auto& f_ele = fobj[fragment][i];+ auto& f_ele = fobj.empty() ? fobj : fobj[fragment][i];resolved |= highlight_nested_field(hdoc, h_ele, fdoc, f_ele, path_parts, path_index + 1, func);}return resolved;} else {- return highlight_nested_field(hdoc, it.value(), fdoc, fobj[fragment], path_parts, path_index + 1, func);+ auto& f_ele = fobj.empty() ? fobj : fobj[fragment];+ return highlight_nested_field(hdoc, it.value(), fdoc, f_ele, path_parts, path_index + 1, func);}} {return false;diff --git a/include/string_utils.h b/include/string_utils.hindex f5e9f414..2252ad59 100644--- a/include/string_utils.h+++ b/include/string_utils.h@@ -329,4 +329,6 @@ struct StringUtils {static bool contains_word(const std::string& haystack, const std::string& needle);static char* get_ip_str(const struct sockaddr* sa, char* s, size_t maxlen);++ static size_t get_num_chars(const std::string& text);};\ No newline at end of filediff --git a/src/collection.cpp b/src/collection.cppindex 377a4745..04e2c85c 100644--- a/src/collection.cpp+++ b/src/collection.cpp@@ -1372,7 +1372,7 @@ Option<nlohmann::json> Collection::search(const std::string & raw_query,bool found_highlight = false;bool found_full_highlight = false;- highlight_result(raw_query, search_field, i, highlight_item.qtoken_leaves, q_tokens, field_order_kv,+ highlight_result(raw_query, search_field, i, highlight_item.qtoken_leaves, field_order_kv,document, highlight_res["snippet"], highlight_res["full"], highlight_res["meta"],string_utils, snippet_threshold,highlight_affix_num_tokens, highlight_item.fully_highlighted, highlight_item.infix,@@ -2096,7 +2096,6 @@ bool Collection::facet_value_to_string(const facet &a_facet, const facet_count_tvoid Collection::highlight_result(const std::string& raw_query, const field &search_field,const size_t search_field_index,const tsl::htrie_map<char, token_leaf>& qtoken_leaves,- const std::vector<std::string>& q_tokens,const KV* field_order_kv, const nlohmann::json & document,nlohmann::json& highlight_doc,nlohmann::json& highlight_full_doc,@@ -2113,7 +2112,7 @@ void Collection::highlight_result(const std::string& raw_query, const field &seabool& found_highlight,bool& found_full_highlight) const {- if(q_tokens.size() == 1 && q_tokens[0] == "*") {+ if(raw_query == "*") {return;}@@ -2126,7 +2125,7 @@ void Collection::highlight_result(const std::string& raw_query, const field &seaTokenizer(raw_query, normalise, false, search_field.locale, symbols_to_index, token_separators).tokenize(raw_query_tokens);const std::string& last_raw_q_token = raw_query_tokens.back();- const std::string& last_q_token = q_tokens.back();+ size_t prefix_token_num_chars = StringUtils::get_num_chars(last_raw_q_token);std::set<std::string> last_full_q_tokens;@@ -2195,7 +2194,7 @@ void Collection::highlight_result(const std::string& raw_query, const field &seatoken_separators, array_highlight, string_utils, is_cyrillic,highlight_affix_num_tokens,qtoken_leaves, last_valid_offset_index, match,- last_raw_q_token,+ prefix_token_num_chars,highlight_fully, snippet_threshold, is_infix_search,raw_query_tokens,last_valid_offset, highlight_start_tag, highlight_end_tag,@@ -2303,7 +2302,7 @@ void Collection::highlight_result(const std::string& raw_query, const field &seahandle_highlight_text(text, normalise, search_field, symbols_to_index, token_separators,highlight, string_utils, is_cyrillic, highlight_affix_num_tokens,- qtoken_leaves, last_valid_offset_index, match, last_raw_q_token,+ qtoken_leaves, last_valid_offset_index, match, prefix_token_num_chars,highlight_fully, snippet_threshold, is_infix_search, raw_query_tokens,last_valid_offset, highlight_start_tag, highlight_end_tag,index_symbols, match_index);@@ -2391,7 +2390,7 @@ bool Collection::handle_highlight_text(std::string& text, bool normalise, constconst size_t highlight_affix_num_tokens,const tsl::htrie_map<char, token_leaf>& qtoken_leaves,int last_valid_offset_index, const Match& match,- const std::string& last_raw_q_token, bool highlight_fully, const size_t snippet_threshold,+ const size_t prefix_token_num_chars, bool highlight_fully, const size_t snippet_threshold,bool is_infix_search, std::vector<std::string>& raw_query_tokens, size_t last_valid_offset,const std::string& highlight_start_tag, const std::string& highlight_end_tag,const uint8_t* index_symbols, const match_index_t& match_index) const {@@ -2443,58 +2442,66 @@ bool Collection::handle_highlight_text(std::string& text, bool normalise, constauto qtoken_it = qtoken_leaves.find(raw_token);// ensures that the `snippet_start_offset` is always from a matched token, and not from query suggestion- if ((found_first_match && token_already_found) ||- (match_offset_index <= last_valid_offset_index &&- match.offsets[match_offset_index].offset == raw_token_index)) {+ bool match_offset_found = (found_first_match && token_already_found) ||+ (match_offset_index <= last_valid_offset_index &&+ match.offsets[match_offset_index].offset == raw_token_index);- // check if the matched token is a prefix of this found token+ // Token might not appear in the best matched window, which is limited to a size of 10.+ // If field is marked to be highlighted fully, or field length exceeds snippet_threshold, we will+ // locate all tokens that appear in the query / query candidates+ bool raw_token_found = !match_offset_found && (highlight_fully || text.size() < snippet_threshold * 6) &&+ qtoken_leaves.find(raw_token) != qtoken_leaves.end();++ if (match_offset_found || raw_token_found) {if(qtoken_it != qtoken_leaves.end() && qtoken_it.value().is_prefix &&qtoken_it.value().root_len < raw_token.size()) {// need to ensure that only the prefix portion is highlighted// if length diff is within 2, we still might not want to highlight partially in some cases// e.g. "samsng" vs "samsung" -> full highlight is preferred, unless it's a full prefix match- //size_t char_diff = raw_token.size() - qtoken_it.value().root_len;- size_t char_diff = (tok_end - tok_start + 1) - last_raw_q_token.size();- auto new_tok_end = (char_diff <= 2 && qtoken_it.value().num_typos != 0) ?- tok_end : (tok_end - char_diff);- token_offsets.emplace(tok_start, new_tok_end);- } else {- token_offsets.emplace(tok_start, tok_end);- }- token_hits.insert(raw_token);-- // to skip over duplicate tokens in the query- do {- match_offset_index++;- } while(match_offset_index <= last_valid_offset_index &&- match.offsets[match_offset_index - 1].offset == match.offsets[match_offset_index].offset);+ size_t k = tok_start;+ size_t num_letters = 0, prefix_letters = 0, prefix_end = tok_start;- if(!found_first_match) {- snippet_start_offset = snippet_start_window.front();- }+ // group unicode code points and calculate number of actual characters+ while(k <= tok_end) {+ k++;+ if ((text[k] & 0xC0) == 0x80) k++;+ if ((text[k] & 0xC0) == 0x80) k++;+ if ((text[k] & 0xC0) == 0x80) k++;- found_first_match = true;+ num_letters++;- } else if((highlight_fully || text.size() < snippet_threshold * 6) &&- qtoken_leaves.find(raw_token) != qtoken_leaves.end()) {+ if(num_letters <= prefix_token_num_chars) {+ prefix_letters++;+ }- // Token might not appear in the best matched window, which is limited to a size of 10.- // If field is marked to be highlighted fully, or field length exceeds snippet_threshold, we will- // locate all tokens that appear in the query / query candidates+ if(num_letters == prefix_token_num_chars) {+ prefix_end = k - 1;+ }+ }- if(qtoken_it != qtoken_leaves.end() && qtoken_it.value().is_prefix &&- qtoken_it.value().root_len < raw_token.size()) {- // need to ensure that only the prefix portion is highlighted- size_t char_diff = (tok_end - tok_start + 1) - last_raw_q_token.size();- auto new_tok_end = (char_diff <= 2 && qtoken_it.value().num_typos != 0) ?- tok_end : (tok_end - char_diff);+ size_t char_diff = num_letters - prefix_letters;+ auto new_tok_end = (char_diff <= 2 && qtoken_it.value().num_typos != 0) ? tok_end : prefix_end;token_offsets.emplace(tok_start, new_tok_end);} else {token_offsets.emplace(tok_start, tok_end);}token_hits.insert(raw_token);++ if(match_offset_found) {+ // to skip over duplicate tokens in the query+ do {+ match_offset_index++;+ } while(match_offset_index <= last_valid_offset_index &&+ match.offsets[match_offset_index - 1].offset == match.offsets[match_offset_index].offset);++ if(!found_first_match) {+ snippet_start_offset = snippet_start_window.front();+ }++ found_first_match = true;+ }} else if(is_infix_search && text.size() < 100 &&raw_token.find(raw_query_tokens.front()) != std::string::npos) {token_offsets.emplace(tok_start, tok_end);diff --git a/src/string_utils.cpp b/src/string_utils.cppindex 33964dad..baaa828d 100644--- a/src/string_utils.cpp+++ b/src/string_utils.cpp@@ -333,6 +333,20 @@ char* StringUtils::get_ip_str(const struct sockaddr* sa, char* s, size_t maxlen)return s;}+size_t StringUtils::get_num_chars(const std::string& s) {+ // finds number of unicode points in given string+ size_t i = 0, j = 0;+ while (s[i]) {+ if ((s[i] & 0xC0) != 0x80) {+ j++;+ }+ i++;+ }++ return j;+}++/*size_t StringUtils::unicode_length(const std::string& bytes) {std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> utf8conv;return utf8conv.from_bytes(bytes).size();diff --git a/test/collection_specific_more_test.cpp b/test/collection_specific_more_test.cppindex 2b7d067e..413da86e 100644--- a/test/collection_specific_more_test.cpp+++ b/test/collection_specific_more_test.cpp@@ -839,6 +839,49 @@ TEST_F(CollectionSpecificMoreTest, CrossFieldWeightIsNotAugmentated) {collectionManager.drop_collection("coll1");}+TEST_F(CollectionSpecificMoreTest, HighlightWithAccentedChars) {+ std::vector<field> fields = {field(".*", field_types::AUTO, false)};+ Collection* coll1 = collectionManager.create_collection("coll1", 1, fields, "", 0, field_types::AUTO).get();++ auto nested_doc = R"({+ "title": "Rāpeti Early Learning Centre",+ "companies": [+ {"title": "Rāpeti Early Learning Centre"}+ ]+ })"_json;++ ASSERT_TRUE(coll1->add(nested_doc.dump()).ok());++ auto results = coll1->search("rap", {"title", "companies"},+ "", {}, {}, {2}, 10,+ 1, FREQUENCY, {true}).get();++ ASSERT_EQ(1, results["hits"].size());+ ASSERT_EQ("<mark>Rāp</mark>eti Early Learning Centre", results["hits"][0]["highlights"][0]["snippet"].get<std::string>());++ auto highlight_doc = R"({+ "companies":[+ {+ "title":"<mark>Rāp</mark>eti Early Learning Centre"+ }+ ],+ "title":"<mark>Rāp</mark>eti Early Learning Centre"+ })"_json;++ ASSERT_EQ(highlight_doc.dump(), results["hits"][0]["highlight"]["snippet"].dump());++ ASSERT_EQ(0, results["hits"][0]["highlight"]["full"].size());+ ASSERT_EQ(2, results["hits"][0]["highlight"]["meta"].size());++ ASSERT_EQ(1, results["hits"][0]["highlight"]["meta"]["title"].size());+ ASSERT_EQ(1, results["hits"][0]["highlight"]["meta"]["title"]["matched_tokens"].size());+ ASSERT_EQ("Rāp", results["hits"][0]["highlight"]["meta"]["title"]["matched_tokens"][0]);++ ASSERT_EQ(1, results["hits"][0]["highlight"]["meta"]["companies.title"].size());+ ASSERT_EQ(1, results["hits"][0]["highlight"]["meta"]["companies.title"]["matched_tokens"].size());+ ASSERT_EQ("Rāp", results["hits"][0]["highlight"]["meta"]["companies.title"]["matched_tokens"][0]);+}+TEST_F(CollectionSpecificMoreTest, FieldWeightNormalization) {std::vector<field> fields = {field("title", field_types::STRING, false),field("brand", field_types::STRING, false),