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

Add guard for non-indexed default sorting field.

Kishore Nallanbaa74ba467a9
diff --git a/src/collection.cpp b/src/collection.cpp
index cad52e5e..ddaafe2e 100644
--- a/src/collection.cpp
+++ b/src/collection.cpp
@@ -1475,6 +1475,12 @@ Option<bool> Collection::validate_and_standardize_sort_fields(const std::vector<
}
if(!default_sorting_field.empty()) {
+ auto def_it = search_schema.find(default_sorting_field);
+ if(def_it == search_schema.end() || !def_it->index) {
+ return Option<bool>(400, "Default sorting field not found in the schema or it has been marked as a "
+ "non-indexed field.");
+ }
+
sort_fields_std.emplace_back(default_sorting_field, sort_field_const::desc);
} else {
sort_fields_std.emplace_back(sort_field_const::seq_id, sort_field_const::desc);
diff --git a/test/collection_sorting_test.cpp b/test/collection_sorting_test.cpp
index 9bf3e5d2..ab6d6584 100644
--- a/test/collection_sorting_test.cpp
+++ b/test/collection_sorting_test.cpp
@@ -1985,6 +1985,29 @@ TEST_F(CollectionSortingTest, WildcardSearchSequenceIdSort) {
ASSERT_EQ(30, res["found"].get<size_t>());
}
+TEST_F(CollectionSortingTest, DefaultSortingFieldNotIndexed) {
+ nlohmann::json schema = R"({
+ "name": "coll1",
+ "fields": [
+ {"name": "category", "type": "string", "sort": true, "index": false}
+ ],
+ "default_sorting_field": "category"
+ })"_json;
+
+ Collection* coll1 = collectionManager.create_collection(schema).get();
+
+ nlohmann::json doc;
+ doc["category"] = "Shoes";
+ ASSERT_TRUE(coll1->add(doc.dump()).ok());
+
+ std::vector<sort_by> sort_fields = {};
+
+ auto res_op = coll1->search("*", {}, "", {}, sort_fields, {2}, 10, 1, FREQUENCY, {true}, 0);
+ ASSERT_FALSE(res_op.ok());
+ ASSERT_EQ("Default sorting field not found in the schema or it has been marked as a "
+ "non-indexed field.", res_op.error());
+}
+
TEST_F(CollectionSortingTest, OptionalFilteringViaSortingWildcard) {
std::string coll_schema = R"(
{