Merge pull request #4206 from opencloud-eu/feat/search-geohash-filter-token

feat(search): geohash cells as aggregation filter tokens
This commit is contained in:
Dominik Schmidt authored and GitHub committed 2026-12-03 16:19:45 +00:00
commit 2e8fc06b50
14 files changed
+287 -25

No files matched your search

@@ -151,15 +151,12 @@ func searchAggregationsToLibregraph(in []*searchsvc.AggregationResult, defs []li
ranges := libregraphRangesToSearch(def.BucketDefinition.GetRanges())
agg.Buckets = make([]libregraph.SearchBucket, 0, len(in[i].GetBuckets()))
for _, b := range in[i].GetBuckets() {
bucket := libregraph.SearchBucket{
agg.Buckets = append(agg.Buckets, libregraph.SearchBucket{
Key: libregraph.PtrString(b.GetKey()),
Count: libregraph.PtrInt64(b.GetCount()),
AggregationFilterToken: libregraph.PtrString(aggregationFilterToken(b.GetKey(), ranges)),
LibreGraphSubAggregations: searchAggregationsToLibregraph(b.GetSubAggregations(), def.LibreGraphSubAggregations),
}
if def.LibreGraphGeohashDefinition == nil {
bucket.AggregationFilterToken = libregraph.PtrString(aggregationFilterToken(b.GetKey(), ranges))
}
agg.Buckets = append(agg.Buckets, bucket)
})
}
out = append(out, agg)
}
@@ -468,22 +468,18 @@ var _ = ginkgo.Describe("SearchQuery", func() {
Expect(captured().GetAggregations()[0].GetGeohashDefinition().GetPrecision()).To(Equal(int32(5)))
})
ginkgo.It("answers geohash cells without a filter token, their sub-aggregations with one", func() {
g, _ := graphWithAggregations(&searchsvc.AggregationResult{
Field: "location",
Buckets: []*searchsvc.Bucket{{Key: "u4pru", Count: 2, SubAggregations: []*searchsvc.AggregationResult{
{Field: "MimeType", Buckets: []*searchsvc.Bucket{{Key: "image/jpeg", Count: 2}}},
}}},
ginkgo.It("answers a geohash cell with a token that filters to the cell", func() {
g, captured := graphWithAggregations(&searchsvc.AggregationResult{
Field: "location",
Buckets: []*searchsvc.Bucket{{Key: "u4pru", Count: 2}},
})
rr := postSearchQuery(g, searchQueryBody(`"aggregations": [{"field": "location", "@libre.graph.geohashDefinition": {"precision": 5},
"@libre.graph.subAggregations": [{"field": "mimeType"}]}]`))
rr := postSearchQuery(g, searchQueryBody(`"aggregations": [{"field": "location", "@libre.graph.geohashDefinition": {"precision": 5}}],
"aggregationFilters": ["location:\"ǂǂ7534707275\""]`))
Expect(rr.Code).To(Equal(http.StatusOK), rr.Body.String())
cell := hitsContainer(rr).Aggregations[0].Buckets[0]
Expect(cell.Key).To(Equal("u4pru"))
Expect(cell.Token).To(BeEmpty())
Expect(rr.Body.String()).ToNot(ContainSubstring("ǂǂ7534707275"))
Expect(cell.SubAggregations[0].Buckets[0].Token).To(Equal(`"ǂǂ696d6167652f6a706567"`))
Expect(hitsContainer(rr).Aggregations[0].Buckets[0].Token).To(Equal(`"ǂǂ7534707275"`))
Expect(captured().GetAggregationFilters()[0].GetField()).To(Equal("location"))
Expect(captured().GetAggregationFilters()[0].GetTerms()).To(Equal([]string{"u4pru"}))
})
ginkgo.It("rejects an $expand it does not know with 400", func() {
+11
View File
@@ -12,6 +12,7 @@ import (
// its field.
type Buckets struct {
Terms []Term
Cells []Cell
Ranges Ranges
}
@@ -44,6 +45,16 @@ func ParseFilter(f *searchsvc.AggregationFilter, fieldType string) (Buckets, err
if len(f.GetTerms()) == 0 {
return buckets, nil
}
if fieldType == mapping.TypeGeopoint {
for _, key := range f.GetTerms() {
cell, err := ParseCell(key)
if err != nil {
return Buckets{}, fmt.Errorf("invalid bucket key on field %q: %w", field, err)
}
buckets.Cells = append(buckets.Cells, cell)
}
return buckets, nil
}
if err := validateTermsField(field, fieldType); err != nil {
return Buckets{}, err
}
@@ -35,6 +35,15 @@ var _ = Describe("ParseFilter", func() {
Expect(got.Ranges.Numeric).To(HaveLen(2))
})
It("reads the keys on a geopoint as geohash cells", func() {
got, err := parse(&searchsvc.AggregationFilter{Field: "location", Terms: []string{"u4p", "u33dc"}})
Expect(err).ToNot(HaveOccurred())
Expect(got.Terms).To(BeEmpty())
Expect(got.Cells).To(HaveLen(2))
Expect(got.Cells[0].Geohash).To(Equal("u4p"))
Expect(got.Cells[1].Geohash).To(Equal("u33dc"))
})
DescribeTable("rejects what no aggregation on the field could have answered",
func(f *searchsvc.AggregationFilter) {
_, err := parse(f)
@@ -51,6 +60,8 @@ var _ = Describe("ParseFilter", func() {
Entry("another spelling of a bool", &searchsvc.AggregationFilter{Field: "audio.hasDrm", Terms: []string{"1"}}),
Entry("a key on a date field", &searchsvc.AggregationFilter{Field: "photo.takenDateTime", Terms: []string{"2018-08-11T00:00:00Z"}}),
Entry("a key on full text", &searchsvc.AggregationFilter{Field: "Content", Terms: []string{"fox"}}),
Entry("a key that is no geohash on a geopoint", &searchsvc.AggregationFilter{Field: "location", Terms: []string{"u4pru", "a"}}),
Entry("a numeric range on a geopoint", &searchsvc.AggregationFilter{Field: "location", Ranges: []*searchsvc.BucketRange{{From: "1"}}}),
Entry("a numeric range on a keyword", &searchsvc.AggregationFilter{Field: "audio.artist", Ranges: []*searchsvc.BucketRange{{From: "1980"}}}),
Entry("a date range on a number", &searchsvc.AggregationFilter{Field: "audio.year", Ranges: []*searchsvc.BucketRange{{From: "2018-08-11T00:00:00Z"}}}),
)
@@ -0,0 +1,53 @@
package aggregation
import (
"fmt"
"strings"
)
const geohashBase32 = "0123456789bcdefghjkmnpqrstuvwxyz"
// Cell is a geohash cell of a geohash aggregation, the bucket key a filter on
// a geopoint field selects. Geohash does not say which cell a point on an edge
// belongs to; both engines follow Lucene, whose geohash_grid OpenSearch answers
// with: a point on MinLat or MinLon lies in the cell, one on MaxLat or MaxLon
// in the next, except at 90 and 180.
type Cell struct {
Geohash string
MinLat, MaxLat, MinLon, MaxLon float64
}
// ParseCell reads a geohash cell as a geohash aggregation spells its keys.
func ParseCell(key string) (Cell, error) {
if len(key) < 1 || len(key) > MaxGeohashPrecision {
return Cell{}, fmt.Errorf("%q is no geohash cell of 1-%d characters", key, MaxGeohashPrecision)
}
c := Cell{Geohash: key, MinLat: -90, MaxLat: 90, MinLon: -180, MaxLon: 180}
even := true
for _, r := range key {
v := strings.IndexRune(geohashBase32, r)
if v < 0 {
return Cell{}, fmt.Errorf("%q is no geohash cell", key)
}
for bit := 4; bit >= 0; bit-- {
upper := v&(1<<bit) != 0
if even {
mid := (c.MinLon + c.MaxLon) / 2
if upper {
c.MinLon = mid
} else {
c.MaxLon = mid
}
} else {
mid := (c.MinLat + c.MaxLat) / 2
if upper {
c.MinLat = mid
} else {
c.MaxLat = mid
}
}
even = !even
}
}
return c, nil
}
@@ -0,0 +1,33 @@
package aggregation_test
import (
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/opencloud-eu/opencloud/services/search/pkg/aggregation"
)
var _ = Describe("ParseCell", func() {
DescribeTable("decodes the bounds of a cell",
func(key string, minLat, maxLat, minLon, maxLon float64) {
c, err := aggregation.ParseCell(key)
Expect(err).ToNot(HaveOccurred())
Expect([]float64{c.MinLat, c.MaxLat, c.MinLon, c.MaxLon}).To(Equal([]float64{minLat, maxLat, minLon, maxLon}))
},
Entry("the cell north-east of 0,0", "s", 0.0, 45.0, 0.0, 45.0),
Entry("the cell south-west of 0,0", "7", -45.0, 0.0, -45.0, 0.0),
Entry("the last cell", "z", 45.0, 90.0, 135.0, 180.0),
Entry("a cell around Skagen", "u4pru", 57.6123046875, 57.65625, 10.37109375, 10.4150390625),
)
DescribeTable("rejects what is no cell",
func(key string) {
_, err := aggregation.ParseCell(key)
Expect(err).To(HaveOccurred())
},
Entry("empty", ""),
Entry("a letter outside the alphabet", "a"),
Entry("upper case", "U4PRU"),
Entry("longer than the longest cell", "u4pruydqqvjq7"),
)
})
+8
View File
@@ -1,6 +1,8 @@
package bleve
import (
"strconv"
"github.com/blevesearch/bleve/v2"
"github.com/blevesearch/bleve/v2/search/query"
@@ -45,6 +47,12 @@ func aggregationFilterQueries(filters []*searchService.AggregationFilter) ([]que
add(bleve.NewTermQuery(term.Key))
}
}
for _, c := range buckets.Cells {
q := bleve.NewTermQuery(strconv.Itoa(len(c.Geohash)) + "/" + c.Geohash)
q.SetField(f.GetField() + geohashSuffix)
q.SetBoost(0)
selected = append(selected, q)
}
for _, r := range buckets.Ranges.Numeric {
add(bleve.NewNumericRangeInclusiveQuery(r.From, r.To, &inclusive, &exclusive))
}
+3 -2
View File
@@ -21,8 +21,9 @@ const (
geohashBase32 = "0123456789bcdefghjkmnpqrstuvwxyz"
)
// encodeGeohash matches Lucene/OpenSearch so both engines bucket into the
// same cells
// encodeGeohash follows Lucene, whose geohash_grid OpenSearch answers with, so
// both engines bucket into the same cells: a point on the middle of an
// interval goes to its upper half
func encodeGeohash(lat, lon float64, precision int) string {
latMin, latMax := -90.0, 90.0
lonMin, lonMax := -180.0, 180.0
+10 -1
View File
@@ -3,6 +3,7 @@ package opensearch
import (
searchService "github.com/opencloud-eu/opencloud/protogen/gen/opencloud/services/search/v0"
"github.com/opencloud-eu/opencloud/services/search/pkg/aggregation"
"github.com/opencloud-eu/opencloud/services/search/pkg/mapping"
"github.com/opencloud-eu/opencloud/services/search/pkg/opensearch/internal/osu"
"github.com/opencloud-eu/opencloud/services/search/pkg/search"
)
@@ -11,11 +12,19 @@ import (
func aggregationFilterQueries(filters []*searchService.AggregationFilter) ([]osu.Builder, error) {
out := make([]osu.Builder, 0, len(filters))
for _, f := range filters {
if _, err := aggregation.ParseFilter(f, search.FieldType(f.GetField())); err != nil {
buckets, err := aggregation.ParseFilter(f, search.FieldType(f.GetField()))
if err != nil {
return nil, err
}
// a bool query of only should clauses needs one of them to match
selected := osu.NewBoolQuery()
if len(buckets.Cells) > 0 {
for _, c := range buckets.Cells {
selected.Should(osu.NewGeoCellQuery(f.GetField()+mapping.GeopointSuffix, c.MinLat, c.MaxLat, c.MinLon, c.MaxLon))
}
out = append(out, selected)
continue
}
for _, key := range f.GetTerms() {
selected.Should(osu.NewTermQuery[string](f.GetField()).Value(key))
}
@@ -0,0 +1,13 @@
package osu_test
import (
"testing"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
func TestOsu(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "OpenSearch Query Builder Suite")
}
@@ -0,0 +1,48 @@
package osu
import (
"encoding/json"
"math"
)
// Lucene stores a geo_point as 32-bit integers, and the edges of a geohash
// cell lie on that grid. geo_bounding_box includes its upper edges, the cell
// does not: half a step down the edge is outside, the point before it inside.
var (
latStep = 180 / math.Exp2(32)
lonStep = 360 / math.Exp2(32)
)
// GeoCellQuery matches the points of a field inside a geohash cell, the same
// points a geohash_grid aggregation counts in it.
type GeoCellQuery struct {
field string
minLat, maxLat, minLon, maxLon float64
}
func NewGeoCellQuery(field string, minLat, maxLat, minLon, maxLon float64) *GeoCellQuery {
return &GeoCellQuery{field: field, minLat: minLat, maxLat: maxLat, minLon: minLon, maxLon: maxLon}
}
func (q *GeoCellQuery) Map() (map[string]any, error) {
top, right := q.maxLat, q.maxLon
// the last cell keeps its edge: nothing lies beyond 90 or 180
if top < 90 {
top -= latStep / 2
}
if right < 180 {
right -= lonStep / 2
}
return map[string]any{"geo_bounding_box": map[string]any{q.field: map[string]any{
"top_left": map[string]any{"lat": top, "lon": q.minLon},
"bottom_right": map[string]any{"lat": q.minLat, "lon": right},
}}}, nil
}
func (q *GeoCellQuery) MarshalJSON() ([]byte, error) {
data, err := q.Map()
if err != nil {
return nil, err
}
return json.Marshal(data)
}
@@ -0,0 +1,41 @@
package osu_test
import (
"math"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/opencloud-eu/opencloud/services/search/pkg/opensearch/internal/osu"
)
var _ = Describe("GeoCellQuery", func() {
halfLatStep := 180 / math.Exp2(33)
halfLonStep := 360 / math.Exp2(33)
box := func(top, bottom, left, right float64) map[string]any {
return map[string]any{"geo_bounding_box": map[string]any{"location_geopoint": map[string]any{
"top_left": map[string]any{"lat": top, "lon": left},
"bottom_right": map[string]any{"lat": bottom, "lon": right},
}}}
}
It("pulls the north and east edges of a cell in by half a step", func() {
q := osu.NewGeoCellQuery("location_geopoint", 57.6123046875, 57.65625, 10.37109375, 10.4150390625)
Expect(q.Map()).To(Equal(box(57.65625-halfLatStep, 57.6123046875, 10.37109375, 10.4150390625-halfLonStep)))
})
It("keeps the edges of the last cell at 90 and 180", func() {
q := osu.NewGeoCellQuery("location_geopoint", 45, 90, 135, 180)
Expect(q.Map()).To(Equal(box(90, 45, 135, 180)))
})
It("marshals to the same query", func() {
q := osu.NewGeoCellQuery("location_geopoint", 45, 90, 135, 180)
Expect(q.MarshalJSON()).To(MatchJSON(`{"geo_bounding_box": {"location_geopoint": {
"top_left": {"lat": 90, "lon": 135}, "bottom_right": {"lat": 45, "lon": 180}}}}`))
})
})
+12 -2
View File
@@ -933,9 +933,19 @@ Fixtures:
- `skagen-a.jpg`, MimeType = image/jpeg
- `skagen-b.jpg`, MimeType = image/jpeg
- `berlin.jpg`, MimeType = image/jpeg
- `null-island.jpg`, MimeType = image/jpeg
- `just-south.jpg`, MimeType = image/jpeg
- `north-east-corner.jpg`, MimeType = image/jpeg
- `nowhere.jpg`, MimeType = image/jpeg
| Case | Query | expected | bleve | OpenSearch | same? |
|---|---|---|---|---|---|
| AGG-50 | `mediatype:image` reads `geohash cells at precision 5` | location u33dc=1, location u4pru=2 | location u33dc=1, location u4pru=2 | location u33dc=1, location u4pru=2 | ✅ |
| AGG-51 | `mediatype:image` reads `camera buckets nested in geohash cells at precision 3` | location u... Leica=1, location u... Leica=2, location u33=1, location u4p=2 | location u... Leica=1, location u... Leica=2, location u33=1, location u4p=2 | location u... Leica=1, location u... Leica=2, location u33=1, location u4p=2 | ✅ |
| AGG-50 | `mediatype:image` reads `geohash cells at precision 5` | location kpbxy=1, location s0000=1, location u33dc=1, location u4pru=2, location zzzzz=1 | location kpbxy=1, location s0000=1, location u33dc=1, location u4pru=2, location zzzzz=1 | location kpbxy=1, location s0000=1, location u33dc=1, location u4pru=2, location zzzzz=1 | ✅ |
| AGG-51 | `mediatype:image` reads `camera buckets nested in geohash cells at precision 3` | location k... Leica=1, location kpb=1, location s... Leica=1, location s00=1, location u... Leica=1, location u... Leica=2, location u33=1, location u4p=2, … +2 more | location k... Leica=1, location kpb=1, location s... Leica=1, location s00=1, location u... Leica=1, location u... Leica=2, location u33=1, location u4p=2, … +2 more | location k... Leica=1, location kpb=1, location s... Leica=1, location s00=1, location u... Leica=1, location u... Leica=2, location u33=1, location u4p=2, … +2 more | ✅ |
| AGG-52 | `mediatype:image` reads `filtered to the cell u4pru, as many matches as the cell counted` | location u4pru=2, skagen-a.jpg, skagen-b.jpg | location u4pru=2, skagen-a.jpg, skagen-b.jpg | location u4pru=2, skagen-a.jpg, skagen-b.jpg | ✅ |
| AGG-53 | `mediatype:image` reads `filtered to two cells of different precision` | berlin.jpg, skagen-a.jpg, skagen-b.jpg | berlin.jpg, skagen-a.jpg, skagen-b.jpg | berlin.jpg, skagen-a.jpg, skagen-b.jpg | ✅ |
| AGG-54 | `mediatype:image` reads `filtered to the cells whose upper edges 0,0 lies on, without the point on the edge` | just-south.jpg | just-south.jpg | just-south.jpg | ✅ |
| AGG-55 | `mediatype:image` reads `filtered to the cell 0,0 lies in, from its lower edges` | null-island.jpg | null-island.jpg | null-island.jpg | ✅ |
| AGG-57 | `mediatype:image` reads `filtered to the cell below 0,1, which a point a billionth of a degree south of the edge lies in` | just-south.jpg | just-south.jpg | just-south.jpg | ✅ |
| AGG-58 | `mediatype:image` reads `filtered to the last cell, which keeps its edges at 90 and 180` | north-east-corner.jpg | north-east-corner.jpg | north-east-corner.jpg | ✅ |
| AGG-56 | `mediatype:image` reads `filtered to a key that is no geohash` | bad request | bad request | bad request | ✅ |
@@ -447,11 +447,17 @@ func geohashFixtures() []search.Resource {
withGeo("skagen-a.jpg", 57.64911, 10.40744),
withGeo("skagen-b.jpg", 57.6495, 10.4090),
withGeo("berlin.jpg", 52.52, 13.405),
withGeo("null-island.jpg", 0, 0),
withGeo("just-south.jpg", -1e-9, 1),
withGeo("north-east-corner.jpg", 90, 180),
fixtureDoc("nowhere.jpg", withMime("image/jpeg")),
}
}
func geohashCases() []aggCase {
terms := func(field string, keys ...string) *searchService.AggregationFilter {
return &searchService.AggregationFilter{Field: field, Terms: keys}
}
cells := func(field string, precision int32, subs ...*searchService.AggregationOption) *searchService.AggregationOption {
return &searchService.AggregationOption{
Field: field,
@@ -462,13 +468,38 @@ func geohashCases() []aggCase {
return []aggCase{
{id: 50, query: "mediatype:image", reads: "geohash cells at precision 5",
aggs: []*searchService.AggregationOption{cells("location", 5)},
want: []string{"location u4pru=2", "location u33dc=1"}},
want: []string{"location u4pru=2", "location kpbxy=1", "location s0000=1", "location u33dc=1", "location zzzzz=1"}},
{id: 51, query: "mediatype:image", reads: "camera buckets nested in geohash cells at precision 3",
aggs: []*searchService.AggregationOption{cells("location", 3, &searchService.AggregationOption{Field: "photo.cameraMake"})},
want: []string{
"location u4p=2", "location u4p=2 / photo.cameraMake Leica=2",
"location kpb=1", "location kpb=1 / photo.cameraMake Leica=1",
"location s00=1", "location s00=1 / photo.cameraMake Leica=1",
"location u33=1", "location u33=1 / photo.cameraMake Leica=1",
"location zzz=1", "location zzz=1 / photo.cameraMake Leica=1",
}},
{id: 52, query: "mediatype:image", reads: "filtered to the cell u4pru, as many matches as the cell counted",
filters: []*searchService.AggregationFilter{terms("location", "u4pru")},
aggs: []*searchService.AggregationOption{cells("location", 5)},
want: []string{"skagen-a.jpg", "skagen-b.jpg", "location u4pru=2"}},
{id: 53, query: "mediatype:image", reads: "filtered to two cells of different precision",
filters: []*searchService.AggregationFilter{terms("location", "u4p", "u33dc")},
want: []string{"berlin.jpg", "skagen-a.jpg", "skagen-b.jpg"}},
{id: 54, query: "mediatype:image", reads: "filtered to the cells whose upper edges 0,0 lies on, without the point on the edge",
filters: []*searchService.AggregationFilter{terms("location", "7", "e", "k")},
want: []string{"just-south.jpg"}},
{id: 55, query: "mediatype:image", reads: "filtered to the cell 0,0 lies in, from its lower edges",
filters: []*searchService.AggregationFilter{terms("location", "s")},
want: []string{"null-island.jpg"}},
{id: 57, query: "mediatype:image", reads: "filtered to the cell below 0,1, which a point a billionth of a degree south of the edge lies in",
filters: []*searchService.AggregationFilter{terms("location", "k")},
want: []string{"just-south.jpg"}},
{id: 58, query: "mediatype:image", reads: "filtered to the last cell, which keeps its edges at 90 and 180",
filters: []*searchService.AggregationFilter{terms("location", "z")},
want: []string{"north-east-corner.jpg"}},
{id: 56, query: "mediatype:image", reads: "filtered to a key that is no geohash",
filters: []*searchService.AggregationFilter{terms("location", "a")},
wantBadRequest: true},
}
}