Skip to content

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

Fixing an issue with grouping across indices.

kishorencef4051679024
diff --git a/include/collection.h b/include/collection.h
index 648ca384..730bad63 100644
--- a/include/collection.h
+++ b/include/collection.h
@@ -282,5 +282,9 @@ public:
void facet_value_to_string(const facet &a_facet, const facet_count_t &facet_count, const nlohmann::json &document,
std::string &value);
+
+ void aggregate_topster(size_t query_index, Topster &topster, Topster *index_topster) const;
+
+ void populate_result_kvs(Topster *topster, std::vector<std::vector<KV *>> &result_kvs) const;
};
diff --git a/include/topster.h b/include/topster.h
index 685e6d62..2e585a6b 100644
--- a/include/topster.h
+++ b/include/topster.h
@@ -69,6 +69,11 @@ struct Topster {
for(auto& kv: group_kv_map) {
delete kv.second;
}
+
+ data = nullptr;
+ kvs = nullptr;
+
+ group_kv_map.clear();
}
static inline void swapMe(KV** a, KV** b) {
diff --git a/src/collection.cpp b/src/collection.cpp
index a51a7e29..ee23aefe 100644
--- a/src/collection.cpp
+++ b/src/collection.cpp
@@ -407,19 +407,30 @@ Option<nlohmann::json> Collection::search(const std::string & query, const std::
for(auto id: excluded_ids) {
LOG(INFO) << id;
- }*/
+ }
- //LOG(INFO) << "include_ids size: " << include_ids.size();
- //LOG(INFO) << "Pos 1: " << include_ids[1][0];
+ LOG(INFO) << "include_ids size: " << include_ids.size();
+ for(auto& group: include_ids) {
+ for(uint32_t& seq_id: group.second) {
+ LOG(INFO) << "seq_id: " << seq_id;
+ }
+
+ LOG(INFO) << "----";
+ }
+ */
std::map<uint32_t, std::map<size_t, std::vector<uint32_t>>> index_to_included_ids;
std::map<uint32_t, std::vector<uint32_t>> index_to_excluded_ids;
for(const auto& pos_ids: include_ids) {
size_t position = pos_ids.first;
- for(auto seq_id: pos_ids.second) {
+ size_t ids_per_pos = std::max(size_t(1), group_limit);
+
+ for(size_t i = 0; i < std::min(ids_per_pos, pos_ids.second.size()); i++) {
+ auto seq_id = pos_ids.second[i];
auto index_id = (seq_id % num_indices);
index_to_included_ids[index_id][position].push_back(seq_id);
+ //LOG(INFO) << "Adding seq_id " << seq_id << " to index_id " << index_id;
}
}
@@ -709,6 +720,12 @@ Option<nlohmann::json> Collection::search(const std::string & query, const std::
Option<nlohmann::json> index_search_op({}); // stores the last error across all index threads
+ // for grouping we have re-aggregate
+
+ const size_t topster_size = std::max((size_t)1, max_hits);
+ Topster topster(topster_size, group_limit);
+ Topster curated_topster(topster_size, group_limit);
+
for(Index* index: indices) {
// wait for the worker
{
@@ -726,15 +743,8 @@ Option<nlohmann::json> Collection::search(const std::string & query, const std::
continue;
}
- for(const std::vector<KV*> & kv_group: index->search_params->raw_result_kvs) {
- kv_group[0]->query_index += searched_queries.size();
- raw_result_kvs.push_back(kv_group);
- }
-
- for(const std::vector<KV*> & kv_group: index->search_params->override_result_kvs) {
- kv_group[0]->query_index += searched_queries.size();
- override_result_kvs.push_back(kv_group);
- }
+ aggregate_topster(searched_queries.size(), topster, index->search_params->topster);
+ aggregate_topster(searched_queries.size(), curated_topster, index->search_params->curated_topster);
searched_queries.insert(searched_queries.end(), index->search_params->searched_queries.begin(),
index->search_params->searched_queries.end());
@@ -783,46 +793,27 @@ Option<nlohmann::json> Collection::search(const std::string & query, const std::
}
}
- // for grouping we have to aggregate group set sizes to a count value
- if(group_limit) {
- for(auto& acc_facet: facets) {
- for(auto& facet_kv: acc_facet.result_map) {
- facet_kv.second.count = facet_kv.second.groups.size();
- }
- }
-
- total_found = groups_processed.size();
- }
-
if(!index_search_op.ok()) {
return index_search_op;
}
- Topster* aggr_topster = nullptr;
+ topster.sort();
+ curated_topster.sort();
- if(group_limit) {
- // group by query requires another round of topster-ing
+ populate_result_kvs(&topster, raw_result_kvs);
+ populate_result_kvs(&curated_topster, override_result_kvs);
- // needs to be atleast 1 since scoring is mandatory
- const size_t topster_size = std::max((size_t)1, max_hits);
- aggr_topster = new Topster(topster_size, group_limit);
+ // for grouping we have to aggregate group set sizes to a count value
+ if(group_limit) {
+ LOG(INFO) << "override_result_kvs size: " << override_result_kvs.size();
- for(const auto& kv_group: raw_result_kvs) {
- for(KV* kv: kv_group) {
- aggr_topster->add(kv);
+ for(auto& acc_facet: facets) {
+ for(auto& facet_kv: acc_facet.result_map) {
+ facet_kv.second.count = facet_kv.second.groups.size();
}
}
- aggr_topster->sort();
-
- raw_result_kvs.clear();
- raw_result_kvs.shrink_to_fit();
-
- for(auto &group_topster_entry: aggr_topster->group_kv_map) {
- Topster* group_topster = group_topster_entry.second;
- const std::vector<KV*> group_kvs(group_topster->kvs, group_topster->kvs+group_topster->size);
- raw_result_kvs.emplace_back(group_kvs);
- }
+ total_found = groups_processed.size() + override_result_kvs.size();
}
// All fields are sorted descending
@@ -1063,8 +1054,6 @@ Option<nlohmann::json> Collection::search(const std::string & query, const std::
delete index->search_params;
}
- delete aggr_topster;
-
result["request_params"] = nlohmann::json::object();;
result["request_params"]["per_page"] = per_page;
result["request_params"]["q"] = query;
@@ -1075,6 +1064,43 @@ Option<nlohmann::json> Collection::search(const std::string & query, const std::
return result;
}
+
+void Collection::populate_result_kvs(Topster *topster, std::vector<std::vector<KV *>> &result_kvs) const {
+ if(topster->distinct) {
+ for(auto &group_topster_entry: topster->group_kv_map) {
+ Topster* group_topster = group_topster_entry.second;
+ const std::vector<KV*> group_kvs(group_topster->kvs, group_topster->kvs+group_topster->size);
+ result_kvs.emplace_back(group_kvs);
+ }
+
+ } else {
+ for(uint32_t t = 0; t < topster->size; t++) {
+ KV* kv = topster->getKV(t);
+ result_kvs.push_back({kv});
+ }
+ }
+}
+
+void Collection::aggregate_topster(size_t query_index, Topster &topster, Topster *index_topster) const {
+ if(index_topster->distinct) {
+ for(auto &group_topster_entry: index_topster->group_kv_map) {
+ Topster* group_topster = group_topster_entry.second;
+ const std::vector<KV*> group_kvs(group_topster->kvs, group_topster->kvs+group_topster->size);
+ for(KV* kv: group_kvs) {
+ kv->query_index += query_index;
+ topster.add(kv);
+ }
+ }
+
+ } else {
+ for(uint32_t t = 0; t < index_topster->size; t++) {
+ KV* kv = index_topster->getKV(t);
+ kv->query_index += query_index;
+ topster.add(kv);
+ }
+ }
+}
+
void Collection::facet_value_to_string(const facet &a_facet, const facet_count_t &facet_count,
const nlohmann::json &document, std::string &value) {
diff --git a/src/index.cpp b/src/index.cpp
index 6fdee499..ce1fecbc 100644
--- a/src/index.cpp
+++ b/src/index.cpp
@@ -1181,34 +1181,6 @@ void Index::search(Option<uint32_t> & outcome,
topster->sort();
curated_topster->sort();
- // loop through topster and remove elements from included and excluded id lists
-
- if(topster->distinct) {
- for(auto &group_topster_entry: topster->group_kv_map) {
- Topster* group_topster = group_topster_entry.second;
- const std::vector<KV*> group_kvs(group_topster->kvs, group_topster->kvs+group_topster->size);
- raw_result_kvs.emplace_back(group_kvs);
- }
-
- for(auto &curated_topster_entry: curated_topster->group_kv_map) {
- Topster* group_topster = curated_topster_entry.second;
- const std::vector<KV*> group_kvs(group_topster->kvs, group_topster->kvs+group_topster->size);
- override_result_kvs.emplace_back(group_kvs);
- }
-
- } else {
- for(uint32_t t = 0; t < topster->size; t++) {
- KV* kv = topster->getKV(t);
- raw_result_kvs.push_back({kv});
- }
-
- for(uint32_t t = 0; t < curated_topster->size; t++) {
- KV* kv = curated_topster->getKV(t);
- override_result_kvs.push_back({kv});
- }
- }
-
- // add curated IDs to result count
all_result_ids_len += curated_topster->size;
delete [] filter_ids;
diff --git a/test/collection_grouping_test.cpp b/test/collection_grouping_test.cpp
new file mode 100644
index 00000000..b6d99948
--- /dev/null
+++ b/test/collection_grouping_test.cpp
@@ -0,0 +1,71 @@
+#include <gtest/gtest.h>
+#include <string>
+#include <vector>
+#include <fstream>
+#include <algorithm>
+#include <collection_manager.h>
+#include "collection.h"
+
+class CollectionGroupingTest : public ::testing::Test {
+protected:
+ Store *store;
+ CollectionManager & collectionManager = CollectionManager::get_instance();
+
+ std::vector<std::string> query_fields;
+ std::vector<sort_by> sort_fields;
+
+ void setupCollection() {
+ std::string state_dir_path = "/tmp/typesense_test/collection_sorting";
+ LOG(INFO) << "Truncating and creating: " << state_dir_path;
+ system(("rm -rf "+state_dir_path+" && mkdir -p "+state_dir_path).c_str());
+
+ store = new Store(state_dir_path);
+ collectionManager.init(store, 4, "auth_key");
+ collectionManager.load();
+ }
+
+ virtual void SetUp() {
+ setupCollection();
+ }
+
+ virtual void TearDown() {
+ delete store;
+ }
+};
+
+TEST_F(CollectionGroupingTest, GroupingOnOptionalIntegerArray) {
+ Collection *coll1;
+
+ std::vector<field> fields = {
+ field("title", field_types::STRING, false),
+ field("description", field_types::STRING, true, true),
+ field("max", field_types::INT32, false),
+ field("scores", field_types::INT64_ARRAY, true, true),
+ field("average", field_types::FLOAT, false, true),
+ field("is_valid", field_types::BOOL, false, true),
+ };
+
+ coll1 = collectionManager.get_collection("coll1");
+ if(coll1 == nullptr) {
+ coll1 = collectionManager.create_collection("coll1", fields, "max").get();
+ }
+
+ std::ifstream infile(std::string(ROOT_DIR)+"test/optional_fields.jsonl");
+
+ std::string json_line;
+
+ while (std::getline(infile, json_line)) {
+ auto add_op = coll1->add(json_line);
+ if(!add_op.ok()) {
+ std::cout << add_op.error() << std::endl;
+ }
+ ASSERT_TRUE(add_op.ok());
+ }
+
+ infile.close();
+
+ // first must be able to fetch all records (i.e. all must have been index)
+
+ auto res = coll1->search("*", {"title"}, "", {}, {}, 0, 10, 1, FREQUENCY, false).get();
+ ASSERT_EQ(6, res["found"].get<size_t>());
+}
\ No newline at end of file
diff --git a/test/collection_override_test.cpp b/test/collection_override_test.cpp
index eaf153f7..8aca5069 100644
--- a/test/collection_override_test.cpp
+++ b/test/collection_override_test.cpp
@@ -18,7 +18,7 @@ protected:
system(("rm -rf "+state_dir_path+" && mkdir -p "+state_dir_path).c_str());
store = new Store(state_dir_path);
- collectionManager.init(store, 1, "auth_key");
+ collectionManager.init(store, 4, "auth_key");
collectionManager.load();
std::ifstream infile(std::string(ROOT_DIR)+"test/multi_field_documents.jsonl");
@@ -248,7 +248,7 @@ TEST_F(CollectionOverrideTest, ExcludeIncludeFacetFilterQuery) {
spp::sparse_hash_set<std::string>(),
spp::sparse_hash_set<std::string>(), 10, "").get();
- ASSERT_EQ(1, results["found"].get<size_t>());
+ ASSERT_EQ(2, results["found"].get<size_t>());
ASSERT_EQ(1, results["hits"].size());
ASSERT_EQ("0", results["hits"][0]["document"]["id"].get<std::string>());
@@ -342,4 +342,38 @@ TEST_F(CollectionOverrideTest, IncludeExcludeHitsQuery) {
ASSERT_EQ(8, results["found"].get<size_t>());
ASSERT_STREQ("8", results["hits"][0]["document"]["id"].get<std::string>().c_str());
ASSERT_STREQ("6", results["hits"][1]["document"]["id"].get<std::string>().c_str());
+}
+
+TEST_F(CollectionOverrideTest, PinnedHitsGrouping) {
+ std::map<size_t, std::vector<std::string>> pinned_hits;
+ pinned_hits[1] = {"6", "8"};
+ pinned_hits[2] = {"1"};
+ pinned_hits[3] = {"13", "4"};
+
+ // without any grouping parameter, only the first ID in a position should be picked
+ // and other IDs should appear in their original positions
+
+ auto results = coll_mul_fields->search("the", {"title"}, "", {"starring"}, {}, 0, 50, 1, FREQUENCY,
+ false, Index::DROP_TOKENS_THRESHOLD,
+ spp::sparse_hash_set<std::string>(),
+ spp::sparse_hash_set<std::string>(), 10, "starring: will", 30,
+ "", 10,
+ pinned_hits, {}).get();
+
+ ASSERT_EQ(10, results["found"].get<size_t>());
+ ASSERT_STREQ("6", results["hits"][0]["document"]["id"].get<std::string>().c_str());
+ ASSERT_STREQ("1", results["hits"][1]["document"]["id"].get<std::string>().c_str());
+ ASSERT_STREQ("13", results["hits"][2]["document"]["id"].get<std::string>().c_str());
+ ASSERT_STREQ("11", results["hits"][3]["document"]["id"].get<std::string>().c_str());
+
+ // with grouping
+
+ results = coll_mul_fields->search("the", {"title"}, "", {"starring"}, {}, 0, 50, 1, FREQUENCY,
+ false, Index::DROP_TOKENS_THRESHOLD,
+ spp::sparse_hash_set<std::string>(),
+ spp::sparse_hash_set<std::string>(), 10, "starring: will", 30,
+ "", 10,
+ pinned_hits, {}, {"cast"}, 2).get();
+
+ ASSERT_EQ(8, results["found"].get<size_t>());
}
\ No newline at end of file
diff --git a/test/collection_test.cpp b/test/collection_test.cpp
index dc904ce5..51865d89 100644
--- a/test/collection_test.cpp
+++ b/test/collection_test.cpp
@@ -2265,7 +2265,6 @@ TEST_F(CollectionTest, OptionalFields) {
// try fetching the schema (should contain optional field)
nlohmann::json coll_summary = coll1->get_summary_json();
- LOG(INFO) << coll_summary;
ASSERT_STREQ("title", coll_summary["fields"][0]["name"].get<std::string>().c_str());
ASSERT_STREQ("string", coll_summary["fields"][0]["type"].get<std::string>().c_str());
ASSERT_FALSE(coll_summary["fields"][0]["facet"].get<bool>());