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

Return an error when per page param exceeds in-built limit.

kishorenc2dcd813c6d9a
diff --git a/src/collection.cpp b/src/collection.cpp
index dd8e0b40..2e7b30f2 100644
--- a/src/collection.cpp
+++ b/src/collection.cpp
@@ -338,7 +338,7 @@ void Collection::populate_overrides(std::string query,
Option<nlohmann::json> Collection::search(const std::string & query, const std::vector<std::string> & search_fields,
const std::string & simple_filter_query, const std::vector<std::string> & facet_fields,
const std::vector<sort_by> & sort_fields, const int num_typos,
- size_t per_page, const size_t page,
+ const size_t per_page, const size_t page,
const token_ordering token_order, const bool prefix,
const size_t drop_tokens_threshold,
const spp::sparse_hash_set<std::string> & include_fields,
@@ -599,8 +599,10 @@ Option<nlohmann::json> Collection::search(const std::string & query, const std::
return Option<nlohmann::json>(422, message);
}
- // ensure that per_page is limited to PER_PAGE_MAX for sanity
- per_page = std::min(per_page, PER_PAGE_MAX);
+ if(per_page > PER_PAGE_MAX) {
+ std::string message = "Only upto " + std::to_string(PER_PAGE_MAX) + " hits can be fetched per page.";
+ return Option<nlohmann::json>(422, message);
+ }
// ensure that (page * per_page) never exceeds number of documents in collection
const size_t max_hits = std::min((page * per_page), get_num_documents());
diff --git a/test/collection_test.cpp b/test/collection_test.cpp
index fd213703..6066da0a 100644
--- a/test/collection_test.cpp
+++ b/test/collection_test.cpp
@@ -2276,13 +2276,26 @@ TEST_F(CollectionTest, ReturnsResultsBasedOnPerPageParam) {
ASSERT_EQ(25, results["found"].get<int>());
// should match collection size
-
- results = collection->search("*", query_fields, "", facets, sort_fields, 0, 100000, 1,
+ results = collection->search("*", query_fields, "", facets, sort_fields, 0, 100, 1,
FREQUENCY, false, 1000, empty, empty, 10).get();
ASSERT_EQ(25, results["hits"].size());
ASSERT_EQ(25, results["found"].get<int>());
+ // cannot fetch more than in-built limit of 250
+ auto res_op = collection->search("*", query_fields, "", facets, sort_fields, 0, 251, 1,
+ FREQUENCY, false, 1000, empty, empty, 10);
+ ASSERT_FALSE(res_op.ok());
+ ASSERT_EQ(422, res_op.code());
+ ASSERT_STREQ("Only upto 250 hits can be fetched per page.", res_op.error().c_str());
+
+ // when page number is not valid
+ res_op = collection->search("*", query_fields, "", facets, sort_fields, 0, 10, 0,
+ FREQUENCY, false, 1000, empty, empty, 10);
+ ASSERT_FALSE(res_op.ok());
+ ASSERT_EQ(422, res_op.code());
+ ASSERT_STREQ("Page must be an integer of value greater than 0.", res_op.error().c_str());
+
// do pagination
results = collection->search("*", query_fields, "", facets, sort_fields, 0, 10, 1,