Skip to content

Commit fe16a06

Browse files
authored
Fix validation of subfields of flattened objects (#2088)
When a document doesn't has subobjects, like when using `subobjects: false or synthetic mode, if an undocumented field is found, we need to check its ancestors to see if it is a member of a flattened object.
1 parent b838f0a commit fe16a06

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

internal/fields/testdata/flattened.json

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
"userName": "Bob",
77
"groupName": "admin"
88
}
9-
}
9+
},
10+
"flattened.request_parameters.userID": 1000
1011
}
11-
}
12+
}

internal/fields/validate.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -681,6 +681,8 @@ func (v *Validator) validateScalarElement(key string, val any, doc common.MapStr
681681
switch {
682682
case skipValidationForField(key):
683683
return nil // generic field, let's skip validation for now
684+
case isFlattenedSubfield(key, v.Schema):
685+
return nil // flattened subfield, it will be stored as member of the flattened ancestor.
684686
case isArrayOfObjects(val):
685687
return fmt.Errorf(`field %q is used as array of objects, expected explicit definition with type group or nested`, key)
686688
case couldBeMultifield(key, v.Schema):
@@ -855,6 +857,22 @@ func isArrayOfObjects(val any) bool {
855857
return false
856858
}
857859

860+
func isFlattenedSubfield(key string, schema []FieldDefinition) bool {
861+
for strings.Contains(key, ".") {
862+
i := strings.LastIndex(key, ".")
863+
key = key[:i]
864+
ancestor := FindElementDefinition(key, schema)
865+
if ancestor == nil {
866+
continue
867+
}
868+
if ancestor.Type == "flattened" {
869+
return true
870+
}
871+
}
872+
873+
return false
874+
}
875+
858876
func findElementDefinitionForRoot(root, searchedKey string, fieldDefinitions []FieldDefinition) *FieldDefinition {
859877
for _, def := range fieldDefinitions {
860878
key := strings.TrimLeft(root+"."+def.Name, ".")

0 commit comments

Comments
 (0)