Merge pull request #4122 from opencloud-eu/fix/search-typed-field-values

fix(search): answer text on numeric and date fields the same on both engines
This commit is contained in:
Florian Schade authored and GitHub committed 2026-11-25 11:31:44 +01:00
commit 98b9dec0f3
11 files changed
+224 -51

No files matched your search

+11 -28
View File
@@ -35,34 +35,17 @@ func FieldNameIndex(t reflect.Type, overrides map[string]FieldOpts) map[string]s
return out
}
// NumericFields lists the fields of t (json names, nested as parent.child) that
// both backends index as numbers, so a range restriction can target them. The
// parts of a geopoint are not numbers of their own.
func NumericFields(t reflect.Type, overrides map[string]FieldOpts) map[string]struct{} {
out := map[string]struct{}{}
var walk func(t reflect.Type, prefix string)
walk = func(t reflect.Type, prefix string) {
_ = walkFields(t, func(fi fieldInfo) error {
name := fi.Name
if prefix != "" {
name = prefix + "." + fi.Name
}
fieldType := overrides[name].Type
if fieldType == "" {
fieldType = inferType(fi.GoField.Type)
}
switch fieldType {
case TypeNumeric:
out[name] = struct{}{}
case TypeObject:
if sub := structType(fi.GoField.Type); sub != nil {
walk(sub, name)
}
}
return nil
})
// FieldTypes maps every field of t (nested as "parent.child") to its effective
// mapping type: the override when there is one, the type inferred from the Go
// type otherwise.
func FieldTypes(t reflect.Type, overrides map[string]FieldOpts) map[string]string {
out := map[string]string{}
for key, goType := range collectFields(t, "") {
fieldType := overrides[key].Type
if fieldType == "" {
fieldType = inferType(goType)
}
out[key] = fieldType
}
walk(t, "")
return out
}
@@ -117,6 +117,22 @@ func (t kqlOpensearchTranspiler) toBuilder(node ast.Node) (osu.Builder, error) {
return osu.NewTermQuery[bool](node.Key).Value(b), nil
}
// a numeric field takes a number, which : and = both match as a whole.
// Anything else matches nothing instead of failing the search:
// size:>100 is the value ">100" and not the range size>100
if query.FieldIsNumeric(node.Key) {
v, ok := query.ParseNumber(node.Value)
if !ok {
return osu.NewMatchNoneQuery(), nil
}
return osu.NewTermQuery[float64](node.Key).Value(v), nil
}
// a date arrives as a date node, text on a date field is none
if query.FieldIsDatetime(node.Key) {
return osu.NewMatchNoneQuery(), nil
}
field, value := node.Key, node.Value
if node.CaseInsensitive {
field += mapping.LowercaseSuffix
@@ -51,6 +51,33 @@ func TestTranspileKQLToOpenSearch(t *testing.T) {
},
Want: osu.NewWildcardQuery("Name_lowercase").Value(`*"a"\\b*`),
},
{
Name: "a numeric field takes a number",
Got: &ast.Ast{
Nodes: []ast.Node{
&ast.StringNode{Key: "Size", Value: "50", Exact: true},
},
},
Want: osu.NewTermQuery[float64]("Size").Value(50),
},
{
Name: "a colon before the comparison is no number and matches nothing",
Got: &ast.Ast{
Nodes: []ast.Node{
&ast.StringNode{Key: "Size", Value: ">100"},
},
},
Want: osu.NewMatchNoneQuery(),
},
{
Name: "text on a date field matches nothing",
Got: &ast.Ast{
Nodes: []ast.Node{
&ast.StringNode{Key: "Mtime", Value: ">2021-01-01"},
},
},
Want: osu.NewMatchNoneQuery(),
},
{
Name: "full-text field uses an analyzed match query, not an unanalyzed term",
Got: &ast.Ast{
+20
View File
@@ -291,6 +291,9 @@ Fixtures:
| FIELDS-13 | `audio.artist:"Some Artist"` | song.mp3 | song.mp3 | song.mp3 | ✅ |
| FIELDS-14 | `audio.artist:"some artist"` | song.mp3 | song.mp3 | song.mp3 | ✅ |
| FIELDS-15 | `audio.duration>100` | song.mp3 | song.mp3 | song.mp3 | ✅ |
| FIELDS-16 | `type:banana` | no match | no match | no match | ✅ |
| FIELDS-17 | `audio.duration:200` | song.mp3 | song.mp3 | song.mp3 | ✅ |
| FIELDS-18 | `audio.duration:long` | no match | no match | no match | ✅ |
### deleted
@@ -443,6 +446,21 @@ Fixtures:
| RANGE-06 | `Mtime:"yesterday"` | no match | no match | no match | ✅ |
| RANGE-07 | `mtime>2021` | no match | no match | no match | ✅ |
| RANGE-08 | `name>100` | no match | no match | no match | ✅ |
| RANGE-09 | `size>=50` | big.txt, small.txt | big.txt, small.txt | big.txt, small.txt | ✅ |
| RANGE-10 | `size<=50` | ancient.txt, small.txt | ancient.txt, small.txt | ancient.txt, small.txt | ✅ |
| RANGE-11 | `size>100 AND size<1000` | big.txt | big.txt | big.txt | ✅ |
| RANGE-12 | `mtime>=2021-01-01` | big.txt, small.txt | big.txt, small.txt | big.txt, small.txt | ✅ |
| RANGE-13 | `size:50` | small.txt | small.txt | small.txt | ✅ |
| RANGE-14 | `size=50` | small.txt | small.txt | small.txt | ✅ |
| RANGE-15 | `size:1.5` | no match | no match | no match | ✅ |
| RANGE-16 | `size:5*` | no match | no match | no match | ✅ |
| RANGE-17 | `size:>100` | no match | no match | no match | ✅ |
| RANGE-18 | `size:<100` | no match | no match | no match | ✅ |
| RANGE-19 | `size:>=100` | no match | no match | no match | ✅ |
| RANGE-20 | `mtime:>"2021-01-01T00:00:00Z"` | no match | no match | no match | ✅ |
| RANGE-21 | `mtime:>2021-01-01` | no match | no match | no match | ✅ |
| RANGE-22 | `size:50..500` | no match | no match | no match | ✅ |
| RANGE-23 | `mtime:2019-01-01..2020-12-31` | no match | no match | no match | ✅ |
### photo
@@ -460,6 +478,8 @@ Fixtures:
| PHOTO-04 | `photo.orientation>1` | dark.jpg | dark.jpg | dark.jpg | ✅ |
| PHOTO-05 | `photo.iso<=100` | bright.jpg | bright.jpg | bright.jpg | ✅ |
| PHOTO-06 | `photo.cameraMake>1` | no match | no match | no match | ✅ |
| PHOTO-07 | `location.altitude>1000` | bright.jpg | bright.jpg | bright.jpg | ✅ |
| PHOTO-08 | `location.latitude<49` | no match | no match | no match | ✅ |
### extraction
@@ -37,6 +37,9 @@ func fieldsGroup() queryGroup {
{id: 13, query: `audio.artist:"Some Artist"`, want: []string{"song.mp3"}},
{id: 14, query: `audio.artist:"some artist"`, want: []string{"song.mp3"}}, // facets search case-insensitively
{id: 15, query: `audio.duration>100`, want: []string{"song.mp3"}},
{id: 16, query: `type:banana`},
{id: 17, query: `audio.duration:200`, want: []string{"song.mp3"}},
{id: 18, query: `audio.duration:long`},
},
}
}
@@ -10,7 +10,7 @@ func photoGroup() queryGroup {
return queryGroup{
name: "photo",
fixtures: []search.Resource{
fixtureDoc("bright.jpg", withMime("image/jpeg"), withPhoto(&libregraph.Photo{CameraMake: libregraph.PtrString("Acme"), Iso: libregraph.PtrInt32(100), FNumber: libregraph.PtrFloat64(1.8), FocalLength: libregraph.PtrFloat64(26), Orientation: libregraph.PtrInt32(1)})),
fixtureDoc("bright.jpg", withMime("image/jpeg"), withPhoto(&libregraph.Photo{CameraMake: libregraph.PtrString("Acme"), Iso: libregraph.PtrInt32(100), FNumber: libregraph.PtrFloat64(1.8), FocalLength: libregraph.PtrFloat64(26), Orientation: libregraph.PtrInt32(1)}), withLocation(&libregraph.GeoCoordinates{Altitude: libregraph.PtrFloat64(1047.7), Latitude: libregraph.PtrFloat64(49.5), Longitude: libregraph.PtrFloat64(11.1)})),
fixtureDoc("dark.jpg", withMime("image/jpeg"), withPhoto(&libregraph.Photo{Iso: libregraph.PtrInt32(3200), FNumber: libregraph.PtrFloat64(4), FocalLength: libregraph.PtrFloat64(85), Orientation: libregraph.PtrInt32(6)})),
fixtureDoc("plain.txt"),
},
@@ -21,6 +21,9 @@ func photoGroup() queryGroup {
{id: 4, query: `photo.orientation>1`, want: []string{"dark.jpg"}},
{id: 5, query: `photo.iso<=100`, want: []string{"bright.jpg"}},
{id: 6, query: `photo.cameraMake>1`}, // a text field takes no range
// the parts of a location are numbers next to the geopoint
{id: 7, query: `location.altitude>1000`, want: []string{"bright.jpg"}},
{id: 8, query: `location.latitude<49`},
},
}
}
@@ -21,6 +21,25 @@ func rangeGroup() queryGroup {
{id: 6, query: `Mtime:"yesterday"`},
{id: 7, query: `mtime>2021`},
{id: 8, query: `name>100`},
{id: 9, query: `size>=50`, want: []string{"small.txt", "big.txt"}},
{id: 10, query: `size<=50`, want: []string{"small.txt", "ancient.txt"}},
{id: 11, query: `size>100 AND size<1000`, want: []string{"big.txt"}},
{id: 12, query: `mtime>=2021-01-01`, want: []string{"small.txt", "big.txt"}},
// a number on a numeric field matches as a whole, with : and with =
{id: 13, query: `size:50`, want: []string{"small.txt"}},
{id: 14, query: `size=50`, want: []string{"small.txt"}},
{id: 15, query: `size:1.5`},
{id: 16, query: `size:5*`},
// not KQL: a colon before the comparison makes it the text ">100",
// which no number is. Old iOS clients send this form.
{id: 17, query: `size:>100`},
{id: 18, query: `size:<100`},
{id: 19, query: `size:>=100`},
{id: 20, query: `mtime:>"2021-01-01T00:00:00Z"`},
{id: 21, query: `mtime:>2021-01-01`},
// the KQL range operator .. is not supported
{id: 22, query: `size:50..500`},
{id: 23, query: `mtime:2019-01-01..2020-12-31`},
},
}
}
+33 -10
View File
@@ -98,16 +98,8 @@ func walk(offset int, nodes []ast.Node) (bleveQuery.Query, int, error) {
for i := offset; i < len(nodes); i++ {
switch n := nodes[i].(type) {
case *ast.StringNode:
// hidden takes bool words only; anything else matches nothing
if n.Key == "Hidden" {
var q bleveQuery.Query
if b, err := strconv.ParseBool(n.Value); err == nil {
bq := bleveQuery.NewBoolFieldQuery(b)
bq.SetField(n.Key)
q = bq
} else {
q = bleveQuery.NewMatchNoneQuery()
}
// a field that is not text takes values of its own type only
if q := typedFieldQuery(n); q != nil {
if prev == nil {
prev = q
} else {
@@ -343,6 +335,37 @@ func mapBinary(operator *ast.OperatorNode, ln, rn bleveQuery.Query, leftIsGroup
})
}
// typedFieldQuery answers a text restriction on a field that is not text; nil
// for every other field. Hidden takes bool words and a numeric field takes a
// number, which : and = both match as a whole. A date arrives as a date node,
// so text on a date field is none. Anything else matches nothing, the same
// answer the OpenSearch backend gives: size:>100 is the value ">100" on a
// numeric field and not the range size>100.
func typedFieldQuery(n *ast.StringNode) bleveQuery.Query {
switch {
case n.Key == "Hidden":
b, err := strconv.ParseBool(n.Value)
if err != nil {
return bleveQuery.NewMatchNoneQuery()
}
q := bleveQuery.NewBoolFieldQuery(b)
q.SetField(n.Key)
return q
case searchQuery.FieldIsNumeric(n.Key):
v, ok := searchQuery.ParseNumber(n.Value)
if !ok {
return bleveQuery.NewMatchNoneQuery()
}
inclusive := true
q := bleveQuery.NewNumericRangeInclusiveQuery(&v, &v, &inclusive, &inclusive)
q.SetField(n.Key)
return q
case searchQuery.FieldIsDatetime(n.Key):
return bleveQuery.NewMatchNoneQuery()
}
return nil
}
func numberRange(field string, operator *ast.OperatorNode, value float64) bleveQuery.Query {
if operator == nil {
return nil
@@ -33,6 +33,14 @@ func boolFieldQuery(field string, value bool) query.Query {
return q
}
func numberQuery(field string, value float64) query.Query {
inclusive := true
q := query.NewNumericRangeInclusiveQuery(&value, &value, &inclusive, &inclusive)
q.SetField(field)
return q
}
func Test_compile(t *testing.T) {
tests := []struct {
name string
@@ -329,6 +337,30 @@ func Test_compile(t *testing.T) {
}),
wantErr: false,
},
{
name: `a numeric field takes a number, anything else matches nothing`,
args: &ast.Ast{
Nodes: []ast.Node{
&ast.StringNode{Key: "size", Value: "50"},
&ast.OperatorNode{Value: "OR"},
&ast.StringNode{Key: "size", Value: "50", Exact: true},
&ast.OperatorNode{Value: "OR"},
&ast.StringNode{Key: "size", Value: ">100"},
&ast.OperatorNode{Value: "OR"},
&ast.StringNode{Key: "size", Value: "50..500"},
&ast.OperatorNode{Value: "OR"},
&ast.StringNode{Key: "mtime", Value: ">2021-01-01"},
},
},
want: query.NewDisjunctionQuery([]query.Query{
numberQuery("Size", 50),
numberQuery("Size", 50),
query.NewMatchNoneQuery(),
query.NewMatchNoneQuery(),
query.NewMatchNoneQuery(),
}),
wantErr: false,
},
{
name: `NOT tag:physik`,
args: &ast.Ast{
@@ -53,6 +53,36 @@ var _ = Describe("FieldIsWordBroken", func() {
})
})
var _ = Describe("FieldIsNumeric and FieldIsDatetime", func() {
It("report the field type, facets included", func() {
for _, f := range []string{"Size", "Type", "audio.duration", "photo.iso", "location.altitude"} {
Expect(query.FieldIsNumeric(f)).To(BeTrue(), f)
Expect(query.FieldIsDatetime(f)).To(BeFalse(), f)
}
Expect(query.FieldIsDatetime("Mtime")).To(BeTrue())
for _, f := range []string{"Name", "Tags", "Hidden", "Content", "Path", "unknown"} {
Expect(query.FieldIsNumeric(f)).To(BeFalse(), f)
Expect(query.FieldIsDatetime(f)).To(BeFalse(), f)
}
})
})
var _ = DescribeTable("ParseNumber",
func(value string, want float64, wantOK bool) {
got, ok := query.ParseNumber(value)
Expect(ok).To(Equal(wantOK))
Expect(got).To(Equal(want))
},
Entry("an integer", "50", 50.0, true),
Entry("a decimal", "1.5", 1.5, true),
Entry("a comparison", ">100", 0.0, false),
Entry("a range", "50..500", 0.0, false),
Entry("a wildcard", "5*", 0.0, false),
Entry("a word", "long", 0.0, false),
Entry("not a finite number", "NaN", 0.0, false),
Entry("nothing", "", 0.0, false),
)
var _ = Describe("Normalize", func() {
It("resolves fields and expands mediatype", func() {
got := norm(
+29 -12
View File
@@ -1,7 +1,9 @@
package query
import (
"math"
"reflect"
"strconv"
"strings"
"sync"
@@ -33,6 +35,12 @@ var siblingFields = sync.OnceValue(func() map[string]mapping.Siblings {
return mapping.SearchSiblings(reflect.TypeFor[search.Resource](), search.Resource{}.SearchFieldOverrides())
})
// fieldTypes holds the mapping type of every field, from the resource struct
// and its overrides.
var fieldTypes = sync.OnceValue(func() map[string]string {
return mapping.FieldTypes(reflect.TypeFor[search.Resource](), search.Resource{}.SearchFieldOverrides())
})
// pathFields are hierarchical path fields (TypePath), derived from the overrides.
var pathFields = sync.OnceValue(func() map[string]struct{} {
out := map[string]struct{}{}
@@ -85,18 +93,6 @@ func FieldIsCaseInsensitive(field string) bool {
return siblingFields()[field].Lowercase
}
// numericFields are the fields indexed as numbers, derived from the resource struct.
var numericFields = sync.OnceValue(func() map[string]struct{} {
return mapping.NumericFields(reflect.TypeFor[search.Resource](), search.Resource{}.SearchFieldOverrides())
})
// FieldIsNumeric reports whether a field is indexed as a number, so a range
// restriction can target it.
func FieldIsNumeric(field string) bool {
_, ok := numericFields()[field]
return ok
}
// FieldIsPath reports whether a field is a hierarchical path field.
func FieldIsPath(field string) bool {
_, ok := pathFields()[field]
@@ -114,3 +110,24 @@ func FieldIsFulltext(field string) bool {
func FieldIsWordBroken(field string) bool {
return siblingFields()[field].Words
}
// FieldIsNumeric reports whether a field is indexed as a number, so a range
// restriction can target it.
func FieldIsNumeric(field string) bool {
return fieldTypes()[field] == mapping.TypeNumeric
}
// FieldIsDatetime reports whether a field holds a point in time.
func FieldIsDatetime(field string) bool {
return fieldTypes()[field] == mapping.TypeDatetime
}
// ParseNumber reads the value of a restriction on a numeric field. ok is false
// for anything but a finite number, ">100" and "50..500" included.
func ParseNumber(value string) (float64, bool) {
v, err := strconv.ParseFloat(value, 64)
if err != nil || math.IsNaN(v) || math.IsInf(v, 0) {
return 0, false
}
return v, true
}