Skip to content

Commit

Permalink
Fix validation of subfields of flattened objects (#2088)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
jsoriano authored Sep 6, 2024
1 parent b838f0a commit fe16a06
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
5 changes: 3 additions & 2 deletions internal/fields/testdata/flattened.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"userName": "Bob",
"groupName": "admin"
}
}
},
"flattened.request_parameters.userID": 1000
}
}
}
18 changes: 18 additions & 0 deletions internal/fields/validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -681,6 +681,8 @@ func (v *Validator) validateScalarElement(key string, val any, doc common.MapStr
switch {
case skipValidationForField(key):
return nil // generic field, let's skip validation for now
case isFlattenedSubfield(key, v.Schema):
return nil // flattened subfield, it will be stored as member of the flattened ancestor.
case isArrayOfObjects(val):
return fmt.Errorf(`field %q is used as array of objects, expected explicit definition with type group or nested`, key)
case couldBeMultifield(key, v.Schema):
Expand Down Expand Up @@ -855,6 +857,22 @@ func isArrayOfObjects(val any) bool {
return false
}

func isFlattenedSubfield(key string, schema []FieldDefinition) bool {
for strings.Contains(key, ".") {
i := strings.LastIndex(key, ".")
key = key[:i]
ancestor := FindElementDefinition(key, schema)
if ancestor == nil {
continue
}
if ancestor.Type == "flattened" {
return true
}
}

return false
}

func findElementDefinitionForRoot(root, searchedKey string, fieldDefinitions []FieldDefinition) *FieldDefinition {
for _, def := range fieldDefinitions {
key := strings.TrimLeft(root+"."+def.Name, ".")
Expand Down

0 comments on commit fe16a06

Please sign in to comment.