Files
opencloud/services/search/pkg/query/bleve/compiler.go
T
Dominik Schmidt c3a08d88da fix(search): answer text on numeric and date fields the same on both engines
A text restriction on a numeric field reached the engines as is. bleve found nothing for size:>100 or size:50..500, OpenSearch failed the search with a number format exception. size=50 only matched on OpenSearch.

Both engines now read the value of such a restriction as a number and match it as a whole, with : and with =. Anything that is no number matches nothing, and so does text on a date field. size:>100 is not KQL, the range form is size>100; old iOS clients still send the colon form.

The field type comes from one table of all fields, built from the walk the mapping validation uses. It replaces the separate walk for numeric fields, which left out the parts of a location: location.altitude>1000 now matches, the parts are indexed as numbers next to the geopoint.

The parity suite covers >=, <=, combined ranges, number equality, the colon forms and the location parts.
2026-11-25 10:58:30 +01:00

394 lines
11 KiB
Go

package bleve
import (
"fmt"
"strconv"
"strings"
"github.com/blevesearch/bleve/v2"
bleveQuery "github.com/blevesearch/bleve/v2/search/query"
"github.com/opencloud-eu/opencloud/pkg/ast"
"github.com/opencloud-eu/opencloud/pkg/kql"
"github.com/opencloud-eu/opencloud/services/search/pkg/mapping"
searchQuery "github.com/opencloud-eu/opencloud/services/search/pkg/query"
)
// The following quoted string enumerates the characters which may be escaped: "+-=&|><!(){}[]^\"~*?:\\/ "
// based on bleve docs https://blevesearch.com/docs/Query-String-Query/
// Wildcards * and ? are excluded. So is /, it is a plain character in a term
// and escaping it would not keep a value wrapped in slashes from being read as
// a regular expression, see fieldQuery.
var bleveEscaper = strings.NewReplacer(
`+`, `\+`,
`-`, `\-`,
`=`, `\=`,
`&`, `\&`,
`|`, `\|`,
`>`, `\>`,
`<`, `\<`,
`!`, `\!`,
`(`, `\(`,
`)`, `\)`,
`{`, `\{`,
`}`, `\}`,
`[`, `\[`,
`]`, `\]`,
`^`, `\^`,
`"`, `\"`,
`~`, `\~`,
`:`, `\:`,
`\`, `\\`,
` `, `\ `,
)
// phraseEscaper escapes a value for a quoted bleve phrase, where only the
// quote and the backslash are special
var phraseEscaper = strings.NewReplacer(
`\`, `\\`,
`"`, `\"`,
)
// fieldQuery matches value on field through the query string field:value, so
// a value with * or ? is a wildcard and a number also matches a numeric field.
// A query string can't carry an empty value, and it reads a value wrapped in
// slashes as a regular expression whether escaped or not; those two get the
// match or wildcard query the string stands for built directly.
func fieldQuery(field, value string) bleveQuery.Query {
if value != "" && !(strings.HasPrefix(value, "/") && strings.HasSuffix(value, "/")) {
return bleveQuery.NewQueryStringQuery(field + ":" + bleveEscaper.Replace(value))
}
var q bleveQuery.FieldableQuery = bleveQuery.NewMatchQuery(value)
if strings.ContainsAny(value, "*?") {
q = bleveQuery.NewWildcardQuery(value)
}
q.SetField(field)
return q
}
// Compiler represents a KQL query search string to the bleve query formatter.
type Compiler struct{}
// Compile implements the query formatter which converts the KQL query search string to the bleve query.
func (c Compiler) Compile(givenAst *ast.Ast) (bleveQuery.Query, error) {
q, err := compile(givenAst)
if err != nil {
return nil, err
}
return q, nil
}
func compile(a *ast.Ast) (bleveQuery.Query, error) {
q, _, err := walk(0, a.Nodes)
if err != nil {
return nil, err
}
switch q.(type) {
case *bleveQuery.ConjunctionQuery, *bleveQuery.DisjunctionQuery:
return q, nil
}
return bleve.NewConjunctionQuery(q), nil
}
func walk(offset int, nodes []ast.Node) (bleveQuery.Query, int, error) {
var prev, next bleveQuery.Query
var operator *ast.OperatorNode
var isGroup bool
for i := offset; i < len(nodes); i++ {
switch n := nodes[i].(type) {
case *ast.StringNode:
// 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 {
next = q
}
break
}
// keys are resolved and media-type expanded by normalize
val := n.Value
k := n.Key
if n.CaseInsensitive {
k += mapping.LowercaseSuffix
val = strings.ToLower(val)
}
isWildcard := strings.ContainsAny(val, "*?")
var q bleveQuery.Query
switch {
case searchQuery.FieldIsPath(n.Key) && !isWildcard:
// the folder term matches the folder itself and its descendants
// (see PathAnalyzer); a query string would analyze the value into
// its prefixes and match everything under the root
tq := bleveQuery.NewTermQuery(val)
tq.SetField(k)
q = tq
case n.Exact && !isWildcard:
// = matches the whole value, on the lowercased sibling for
// case-insensitive fields
tq := bleveQuery.NewTermQuery(val)
tq.SetField(k)
q = tq
case searchQuery.FieldIsWordBroken(n.Key) && !isWildcard:
// a word-broken field matches the value as a phrase of its words on the
// _words sibling (a quoted query string term is a match phrase query
// run through the field's analyzer); wildcards stay on _lowercase.
q = bleveQuery.NewQueryStringQuery(n.Key + mapping.WordsSuffix + `:"` + phraseEscaper.Replace(val) + `"`)
case searchQuery.FieldIsFulltext(n.Key) && !isWildcard:
// a fulltext field is its own words field, the phrase runs on it
q = bleveQuery.NewQueryStringQuery(k + `:"` + phraseEscaper.Replace(val) + `"`)
case isWildcard && searchQuery.FieldIsWordBroken(n.Key) && !strings.HasSuffix(val, "*"):
// a wildcard on a word-broken field forgives a missing extension:
// *report also matches Report.txt
bq := bleve.NewBooleanQuery()
bq.AddShould(fieldQuery(k, val), fieldQuery(k, val+".*"))
bq.SetMinShould(1)
q = bq
default:
q = fieldQuery(k, val)
}
if prev == nil {
prev = q
} else {
next = q
}
case *ast.DateTimeNode:
q := &bleveQuery.DateRangeQuery{
Start: bleveQuery.BleveQueryTime{},
End: bleveQuery.BleveQueryTime{},
InclusiveStart: nil,
InclusiveEnd: nil,
FieldVal: n.Key,
}
if n.Operator == nil {
continue
}
switch n.Operator.Value {
case ">":
q.Start.Time = n.Value
q.InclusiveStart = &[]bool{false}[0]
case ">=":
q.Start.Time = n.Value
q.InclusiveStart = &[]bool{true}[0]
case "<":
q.End.Time = n.Value
q.InclusiveEnd = &[]bool{false}[0]
case "<=":
q.End.Time = n.Value
q.InclusiveEnd = &[]bool{true}[0]
default:
continue
}
if prev == nil {
prev = q
} else {
next = q
}
case *ast.NumberNode:
var q bleveQuery.Query
if field := n.Key; searchQuery.FieldIsNumeric(field) {
q = numberRange(field, n.Operator, n.Value)
} else {
// same answer as the OpenSearch backend: a range on a non-numeric key
// matches nothing instead of querying an arbitrary field
q = bleveQuery.NewMatchNoneQuery()
}
if q == nil {
continue
}
if prev == nil {
prev = q
} else {
next = q
}
case *ast.BooleanNode:
q := bleveQuery.NewBoolFieldQuery(n.Value)
q.SetField(n.Key)
if prev == nil {
prev = q
} else {
next = q
}
case *ast.GroupNode:
// keys resolved and grouping property propagated in normalize
q, _, err := walk(0, n.Nodes)
if err != nil {
return nil, 0, err
}
if prev == nil {
prev = q
isGroup = true
} else {
next = q
}
case *ast.OperatorNode:
if n.Value == kql.BoolAND || n.Value == kql.BoolOR {
operator = n
} else if n.Value == kql.BoolNOT {
var err error
next, offset, err = nextNode(i+1, nodes)
if err != nil {
return nil, 0, err
}
q := bleve.NewBooleanQuery()
q.AddMustNot(next)
if prev == nil {
// unary at the beginning: the term was consumed into the
// MustNot via nextNode, so clear next, otherwise a following
// operator would bind the stale term (NOT x AND y drops y).
prev = q
next = nil
} else {
next = q
}
}
}
if prev != nil && next != nil && operator != nil {
prev = mapBinary(operator, prev, next, isGroup)
isGroup = false
operator = nil
next = nil
}
if i < offset {
i = offset
}
}
if prev == nil {
return nil, 0, fmt.Errorf("can not compile the query")
}
return prev, offset, nil
}
func nextNode(offset int, nodes []ast.Node) (bleveQuery.Query, int, error) {
if offset >= len(nodes) {
return nil, 0, fmt.Errorf("operator without an operand")
}
if n, ok := nodes[offset].(*ast.GroupNode); ok {
// keys are resolved and group keys propagated by normalize
gq, _, err := walk(0, n.Nodes)
if err != nil {
return nil, 0, err
}
return gq, offset + 1, nil
}
if n, ok := nodes[offset].(*ast.OperatorNode); ok {
if n.Value == kql.BoolNOT {
return walk(offset, nodes)
}
}
one := nodes[:offset+1]
return walk(offset, one)
}
func mapBinary(operator *ast.OperatorNode, ln, rn bleveQuery.Query, leftIsGroup bool) bleveQuery.Query {
if operator.Value == kql.BoolOR {
right, ok := rn.(*bleveQuery.DisjunctionQuery)
switch left := ln.(type) {
case *bleveQuery.DisjunctionQuery:
if ok {
left.AddQuery(right.Disjuncts...)
} else {
left.AddQuery(rn)
}
return left
case *bleveQuery.ConjunctionQuery:
return bleveQuery.NewDisjunctionQuery([]bleveQuery.Query{ln, rn})
default:
if ok {
left := bleveQuery.NewDisjunctionQuery([]bleveQuery.Query{ln})
left.AddQuery(right.Disjuncts...)
return left
}
return bleveQuery.NewDisjunctionQuery([]bleveQuery.Query{ln, rn})
}
}
if operator.Value == kql.BoolAND {
switch left := ln.(type) {
case *bleveQuery.ConjunctionQuery:
left.AddQuery(rn)
return left
case *bleveQuery.DisjunctionQuery:
if !leftIsGroup {
last := left.Disjuncts[len(left.Disjuncts)-1]
rn = bleveQuery.NewConjunctionQuery([]bleveQuery.Query{
last,
rn,
})
dj := bleveQuery.NewDisjunctionQuery(left.Disjuncts[:len(left.Disjuncts)-1])
dj.AddQuery(rn)
return dj
}
}
}
return bleveQuery.NewConjunctionQuery([]bleveQuery.Query{
ln,
rn,
})
}
// 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
}
inclusive, exclusive := true, false
var q *bleveQuery.NumericRangeQuery
switch operator.Value {
case ">":
q = bleveQuery.NewNumericRangeInclusiveQuery(&value, nil, &exclusive, nil)
case ">=":
q = bleveQuery.NewNumericRangeInclusiveQuery(&value, nil, &inclusive, nil)
case "<":
q = bleveQuery.NewNumericRangeInclusiveQuery(nil, &value, nil, &exclusive)
case "<=":
q = bleveQuery.NewNumericRangeInclusiveQuery(nil, &value, nil, &inclusive)
default:
return nil
}
q.SetField(field)
return q
}