diff --git a/services/graph/pkg/service/v0/searchquery_mapping.go b/services/graph/pkg/service/v0/searchquery_mapping.go index 5ad25fe1e9..719e503e3e 100644 --- a/services/graph/pkg/service/v0/searchquery_mapping.go +++ b/services/graph/pkg/service/v0/searchquery_mapping.go @@ -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) } diff --git a/services/graph/pkg/service/v0/searchquery_test.go b/services/graph/pkg/service/v0/searchquery_test.go index a807f794b4..905ea97e7e 100644 --- a/services/graph/pkg/service/v0/searchquery_test.go +++ b/services/graph/pkg/service/v0/searchquery_test.go @@ -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() { diff --git a/services/search/pkg/aggregation/filter.go b/services/search/pkg/aggregation/filter.go index 63e116ea63..d4800b1dc7 100644 --- a/services/search/pkg/aggregation/filter.go +++ b/services/search/pkg/aggregation/filter.go @@ -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 } diff --git a/services/search/pkg/aggregation/filter_test.go b/services/search/pkg/aggregation/filter_test.go index 605e64a523..19fa2865d0 100644 --- a/services/search/pkg/aggregation/filter_test.go +++ b/services/search/pkg/aggregation/filter_test.go @@ -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"}}}), ) diff --git a/services/search/pkg/aggregation/geohash.go b/services/search/pkg/aggregation/geohash.go new file mode 100644 index 0000000000..50666d93f9 --- /dev/null +++ b/services/search/pkg/aggregation/geohash.go @@ -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< 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)) } diff --git a/services/search/pkg/opensearch/internal/osu/osu_suite_test.go b/services/search/pkg/opensearch/internal/osu/osu_suite_test.go new file mode 100644 index 0000000000..ceea359067 --- /dev/null +++ b/services/search/pkg/opensearch/internal/osu/osu_suite_test.go @@ -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") +} diff --git a/services/search/pkg/opensearch/internal/osu/query_geo_cell.go b/services/search/pkg/opensearch/internal/osu/query_geo_cell.go new file mode 100644 index 0000000000..1e202f0169 --- /dev/null +++ b/services/search/pkg/opensearch/internal/osu/query_geo_cell.go @@ -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) +} diff --git a/services/search/pkg/opensearch/internal/osu/query_geo_cell_test.go b/services/search/pkg/opensearch/internal/osu/query_geo_cell_test.go new file mode 100644 index 0000000000..641ddef1b7 --- /dev/null +++ b/services/search/pkg/opensearch/internal/osu/query_geo_cell_test.go @@ -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}}}}`)) + }) +}) diff --git a/services/search/pkg/parity/README.md b/services/search/pkg/parity/README.md index 0b069ac162..5465614142 100644 --- a/services/search/pkg/parity/README.md +++ b/services/search/pkg/parity/README.md @@ -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 | ✅ | diff --git a/services/search/pkg/parity/aggregations_test.go b/services/search/pkg/parity/aggregations_test.go index ed91e328f4..091f1ce4ff 100644 --- a/services/search/pkg/parity/aggregations_test.go +++ b/services/search/pkg/parity/aggregations_test.go @@ -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}, } }