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
Parameterize rank fields.
Kishore Nallan54a60398ab5d
diff --git a/include/collection.h b/include/collection.hindex 3eb10476..33c45c8e 100644--- a/include/collection.h+++ b/include/collection.h@@ -17,12 +17,16 @@ private:spp::sparse_hash_map<std::string, field> schema;+ std::vector<std::string> rank_fields;+// Integer ID used internally for bitmaps - not exposed to the clientuint32_t seq_id;spp::sparse_hash_map<std::string, art_tree*> index_map;- spp::sparse_hash_map<uint32_t, uint16_t> doc_scores;+ spp::sparse_hash_map<uint32_t, int64_t> primary_rank_scores;++ spp::sparse_hash_map<uint32_t, int64_t> secondary_rank_scores;uint32_t next_seq_id();@@ -39,7 +43,7 @@ private:long long int n);void log_leaves(const int cost, const std::string &token, const std::vector<art_leaf *> &leaves) const;- void search_candidates(std::vector<std::vector<art_leaf*>> & token_leaves, std::vector<nlohmann::json> & results,+ void search_candidates(std::vector<std::vector<art_leaf*>> & token_leaves, std::vector<Topster<100>::KV> & result_kvs,spp::sparse_hash_set<uint64_t> & dedup_seq_ids, size_t & total_results, const size_t & max_results);void index_string_field(const std::string &field_name, art_tree *t, const nlohmann::json &document, uint32_t seq_id) const;@@ -48,7 +52,8 @@ private:public:Collection() = delete;- Collection(const std::string & state_dir_path, const std::string & name, const std::vector<field> & fields);+ Collection(const std::string & state_dir_path, const std::string & name, const std::vector<field> & search_fields,+ const std::vector<std::string> rank_fields);~Collection();std::string add(std::string json_str);std::vector<nlohmann::json> search(std::string query, const int num_typos, const size_t num_results,diff --git a/include/topster.h b/include/topster.hindex 54e19c84..34b37a87 100644--- a/include/topster.h+++ b/include/topster.h@@ -100,4 +100,8 @@ struct Topster {uint64_t getKeyAt(uint32_t index) {return data[index].key;}++ KV getKV(uint32_t index) {+ return data[index];+ }};\ No newline at end of filediff --git a/src/art.cpp b/src/art.cppindex 156fc857..8b82540a 100644--- a/src/art.cpp+++ b/src/art.cpp@@ -62,7 +62,7 @@ bool compare_art_node_frequency(const art_node *a, const art_node *b) {b_value = b->max_token_count;}- return a_value < b_value;+ return a_value > b_value;}bool compare_art_node_score(const art_node* a, const art_node* b) {@@ -82,7 +82,15 @@ bool compare_art_node_score(const art_node* a, const art_node* b) {b_value = b->max_score;}- return a_value < b_value;+ return a_value > b_value;+}++bool compare_art_node_frequency_pq(const art_node *a, const art_node *b) {+ return !compare_art_node_frequency(a, b);+}++bool compare_art_node_score_pq(const art_node* a, const art_node* b) {+ return !compare_art_node_frequency(a, b);}/**@@ -897,10 +905,10 @@ static int art_topk_iter(const art_node *root, token_ordering token_order, constif(token_order == FREQUENCY) {q = std::priority_queue<art_node *, std::vector<const art_node *>,- std::function<bool(const art_node*, const art_node*)>>(compare_art_node_frequency);+ std::function<bool(const art_node*, const art_node*)>>(compare_art_node_frequency_pq);} else {q = std::priority_queue<art_node *, std::vector<const art_node *>,- std::function<bool(const art_node*, const art_node*)>>(compare_art_node_score);+ std::function<bool(const art_node*, const art_node*)>>(compare_art_node_score_pq);}q.push(root);diff --git a/src/collection.cpp b/src/collection.cppindex 94c0291d..5adb94b7 100644--- a/src/collection.cpp+++ b/src/collection.cpp@@ -11,13 +11,13 @@#include "art.h"#include "json.hpp"-Collection::Collection(const std::string & state_dir_path, const std::string & name,- const std::vector<field> & fields): seq_id(0), name(name) {+Collection::Collection(const std::string & state_dir_path, const std::string & name, const std::vector<field> & search_fields,+ const std::vector<std::string> rank_fields): seq_id(0), name(name), rank_fields(rank_fields) {store = new Store(state_dir_path);nlohmann::json fields_json = nlohmann::json::array();- for(const field& field: fields) {+ for(const field& field: search_fields) {art_tree *t = new art_tree;art_tree_init(t);@@ -68,7 +68,14 @@ std::string Collection::add(std::string json_str) {}}- doc_scores[seq_id] = document["points"];+ if(rank_fields.size() > 0 && document.count(rank_fields[0])) {+ primary_rank_scores[seq_id] = document[rank_fields[0]];+ }++ if(rank_fields.size() > 1 && document.count(rank_fields[1])) {+ secondary_rank_scores[seq_id] = document[rank_fields[1]];+ }+return document["id"];}@@ -137,7 +144,7 @@ void Collection::index_string_field(const std::string &field_name, art_tree *t,}void Collection::search_candidates(std::vector<std::vector<art_leaf*>> & token_leaves,- std::vector<nlohmann::json> & results, spp::sparse_hash_set<uint64_t> & dedup_seq_ids,+ std::vector<Topster<100>::KV> & result_kvs, spp::sparse_hash_set<uint64_t> & dedup_seq_ids,size_t & total_results, const size_t & max_results) {const size_t combination_limit = 10;auto product = []( long long a, std::vector<art_leaf*>& b ) { return a*b.size(); };@@ -178,10 +185,7 @@ void Collection::search_candidates(std::vector<std::vector<art_leaf*>> & token_lfor (uint32_t i = 0; i < topster.size && total_results < max_results; i++) {uint64_t seq_id = topster.getKeyAt(i);if(dedup_seq_ids.count(seq_id) == 0) {- std::string value;- store->get(get_seq_id_key((uint32_t) seq_id), value);- nlohmann::json document = nlohmann::json::parse(value);- results.push_back(document);+ result_kvs.push_back(topster.getKV(i));dedup_seq_ids.emplace(seq_id);total_results++;}@@ -211,7 +215,7 @@ std::vector<nlohmann::json> Collection::search(std::string query, const int num_const size_t max_results = std::min(num_results, (size_t) Collection::MAX_RESULTS);size_t total_results = 0;- std::vector<nlohmann::json> results;+ std::vector<Topster<100>::KV> result_kvs;// To prevent us from doing ART search repeatedly as we iterate through possible correctionsspp::sparse_hash_map<std::string, std::vector<art_leaf*>> token_cost_cache;@@ -251,7 +255,7 @@ std::vector<nlohmann::json> Collection::search(std::string query, const int num_}token_leaves.clear();- size_t token_index = 0;+ int token_index = 0;bool retry_with_larger_cost = false;while(token_index < tokens.size()) {@@ -260,7 +264,7 @@ std::vector<nlohmann::json> Collection::search(std::string query, const int num_const std::string token_cost_hash = token + std::to_string(costs[token_index]);std::vector<art_leaf*> leaves;- std::cout << "\n**Searching for: " << token << " - cost: " << costs[token_index] << std::endl;+ //std::cout << "\nSearching for: " << token << " - cost: " << costs[token_index] << std::endl;if(token_cost_cache.count(token_cost_hash) != 0) {leaves = token_cost_cache[token_cost_hash];@@ -294,8 +298,9 @@ std::vector<nlohmann::json> Collection::search(std::string query, const int num_n = -1;N = std::accumulate(token_to_costs.begin(), token_to_costs.end(), 1LL, product);- // Unless we're already at max_cost for this token, don't look at remaining tokens since we would- // see them again in a future iteration when we retry with a larger cost+ // Don't look at remaining tokens if+ // a) We've run out of tokens, or b) We're not at at max_cost for this token+ // since we would see them again in a future iteration when we retry with a larger costif(token_index == -1 || costs[token_index] != max_cost) {retry_with_larger_cost = true;break;@@ -308,14 +313,10 @@ std::vector<nlohmann::json> Collection::search(std::string query, const int num_if(token_leaves.size() != 0 && !retry_with_larger_cost) {// If a) all tokens were found, or b) Some were skipped because they don't exist within max_cost,// go ahead and search for candidates with what we have so far- search_candidates(token_leaves, results, result_set, total_results, max_results);- std::cout << "total_results = " << total_results << std::endl;- for(auto res: results) {- std::cout << "RES: " << res << std::endl;- }+ search_candidates(token_leaves, result_kvs, result_set, total_results, max_results);if (total_results >= max_results) {- // Unless there are results, we continue outerloop (looking at tokens with greater cost)+ // If we don't find enough results, we continue outerloop (looking at tokens with greater cost)break;}}@@ -323,7 +324,7 @@ std::vector<nlohmann::json> Collection::search(std::string query, const int num_n++;}- if(results.size() == 0 && token_to_count.size() != 0) {+ if(result_kvs.size() == 0 && token_to_count.size() != 0) {// Drop certain token with least hits and try searching againstd::string truncated_query;@@ -333,9 +334,9 @@ std::vector<nlohmann::json> Collection::search(std::string query, const int num_}std::sort(token_count_pairs.begin(), token_count_pairs.end(), [=]- (const std::pair<std::string, uint32_t>& a, const std::pair<std::string, uint32_t>& b) {- return a.second > b.second;- }+ (const std::pair<std::string, uint32_t>& a, const std::pair<std::string, uint32_t>& b) {+ return a.second > b.second;+ });for(uint32_t i = 0; i < token_count_pairs.size()-1; i++) {@@ -347,6 +348,15 @@ std::vector<nlohmann::json> Collection::search(std::string query, const int num_return search(truncated_query, num_typos, num_results);}+ std::vector<nlohmann::json> results;++ for(auto result_kv: result_kvs) {+ std::string value;+ store->get(get_seq_id_key((uint32_t) result_kv.key), value);+ nlohmann::json document = nlohmann::json::parse(value);+ results.push_back(document);+ }+long long int timeMillis = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - begin).count();std::cout << "Time taken for result calc: " << timeMillis << "us" << std::endl;store->print_memory_usage();@@ -396,16 +406,11 @@ void Collection::score_results(Topster<100> &topster, const std::vector<art_leaf}const uint64_t match_score = (uint64_t)(mscore.words_present * 32 + (MAX_SEARCH_TOKENS - mscore.distance));- /*- std::cout << "final_score: " << final_score << ", doc_id: " << doc_id << std::endl;- uint32_t doc_score = doc_scores.at(doc_id);- std::cout << "result_ids[i]: " << result_ids[i] << " - mscore.distance: "- << (int) mscore.distance << " - mscore.words_present: " << (int) mscore.words_present- << " - doc_scores[doc_id]: " << (int) doc_scores.at(doc_id) << " - final_score: "- << final_score << std::endl;- */-- topster.add(doc_id, match_score, doc_scores.at(doc_id), 0);+ int64_t primary_rank_score = primary_rank_scores.count(doc_id) > 0 ? primary_rank_scores.at(doc_id) : 0;+ int64_t secondary_rank_score = secondary_rank_scores.count(doc_id) > 0 ? secondary_rank_scores.at(doc_id) : 0;+ topster.add(doc_id, match_score, primary_rank_score, secondary_rank_score);+ /*std::cout << "mscore.distance: " << (int) mscore.distance << ", match_score: "+ << match_score << ", primary_rank_score: " << primary_rank_score << ", doc_id: " << doc_id << std::endl;*/}}diff --git a/src/main/main.cpp b/src/main/main.cppindex b81baed2..21a0c3cf 100644--- a/src/main/main.cpp+++ b/src/main/main.cpp@@ -6,14 +6,40 @@#include <chrono>#include <art.h>#include <unordered_map>+#include <queue>#include "string_utils.h"#include "collection.h"using namespace std;int main() {+ std::array<int, 10> s = {5, 7, 4, 2, 8, 6, 1, 9, 0, 3};+ std::sort(s.begin(), s.end(), [](int a, int b) {+ return a > b;+ });+ for (auto a : s) {+ std::cout << a << " ";+ }++ std::cout << "\n\n\n";++ auto cmp = [](int a, int b) { return a > b; };+ std::priority_queue<int, std::vector<int>, decltype(cmp)> q(cmp);++ for(int n : {1,8,5,6,3,4,0,9,7,2})+ q.push(n);++ while(!q.empty()) {+ std::cout << q.top() << " ";+ q.pop();+ }+ std::cout << '\n';++ return 0;+std::vector<field> fields = {field("title", field_type::STRING)};- Collection *collection = new Collection("/tmp/typesense-data", "collection", fields);+ std::vector<std::string> rank_fields = {"points"};+ Collection *collection = new Collection("/tmp/typesense-data", "collection", fields, rank_fields);std::ifstream infile("/Users/kishore/others/wreally/typesense/test/documents.jsonl");//std::ifstream infile("/Users/kishore/Downloads/hnstories.jsonl");diff --git a/src/main/server.cpp b/src/main/server.cppindex e2cf1483..7bfc4361 100644--- a/src/main/server.cpp+++ b/src/main/server.cpp@@ -27,7 +27,8 @@ static h2o_globalconf_t config;static h2o_context_t ctx;static h2o_accept_ctx_t accept_ctx;std::vector<field> fields = {field("title", field_type::STRING)};-static Collection *collection = new Collection("/tmp/typesense-data", "collection", fields);+std::vector<std::string> rank_fields = {"points"};+static Collection *collection = new Collection("/tmp/typesense-data", "collection", fields, rank_fields);static h2o_pathconf_t *register_handler(h2o_hostconf_t *hostconf, const char *path,int (*on_req)(h2o_handler_t *, h2o_req_t *)) {diff --git a/test/collection_test.cpp b/test/collection_test.cppindex 0be7ac76..669fbfb1 100644--- a/test/collection_test.cpp+++ b/test/collection_test.cpp@@ -11,7 +11,8 @@ protected:virtual void SetUp() {std::ifstream infile("/Users/kishore/others/wreally/typesense/test/documents.jsonl");std::vector<field> fields = {field("title", field_type::STRING)};- collection = new Collection("/tmp/typesense_test/collection", "collection", fields);+ std::vector<std::string> rank_fields = {"points"};+ collection = new Collection("/tmp/typesense_test/collection", "collection", fields, rank_fields);std::string json_line;