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

Allow null values for optional nested fields.

Kishore Nallan057939899331
diff --git a/src/field.cpp b/src/field.cpp
index fb334dc4..97e385af 100644
--- a/src/field.cpp
+++ b/src/field.cpp
@@ -721,6 +721,11 @@ Option<bool> field::flatten_field(nlohmann::json& doc, nlohmann::json& obj, cons
// end of path: check if obj matches expected type
std::string detected_type;
if(!field::get_type(obj, detected_type)) {
+ if(obj.is_null() && the_field.optional) {
+ // null values are allowed only if field is optional
+ return Option<bool>(false);
+ }
+
return Option<bool>(400, "Field `" + the_field.name + "` has an incorrect type.");
}
diff --git a/test/collection_nested_fields_test.cpp b/test/collection_nested_fields_test.cpp
index 2fa978e5..997026a7 100644
--- a/test/collection_nested_fields_test.cpp
+++ b/test/collection_nested_fields_test.cpp
@@ -1390,7 +1390,8 @@ TEST_F(CollectionNestedFieldsTest, ExplicitSchemaOptionalFieldValidation) {
"fields": [
{"name": "details", "type": "object", "optional": true },
{"name": "company.name", "type": "string", "optional": true },
- {"name": "locations", "type": "object[]", "optional": true }
+ {"name": "locations", "type": "object[]", "optional": true },
+ {"name": "blocks.text.description", "type": "string[]", "optional": true }
]
})"_json;
@@ -1398,14 +1399,31 @@ TEST_F(CollectionNestedFieldsTest, ExplicitSchemaOptionalFieldValidation) {
ASSERT_TRUE(op.ok());
Collection* coll1 = op.get();
- // no optional field is present and that should be allowed
+ // when a nested field is null it should be allowed
auto doc1 = R"({
- "foo": "bar"
+ "company": {"name": null}
})"_json;
auto add_op = coll1->add(doc1.dump(), CREATE);
ASSERT_TRUE(add_op.ok());
+ // check the same with nested array type
+
+ doc1 = R"({
+ "blocks": {"text": [{"description": null}]}
+ })"_json;
+
+ add_op = coll1->add(doc1.dump(), CREATE);
+ ASSERT_TRUE(add_op.ok());
+
+ // no optional field is present and that should be allowed
+ doc1 = R"({
+ "foo": "bar"
+ })"_json;
+
+ add_op = coll1->add(doc1.dump(), CREATE);
+ ASSERT_TRUE(add_op.ok());
+
// some parts of an optional field is present in a subsequent doc indexed
auto doc2 = R"({
"details": {"name": "foo"}
@@ -1421,7 +1439,7 @@ TEST_F(CollectionNestedFieldsTest, ExplicitSchemaOptionalFieldValidation) {
// check fields and their properties
auto coll_fields = coll1->get_fields();
- ASSERT_EQ(5, coll_fields.size());
+ ASSERT_EQ(6, coll_fields.size());
for(auto& coll_field : coll_fields) {
ASSERT_TRUE(coll_field.optional);
}