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

Option fields can have a `null` value.

Kishore Nallane8dd34c1c3ad
diff --git a/src/index.cpp b/src/index.cpp
index 8c77988d..86f604bb 100644
--- a/src/index.cpp
+++ b/src/index.cpp
@@ -307,6 +307,12 @@ Option<uint32_t> Index::validate_index_in_memory(nlohmann::json& document, uint3
"but is not found in the document.");
}
+ if(a_field.optional && document[field_name].is_null()) {
+ // we will ignore `null` on an option field
+ document.erase(field_name);
+ continue;
+ }
+
nlohmann::json::iterator dummy_iter;
bool array_ele_erased = false;
diff --git a/test/collection_test.cpp b/test/collection_test.cpp
index c66944cc..df3c16bf 100644
--- a/test/collection_test.cpp
+++ b/test/collection_test.cpp
@@ -2592,6 +2592,46 @@ TEST_F(CollectionTest, OptionalFields) {
collectionManager.drop_collection("coll1");
}
+TEST_F(CollectionTest, OptionalFieldCanBeNull) {
+ Collection *coll1;
+
+ std::vector<field> fields = {field("title", field_types::STRING, false),
+ field("artist", field_types::STRING, false, true),
+ field("genres", field_types::STRING_ARRAY, false, true),
+ field("launch_year", field_types::INT32, false, true),
+ field("updated_at", field_types::INT64, false, true),
+ field("points", field_types::INT32, false),};
+
+ coll1 = collectionManager.get_collection("coll1").get();
+ if(coll1 == nullptr) {
+ coll1 = collectionManager.create_collection("coll1", 4, fields, "points").get();
+ }
+
+ nlohmann::json doc;
+
+ doc["id"] = "0";
+ doc["title"] = "Beat it";
+ doc["artist"] = nullptr;
+ doc["genres"] = nullptr;
+ doc["launch_year"] = nullptr;
+ doc["updated_at"] = nullptr;
+ doc["points"] = 100;
+
+ ASSERT_TRUE(coll1->add(doc.dump()).ok());
+
+ ASSERT_EQ(2, coll1->_get_indexes()[0]->_get_search_index().at("title")->size);
+ ASSERT_EQ(0, coll1->_get_indexes()[0]->_get_search_index().at("artist")->size);
+ ASSERT_EQ(0, coll1->_get_indexes()[0]->_get_search_index().at("genres")->size);
+
+ auto results = coll1->search("beat",
+ {"title", "artist"}, "", {}, {}, 0, 10, 1, FREQUENCY).get();
+
+ ASSERT_EQ(1, results["found"].get<size_t>());
+ ASSERT_EQ(1, results["hits"].size());
+
+ collectionManager.drop_collection("coll1");
+}
+
TEST_F(CollectionTest, WildcardQueryReturnsResultsBasedOnPerPageParam) {
std::vector<std::string> facets;
spp::sparse_hash_set<std::string> empty;