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

refactor counter events with tests (#1557)

Krunal Gandhife2a0be56431
diff --git a/include/analytics_manager.h b/include/analytics_manager.h
index 51efba1c..f4394a53 100644
--- a/include/analytics_manager.h
+++ b/include/analytics_manager.h
@@ -11,6 +11,7 @@
struct event_type_collection {
std::string event_type;
std::string collection;
+ bool log_to_file = false;
};
struct event_t {
@@ -21,19 +22,21 @@ struct event_t {
std::string doc_id;
std::string name;
std::vector<std::pair<std::string, std::string>> data;
+ bool log_to_file;
event_t() = delete;
~event_t() = default;
event_t(const std::string& q, const std::string& type, uint64_t ts, const std::string& uid, const std::string& id,
- const std::string& event_name, const std::vector<std::pair<std::string, std::string>> datavec) {
+ const std::string& event_name, bool should_log_to_file, const std::vector<std::pair<std::string, std::string>> datavec) {
query = q;
event_type = type;
timestamp = ts;
user_id = uid;
doc_id = id;
name = event_name;
+ log_to_file = should_log_to_file;
data = datavec;
}
diff --git a/src/analytics_manager.cpp b/src/analytics_manager.cpp
index b26551bc..e6c97322 100644
--- a/src/analytics_manager.cpp
+++ b/src/analytics_manager.cpp
@@ -194,9 +194,25 @@ Option<bool> AnalyticsManager::create_index(nlohmann::json &payload, bool upsert
QueryAnalytics *noresultsQueries = new QueryAnalytics(limit);
nohits_queries.emplace(suggestion_collection, noresultsQueries);
} else if(payload["type"] == COUNTER_TYPE) {
+ if(query_collection_events.count(suggestion_collection) == 0) {
+ std::vector<event_t> vec;
+ query_collection_events.emplace(suggestion_collection, vec);
+ }
+
std::map<std::string, uint16_t> event_weight_map;
for(const auto& event : params["source"]["events"]){
- event_weight_map[event["type"]] = event["weight"];
+ if(!event.contains("name") || event_collection_map.count(event["name"]) != 0) {
+ return Option<bool>(400, "Events must contain a unique name.");
+ }
+ //store event name to their weights
+ //which can be used to keep counter events separate from non counter events
+ bool log_to_file = false;
+ if(event.contains("log_to_file")) {
+ log_to_file = event["log_to_file"].get<bool>();
+ }
+ event_weight_map[event["name"]] = event["weight"];
+ event_type_collection ec {event["type"], suggestion_collection, log_to_file};
+ event_collection_map.emplace(event["name"], ec);
}
counter_events.emplace(suggestion_collection, counter_event_t{counter_field, {}, event_weight_map});
} else if(is_event_type) {
@@ -207,7 +223,7 @@ Option<bool> AnalyticsManager::create_index(nlohmann::json &payload, bool upsert
query_collection_events.emplace(suggestion_collection, vec);
}
auto sub_event_type = get_sub_event_type(payload["type"]);
- event_type_collection ec {sub_event_type, suggestion_collection};
+ event_type_collection ec {sub_event_type, suggestion_collection, true};
event_collection_map.emplace(params["name"], ec);
}
@@ -421,18 +437,19 @@ Option<bool> AnalyticsManager::add_event(const std::string& client_ip, const std
doc_id = event_json["doc_id"].get<std::string>();
}
- event_t event(query, event_type, now_ts_useconds, user_id, doc_id, event_name, custom_data);
+ event_t event(query, event_type, now_ts_useconds, user_id, doc_id,
+ event_name, event_collection_map[event_name].log_to_file, custom_data);
events_vec.emplace_back(event);
if (!counter_events.empty()) {
auto counter_events_it = counter_events.find(query_collection);
if (counter_events_it != counter_events.end()) {
- auto event_weight_map_it = counter_events_it->second.event_weight_map.find(event_type);
+ auto event_weight_map_it = counter_events_it->second.event_weight_map.find(event_name);
if (event_weight_map_it != counter_events_it->second.event_weight_map.end()) {
auto inc_val = event_weight_map_it->second;
counter_events_it->second.docid_counts[doc_id] += inc_val;
} else {
- LOG(ERROR) << "event_type " << event_type
+ LOG(ERROR) << "event_name " << event_name
<< " not defined in analytic rule for counter events.";
}
} else {
@@ -584,7 +601,7 @@ void AnalyticsManager::persist_events() {
for (auto &events_collection_it: query_collection_events) {
const auto& collection = events_collection_it.first;
for (const auto &event: events_collection_it.second) {
- if (analytics_logs.is_open()) {
+ if (analytics_logs.is_open() && event.log_to_file) {
//store events to log file
analytics_logs << event.timestamp << "\t" << event.name << "\t"
<< collection << "\t" << event.user_id << "\t" << event.doc_id << "\t"
@@ -654,6 +671,18 @@ void AnalyticsManager::dispose() {
}
nohits_queries.clear();
+
+ suggestion_configs.clear();
+
+ query_collection_mapping.clear();
+
+ counter_events.clear();
+
+ query_collection_events.clear();
+
+ event_collection_map.clear();
+
+ events_cache.clear();
}
void AnalyticsManager::init(Store* store, const std::string& analytics_dir) {
diff --git a/test/analytics_manager_test.cpp b/test/analytics_manager_test.cpp
index f42e1f72..a77f1087 100644
--- a/test/analytics_manager_test.cpp
+++ b/test/analytics_manager_test.cpp
@@ -788,40 +788,13 @@ TEST_F(AnalyticsManagerTest, PopularityScore) {
ASSERT_TRUE(products_coll->add(doc.dump()).ok());
auto analytics_rule = R"({
- "name": "click_events",
- "type": "clicks",
- "params": {
- "name": "XY",
- "source": {
- "collection": "products"
- }
- }
- })"_json;
-
- auto create_op = analyticsManager.create_rule(analytics_rule, true, true);
- ASSERT_TRUE(create_op.ok());
-
- analytics_rule = R"({
- "name": "conversion_events",
- "type": "conversions",
- "params": {
- "name": "YZ",
- "source": {
- "collection": "products"
- }
- }
- })"_json;
-
- create_op = analyticsManager.create_rule(analytics_rule, true, true);
- ASSERT_TRUE(create_op.ok());
-
- analytics_rule = R"({
"name": "product_popularity",
"type": "counter",
"params": {
"source": {
"collections": ["products"],
- "events": [{"type": "click", "weight": 1}, {"type": "conversion", "weight": 5} ]
+ "events": [{"type": "click", "weight": 1, "name": "CLK1"}, {"type": "conversion", "weight": 5, "name": "CNV1"} ],
+ "log_to_file": true
},
"destination": {
"collection": "products",
@@ -830,7 +803,7 @@ TEST_F(AnalyticsManagerTest, PopularityScore) {
}
})"_json;
- create_op = analyticsManager.create_rule(analytics_rule, false, true);
+ auto create_op = analyticsManager.create_rule(analytics_rule, false, true);
ASSERT_TRUE(create_op.ok());
std::shared_ptr<http_req> req = std::make_shared<http_req>();
@@ -838,7 +811,7 @@ TEST_F(AnalyticsManagerTest, PopularityScore) {
nlohmann::json event1 = R"({
"type": "conversion",
- "name": "YZ",
+ "name": "CNV1",
"data": {
"q": "trousers",
"doc_id": "1",
@@ -851,7 +824,7 @@ TEST_F(AnalyticsManagerTest, PopularityScore) {
nlohmann::json event2 = R"({
"type": "click",
- "name": "XY",
+ "name": "CLK1",
"data": {
"q": "shorts",
"doc_id": "3",
@@ -873,7 +846,7 @@ TEST_F(AnalyticsManagerTest, PopularityScore) {
nlohmann::json event3 = R"({
"type": "click",
- "name": "XY",
+ "name": "CLK1",
"data": {
"q": "shorts",
"doc_id": "1",
@@ -886,7 +859,7 @@ TEST_F(AnalyticsManagerTest, PopularityScore) {
nlohmann::json event4 = R"({
"type": "conversion",
- "name": "YZ",
+ "name": "CNV1",
"data": {
"q": "shorts",
"doc_id": "3",
@@ -935,7 +908,7 @@ TEST_F(AnalyticsManagerTest, PopularityScore) {
nlohmann::json event5 = R"({
"type": "conversion",
- "name": "YZ",
+ "name": "CNV1",
"data": {
"q": "shorts",
"doc_id": "3",
@@ -952,6 +925,12 @@ TEST_F(AnalyticsManagerTest, PopularityScore) {
}
TEST_F(AnalyticsManagerTest, PopularityScoreValidation) {
+ //restart analytics manager as fresh
+ analyticsManager.dispose();
+ analyticsManager.stop();
+ system("rm -rf /tmp/typesense_test/analytics_manager_test/analytics_events.tsv");
+ analyticsManager.init(store, "/tmp/typesense_test/analytics_manager_test");
+
nlohmann::json products_schema = R"({
"name": "books",
"fields": [
@@ -960,7 +939,18 @@ TEST_F(AnalyticsManagerTest, PopularityScoreValidation) {
]
})"_json;
- Collection* products_coll = collectionManager.create_collection(products_schema).get();
+ Collection *products_coll = collectionManager.create_collection(products_schema).get();
+
+ nlohmann::json doc;
+ doc["popularity"] = 0;
+
+ doc["id"] = "0";
+ doc["title"] = "Cool trousers";
+ ASSERT_TRUE(products_coll->add(doc.dump()).ok());
+
+ doc["id"] = "1";
+ doc["title"] = "Funky trousers";
+ ASSERT_TRUE(products_coll->add(doc.dump()).ok());
nlohmann::json analytics_rule = R"({
"name": "books_popularity",
@@ -968,7 +958,7 @@ TEST_F(AnalyticsManagerTest, PopularityScoreValidation) {
"params": {
"source": {
"collections": ["books"],
- "events": [{"type": "query_click", "weight": 1}, {"type": "query_purchase", "weight": 5} ]
+ "events": [{"type": "click", "weight": 1, "name": "CLK2"}, {"type": "conversion", "weight": 5, "name": "CNV2"} ]
},
"destination": {
"collection": "popular_books",
@@ -987,7 +977,7 @@ TEST_F(AnalyticsManagerTest, PopularityScoreValidation) {
"params": {
"source": {
"collections": ["books"],
- "events": [{"type": "query_click", "weight": 1}, {"type": "query_purchase", "weight": 5} ]
+ "events": [{"type": "click", "weight": 1, "name": "CLK3"}, {"type": "conversion", "weight": 5, "name": "CNV3"} ]
},
"destination": {
"collection": "books",
@@ -1074,4 +1064,178 @@ TEST_F(AnalyticsManagerTest, PopularityScoreValidation) {
create_op = analyticsManager.create_rule(analytics_rule, false, true);
ASSERT_FALSE(create_op.ok());
ASSERT_EQ("Bad or missing events.", create_op.error());
+
+ analytics_rule = R"({
+ "name": "books_popularity",
+ "type": "counter",
+ "params": {
+ "source": {
+ "collections": ["books"],
+ "events": [{"type": "click", "weight": 1}, {"type": "conversion", "weight": 5} ]
+ },
+ "destination": {
+ "collection": "books",
+ "counter_field": "popularity"
+ }
+ }
+ })"_json;
+
+ create_op = analyticsManager.create_rule(analytics_rule, false, true);
+ ASSERT_FALSE(create_op.ok());
+ ASSERT_EQ("Events must contain a unique name.", create_op.error());
+
+
+ std::shared_ptr<http_req> req = std::make_shared<http_req>();
+ std::shared_ptr<http_res> res = std::make_shared<http_res>(nullptr);
+
+ //correct params
+ analytics_rule = R"({
+ "name": "books_popularity2",
+ "type": "counter",
+ "params": {
+ "source": {
+ "collections": ["books"],
+ "events": [{"type": "click", "weight": 1, "name" : "CLK4"}, {"type": "conversion", "weight": 5, "name": "CNV4", "log_to_file" : true} ]
+ },
+ "destination": {
+ "collection": "books",
+ "counter_field": "popularity"
+ }
+ }
+ })"_json;
+
+ create_op = analyticsManager.create_rule(analytics_rule, false, true);
+ ASSERT_TRUE(create_op.ok());
+
+ nlohmann::json event = R"({
+ "type": "conversion",
+ "name": "CNV4",
+ "data": {
+ "q": "shorts",
+ "doc_id": "1",
+ "user_id": "11"
+ }
+ })"_json;
+ req->body = event.dump();
+ ASSERT_TRUE(post_create_event(req, res));
+
+ auto popular_clicks = analyticsManager.get_popular_clicks();
+ ASSERT_EQ("popularity", popular_clicks["books"].counter_field);
+ ASSERT_EQ(1, popular_clicks["books"].docid_counts.size());
+ ASSERT_EQ(5, popular_clicks["books"].docid_counts["1"]);
+
+ //trigger persistance event manually
+ for (auto &popular_clicks_it: popular_clicks) {
+ std::string docs;
+ req->params["collection"] = popular_clicks_it.first;
+ req->params["action"] = "update";
+ popular_clicks_it.second.serialize_as_docs(docs);
+ req->body = docs;
+ post_import_documents(req, res);
+ }
+
+ sort_fields = {sort_by("popularity", "DESC")};
+ auto results = products_coll->search("*", {}, "", {},
+ sort_fields, {0}, 10, 1, FREQUENCY, {false},
+ Index::DROP_TOKENS_THRESHOLD, spp::sparse_hash_set<std::string>(),
+ spp::sparse_hash_set<std::string>()).get();
+
+ ASSERT_EQ(2, results["hits"].size());
+
+ ASSERT_EQ("1", results["hits"][0]["document"]["id"]);
+ ASSERT_EQ(5, results["hits"][0]["document"]["popularity"]);
+ ASSERT_EQ("Funky trousers", results["hits"][0]["document"]["title"]);
+
+ ASSERT_EQ("0", results["hits"][1]["document"]["id"]);
+ ASSERT_EQ(0, results["hits"][1]["document"]["popularity"]);
+ ASSERT_EQ("Cool trousers", results["hits"][1]["document"]["title"]);
+
+ //verify log file
+ analyticsManager.persist_events();
+
+ auto fileOutput = Config::fetch_file_contents("/tmp/typesense_test/analytics_manager_test/analytics_events.tsv");
+
+ std::stringstream strbuff(fileOutput.get());
+ std::string timestamp, collection, userid, name, q, docid;
+ strbuff >> timestamp >> name >> collection >> userid >> docid >> q;
+ ASSERT_EQ("CNV4", name);
+ ASSERT_EQ("books", collection);
+ ASSERT_EQ("11", userid);
+ ASSERT_EQ("1", docid);
+ ASSERT_EQ("shorts", q);
+
+ //now add click event rule
+ analytics_rule = R"({
+ "name": "book_click_events",
+ "type": "clicks",
+ "params": {
+ "name": "APC2",
+ "source": {
+ "collection": "books"
+ }
+ }
+ })"_json;
+
+ create_op = analyticsManager.create_rule(analytics_rule, true, true);
+ ASSERT_TRUE(create_op.ok());
+
+ event = R"({
+ "type": "click",
+ "name": "APC2",
+ "data": {
+ "q": "technology",
+ "doc_id": "21",
+ "user_id": "13"
+ }
+ })"_json;
+
+ req->body = event.dump();
+ ASSERT_TRUE(post_create_event(req, res));
+
+ //normal click event should not increment popularity score
+ popular_clicks = analyticsManager.get_popular_clicks();
+ ASSERT_EQ("popularity", popular_clicks["books"].counter_field);
+ ASSERT_EQ(1, popular_clicks["books"].docid_counts.size());
+ ASSERT_EQ(5, popular_clicks["books"].docid_counts["1"]);
+
+ //add another counter event
+ event = R"({
+ "type": "conversion",
+ "name": "CNV4",
+ "data": {
+ "q": "shorts",
+ "doc_id": "1",
+ "user_id": "11"
+ }
+ })"_json;
+ req->body = event.dump();
+ ASSERT_TRUE(post_create_event(req, res));
+
+ popular_clicks = analyticsManager.get_popular_clicks();
+ ASSERT_EQ(1, popular_clicks.size());
+ ASSERT_EQ("popularity", popular_clicks["books"].counter_field);
+ ASSERT_EQ(1, popular_clicks["books"].docid_counts.size());
+ ASSERT_EQ(10, popular_clicks["books"].docid_counts["1"]);
+
+ //check log file
+ analyticsManager.persist_events();
+
+ fileOutput = Config::fetch_file_contents("/tmp/typesense_test/analytics_manager_test/analytics_events.tsv");
+
+ std::stringstream strbuff2(fileOutput.get());
+ timestamp.clear(), collection.clear(), userid.clear(), name.clear(), q.clear(), docid.clear();
+ strbuff2 >> timestamp >> name >> collection >> userid >> docid >> q;
+ ASSERT_EQ("CNV4", name);
+ ASSERT_EQ("books", collection);
+ ASSERT_EQ("11", userid);
+ ASSERT_EQ("1", docid);
+ ASSERT_EQ("shorts", q);
+
+ timestamp.clear(), collection.clear(), userid.clear(), name.clear(), q.clear(), docid.clear();
+ strbuff2 >> timestamp >> name >> collection >> userid >> docid >> q;
+ ASSERT_EQ("APC2", name);
+ ASSERT_EQ("books", collection);
+ ASSERT_EQ("13", userid);
+ ASSERT_EQ("21", docid);
+ ASSERT_EQ("technology", q);
}
\ No newline at end of file