Merge pull request #3298 from opencloud-eu/feat/search-sort-properties

feat(search): sort results via sortProperties / order_by
This commit is contained in:
Dominik Schmidt authored and GitHub committed 2026-12-03 20:21:53 +01:00
commit 46b508446f
16 files changed
+1237 -359

No files matched your search

File diff suppressed because it is too large. Load diff
@@ -771,6 +771,13 @@
"type": "integer",
"format": "int32",
"description": "Optional. Number of leading matches to skip in the globally sorted,\ncross-space merged result list."
},
"orderBy": {
"type": "array",
"items": {
"$ref": "#/definitions/v0SortProperty"
},
"description": "Optional. Fields to sort the matches by, in order of precedence. When\nempty, matches are sorted by relevance score. Only a subset of the\nindexed fields is sortable; the graph service validates this before\nforwarding the request."
}
}
},
@@ -800,6 +807,19 @@
}
}
},
"v0SortProperty": {
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "Required. The field to sort on, in graph notation (\"name\", \"size\",\n\"lastModifiedDateTime\", \"mimeType\" or a scalar facet field such as\n\"photo.takenDateTime\" or \"audio.artist\"). A field is sortable when it is\nindexed as a scalar in both backends AND carried on the Match entity\n(the service layer needs the sort key to merge per-space result\nstreams); see the search package's IsSortableField."
},
"isDescending": {
"type": "boolean",
"description": "Optional. Sort in descending order. Defaults to ascending."
}
}
},
"v0Video": {
"type": "object",
"properties": {
@@ -81,6 +81,11 @@ message SearchRequest {
// Optional. Number of leading matches to skip in the globally sorted,
// cross-space merged result list.
int32 from = 7 [(google.api.field_behavior) = OPTIONAL];
// Optional. Fields to sort the matches by, in order of precedence. When
// empty, matches are sorted by relevance score. Only a subset of the
// indexed fields is sortable; the graph service validates this before
// forwarding the request.
repeated SortProperty order_by = 8 [(google.api.field_behavior) = OPTIONAL];
}
message SearchResponse {
@@ -128,6 +133,18 @@ message GeohashDefinition {
int32 precision = 1;
}
message SortProperty {
// Required. The field to sort on, in graph notation ("name", "size",
// "lastModifiedDateTime", "mimeType" or a scalar facet field such as
// "photo.takenDateTime" or "audio.artist"). A field is sortable when it is
// indexed as a scalar in both backends AND carried on the Match entity
// (the service layer needs the sort key to merge per-space result
// streams); see the search package's IsSortableField.
string name = 1;
// Optional. Sort in descending order. Defaults to ascending.
bool is_descending = 2;
}
enum MetricKind {
METRIC_KIND_UNSPECIFIED = 0;
METRIC_KIND_SUM = 1;
+32 -13
View File
@@ -46,10 +46,6 @@ func (g Graph) SearchQuery(w http.ResponseWriter, r *http.Request) {
// every request is validated before the first one runs
searches := make([]*searchsvc.SearchRequest, 0, len(req.Requests))
for _, sr := range req.Requests {
if property := unsupportedProperty(sr); property != "" {
errorcode.NotSupported.Render(w, r, http.StatusNotImplemented, property+" is not supported yet")
return
}
prepared, err := searchRequestOf(sr)
if err != nil {
errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, err.Error())
@@ -89,15 +85,6 @@ func validateSearchExpand(r *http.Request) error {
return nil
}
// unsupportedProperty names a property of the spec this endpoint does not
// evaluate yet.
func unsupportedProperty(sr libregraph.SearchRequest) string {
if len(sr.SortProperties) > 0 {
return "sortProperties"
}
return ""
}
// searchRequestOf validates one request against the spec and the index rules
// (the search service checks them again) and translates it. Fields are
// validated under the request's names so an error reads like the request.
@@ -111,6 +98,9 @@ func searchRequestOf(sr libregraph.SearchRequest) (*searchsvc.SearchRequest, err
if err := validateAggregations(sr.Aggregations); err != nil {
return nil, err
}
if err := validateSortProperties(sr.SortProperties); err != nil {
return nil, err
}
aggregations := libregraphAggregationsToSearch(sr.Aggregations)
filters, err := aggregationFiltersToSearch(sr.AggregationFilters)
if err != nil {
@@ -135,6 +125,7 @@ func searchRequestOf(sr libregraph.SearchRequest) (*searchsvc.SearchRequest, err
PageSize: &size,
Aggregations: aggregations,
AggregationFilters: filters,
OrderBy: libregraphSortToSearch(sr.SortProperties),
}, nil
}
@@ -260,6 +251,34 @@ func validateAggregations(aggs []libregraph.AggregationOption) error {
return nil
}
// validateSortProperties rejects sorting by unknown or multivalued fields.
// Sortable are scalar fields carried on the search hit: name, size,
// lastModifiedDateTime, mimeType and the facet fields (photo.takenDateTime,
// audio.artist, image.width, ...); see search.IsSortableField.
func validateSortProperties(sortProperties []libregraph.SortProperty) error {
for _, sp := range sortProperties {
if !search.IsSortableField(sp.Name) {
return fmt.Errorf("field %q is not sortable; sortable are scalar hit fields such as name, size, lastModifiedDateTime, mimeType or photo.takenDateTime", sp.Name)
}
}
return nil
}
func libregraphSortToSearch(in []libregraph.SortProperty) []*searchsvc.SortProperty {
if len(in) == 0 {
return nil
}
out := make([]*searchsvc.SortProperty, 0, len(in))
for _, sp := range in {
p := &searchsvc.SortProperty{Name: sp.Name}
if sp.IsDescending != nil {
p.IsDescending = *sp.IsDescending
}
out = append(out, p)
}
return out
}
// renderSearchError answers with the status the search service failed with.
func (g Graph) renderSearchError(w http.ResponseWriter, r *http.Request, err error) {
e := merrors.Parse(err.Error())
@@ -440,16 +440,6 @@ var _ = ginkgo.Describe("SearchQuery", func() {
Expect(aggs[1].Metric.Value).To(BeNil(), "no value, not zero")
})
ginkgo.DescribeTable("answers a property it does not evaluate with 501 instead of ignoring it",
func(fragment, property string) {
rr := postSearchQuery(graphWithoutSearch(), searchQueryBody(fragment))
Expect(rr.Code).To(Equal(http.StatusNotImplemented), rr.Body.String())
Expect(rr.Body.String()).To(ContainSubstring("notSupported"))
Expect(rr.Body.String()).To(ContainSubstring(property))
},
ginkgo.Entry("sortProperties", `"sortProperties": [{"name": "name"}]`, "sortProperties"),
)
ginkgo.It("rejects more than 5 requests with 400", func() {
one := `{"entityTypes": ["driveItem"], "query": {"queryString": "a"}}`
body := `{"requests": [` + strings.Repeat(one+",", 5) + one + `]}`
@@ -482,6 +472,47 @@ var _ = ginkgo.Describe("SearchQuery", func() {
Expect(captured().GetAggregationFilters()[0].GetTerms()).To(Equal([]string{"u4pru"}))
})
ginkgo.It("forwards sortProperties to the search service as order_by", func() {
g, captured := graphWithSearchAnswer(&searchsvc.SearchResponse{})
rr := postSearchQuery(g, searchQueryBody(`"sortProperties": [{"name": "photo.takenDateTime", "isDescending": true}, {"name": "name"}]`))
Expect(rr.Code).To(Equal(http.StatusOK), rr.Body.String())
Expect(captured().GetOrderBy()).To(HaveLen(2))
Expect(captured().GetOrderBy()[0].GetName()).To(Equal("photo.takenDateTime"))
Expect(captured().GetOrderBy()[0].GetIsDescending()).To(BeTrue())
Expect(captured().GetOrderBy()[1].GetName()).To(Equal("name"))
Expect(captured().GetOrderBy()[1].GetIsDescending()).To(BeFalse())
})
ginkgo.DescribeTable("accepts sorting by scalar hit fields",
func(field string) {
g, _ := graphWithSearchAnswer(&searchsvc.SearchResponse{})
rr := postSearchQuery(g, searchQueryBody(fmt.Sprintf(`"sortProperties": [{"name": %q}]`, field)))
Expect(rr.Code).To(Equal(http.StatusOK), rr.Body.String())
},
ginkgo.Entry("name", "name"),
ginkgo.Entry("size", "size"),
ginkgo.Entry("lastModifiedDateTime", "lastModifiedDateTime"),
ginkgo.Entry("mimeType", "mimeType"),
ginkgo.Entry("photo.takenDateTime", "photo.takenDateTime"),
ginkgo.Entry("photo.iso", "photo.iso"),
ginkgo.Entry("audio.artist", "audio.artist"),
ginkgo.Entry("image.width", "image.width"),
)
ginkgo.DescribeTable("rejects sorting by unsortable fields with 400",
func(field string) {
rr := postSearchQuery(graphWithoutSearch(), searchQueryBody(fmt.Sprintf(`"sortProperties": [{"name": %q}]`, field)))
Expect(rr.Code).To(Equal(http.StatusBadRequest), rr.Body.String())
Expect(rr.Body.String()).To(ContainSubstring(field))
},
ginkgo.Entry("unknown field", "definitelyNotAField"),
ginkgo.Entry("multivalued field", "tags"),
ginkgo.Entry("internal index field name", "Mtime"),
ginkgo.Entry("bare audio facet", "audio"),
ginkgo.Entry("bare location facet", "location"),
)
ginkgo.It("rejects an $expand it does not know with 400", func() {
req := httptest.NewRequest(http.MethodPost, "/search/query?$expand=thumbnails,permissions", bytes.NewBufferString(searchQueryBody(`"from": 0`)))
rr := httptest.NewRecorder()
+13 -2
View File
@@ -109,8 +109,19 @@ func (b *Backend) Search(ctx context.Context, sir *search.IndexQuery) (*search.I
bleveReq := bleve.NewSearchRequest(q)
bleveReq.Highlight = bleve.NewHighlight()
// ties by id, like the cross-space merge
bleveReq.SortBy([]string{"-_score", "_id"})
// order_by first, then like the cross-space merge: score, ties by id
sortOrder := make([]string, 0, len(sir.OrderBy)+2)
for _, sp := range sir.OrderBy {
field, ok := search.SortIndexField(sp.GetName())
if !ok {
return nil, errtypes.BadRequest(fmt.Sprintf("field %q is not sortable", sp.GetName()))
}
if sp.GetIsDescending() {
field = "-" + field
}
sortOrder = append(sortOrder, field)
}
bleveReq.SortBy(append(sortOrder, "-_score", "_id"))
bleveReq.Size = search.EnginePageSize(sir.PageSize, math.MaxInt)
collector, err := newAggCollector(sir.Aggregations)
+18 -3
View File
@@ -126,9 +126,7 @@ func (b *Backend) Search(ctx context.Context, sir *search.IndexQuery) (*search.I
searchParams := opensearchgoAPI.SearchParams{
SourceExcludes: []string{"Content"}, // Do not send back the full content in the search response, as it is only needed for highlighting and can be large. The highlighted snippets will be sent back in the response instead.
// ties by id, like the cross-space merge
Sort: []string{"_score:desc", "ID:asc"},
TrackScores: conversions.ToPointer(true),
TrackScores: conversions.ToPointer(true),
// count every match, the default stops at 10000
TrackTotalHits: true,
Size: conversions.ToPointer(search.EnginePageSize(sir.PageSize, 1000)),
@@ -139,6 +137,22 @@ func (b *Backend) Search(ctx context.Context, sir *search.IndexQuery) (*search.I
searchParams.Preference = "user-" + u.GetId().GetOpaqueId()
}
// order_by first, missing values last in both directions, then like the
// cross-space merge: score, ties by id
sortClause := make([]map[string]any, 0, len(sir.OrderBy)+2)
for _, sp := range sir.OrderBy {
field, ok := search.SortIndexField(sp.GetName())
if !ok {
return nil, errtypes.BadRequest(fmt.Sprintf("field %q is not sortable", sp.GetName()))
}
order := "asc"
if sp.GetIsDescending() {
order = "desc"
}
sortClause = append(sortClause, map[string]any{field: map[string]any{"order": order, "missing": "_last"}})
}
sortClause = append(sortClause, map[string]any{"_score": map[string]any{"order": "desc"}}, map[string]any{"ID": map[string]any{"order": "asc"}})
aggregationsBody, err := aggs.Build(sir.Aggregations)
if err != nil {
return nil, errtypes.BadRequest(err.Error())
@@ -164,6 +178,7 @@ func (b *Backend) Search(ctx context.Context, sir *search.IndexQuery) (*search.I
},
},
Aggs: aggregationsBody,
Sort: sortClause,
},
)
if err != nil {
@@ -96,6 +96,7 @@ func BuildSearchReq(req *opensearchgoAPI.SearchReq, q Builder, p ...SearchBodyPa
type SearchBodyParams struct {
Highlight *BodyParamHighlight `json:"highlight,omitempty"`
Aggs map[string]any `json:"aggs,omitempty"`
Sort []map[string]any `json:"sort,omitempty"`
}
//----------------------------------------------------------------------------//
+54 -23
View File
@@ -272,7 +272,7 @@ Fixtures:
- `plain.txt`, ID = 1$1!plain.txt
- `box`, ID = 1$1!box, folder
- `boxed.txt`, ID = 1$1!boxed.txt, Path = ./box/boxed.txt
- `song.mp3`, ID = 1$1!song.mp3, MimeType = audio/mpeg
- `song.mp3`, ID = 1$1!song.mp3, MimeType = audio/mpeg, audio.duration = 200
| Case | Query | expected | bleve | OpenSearch | same? |
|---|---|---|---|---|---|
@@ -828,7 +828,7 @@ Fixtures:
Fixtures:
- `some_song.mp3`, ID = 1$1!5, MimeType = audio/mpeg
- `some_song.mp3`, ID = 1$1!5, MimeType = audio/mpeg, audio.duration = 225000, audio.year = 2004
- `team.jpg`, ID = 1$1!6, MimeType = image/jpeg
- `lost.jpg`, ID = 1$1!7, MimeType = image/jpeg
@@ -845,17 +845,17 @@ Fixtures:
Fixtures:
- `a.mp3`, MimeType = audio/mpeg, Tags = live, remaster
- `b.mp3`, MimeType = audio/mpeg, Tags = live
- `c.mp3`, MimeType = audio/mpeg
- `d.mp3`, MimeType = audio/mpeg
- `e.mp3`, MimeType = audio/mpeg
- `f.mp3`, MimeType = audio/mpeg
- `g.mp3`, MimeType = audio/mpeg
- `a.jpg`, MimeType = image/jpeg
- `b.jpg`, MimeType = image/jpeg
- `c.jpg`, MimeType = image/jpeg
- `d.jpg`, MimeType = image/jpeg
- `a.mp3`, MimeType = audio/mpeg, Tags = live, remaster, audio.year = 1971
- `b.mp3`, MimeType = audio/mpeg, Tags = live, audio.year = 1975
- `c.mp3`, MimeType = audio/mpeg, audio.year = 1982
- `d.mp3`, MimeType = audio/mpeg, audio.year = 1999
- `e.mp3`, MimeType = audio/mpeg, audio.year = 2001
- `f.mp3`, MimeType = audio/mpeg, audio.year = 2005
- `g.mp3`, MimeType = audio/mpeg, audio.year = 2009
- `a.jpg`, MimeType = image/jpeg, photo.takenDateTime = 2018-08-11T09:15:00Z
- `b.jpg`, MimeType = image/jpeg, photo.takenDateTime = 2018-08-11T19:42:00Z
- `c.jpg`, MimeType = image/jpeg, photo.takenDateTime = 2018-09-01T12:00:00Z
- `d.jpg`, MimeType = image/jpeg, photo.takenDateTime = 2021-08-11T08:00:00Z
- `live.txt`, Tags = Apple, apple, Banana
| Case | Query | expected | bleve | OpenSearch | same? |
@@ -906,16 +906,16 @@ Fixtures:
Fixtures:
- `card-00000.mp3`, MimeType = audio/mpeg
- `card-00001.mp3`, MimeType = audio/mpeg
- `card-00002.mp3`, MimeType = audio/mpeg
- `card-00003.mp3`, MimeType = audio/mpeg
- `card-00004.mp3`, MimeType = audio/mpeg
- `card-00005.mp3`, MimeType = audio/mpeg
- `card-00006.mp3`, MimeType = audio/mpeg
- `card-00007.mp3`, MimeType = audio/mpeg
- `card-00008.mp3`, MimeType = audio/mpeg
- `card-00009.mp3`, MimeType = audio/mpeg
- `card-00000.mp3`, MimeType = audio/mpeg, audio.year = 1950
- `card-00001.mp3`, MimeType = audio/mpeg, audio.year = 1951
- `card-00002.mp3`, MimeType = audio/mpeg, audio.year = 1952
- `card-00003.mp3`, MimeType = audio/mpeg, audio.year = 1953
- `card-00004.mp3`, MimeType = audio/mpeg, audio.year = 1954
- `card-00005.mp3`, MimeType = audio/mpeg, audio.year = 1955
- `card-00006.mp3`, MimeType = audio/mpeg, audio.year = 1956
- `card-00007.mp3`, MimeType = audio/mpeg, audio.year = 1957
- `card-00008.mp3`, MimeType = audio/mpeg, audio.year = 1958
- `card-00009.mp3`, MimeType = audio/mpeg, audio.year = 1959
- ... and 10040 more of the same
| Case | Query | expected | bleve | OpenSearch | same? |
@@ -949,3 +949,34 @@ Fixtures:
| 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 | ✅ |
## Sorting
### sorting
Fixtures:
- `b.mp3`, MimeType = audio/mpeg, Size = 300, Mtime = 2024-03-01T00:00:00Z, audio.duration = 200000, audio.year = 1999
- `a.mp3`, MimeType = audio/mpeg, Size = 100, Mtime = 2024-01-01T00:00:00Z, audio.duration = 300000, audio.year = 2005
- `C.mp3`, MimeType = audio/mpeg, Size = 200, Mtime = 2024-02-01T00:00:00Z, audio.duration = 100000, audio.year = 1999
- `d.mp3`, MimeType = audio/mpeg, Size = 200, Mtime = 2024-04-01T00:00:00Z
- `x.jpg`, MimeType = image/jpeg, photo.takenDateTime = 2020-06-01T12:00:00Z
- `y.jpg`, MimeType = image/jpeg, photo.takenDateTime = 2010-06-01T12:00:00Z
- `z.jpg`, MimeType = image/jpeg
- `apple.txt`
- `Zebra.txt`
- `Übung.txt`
| Case | Query | expected | bleve | OpenSearch | same? |
|---|---|---|---|---|---|
| SORT-01 | `mediatype:audio` reads `by size, a tie in the order of the ids` | a.mp3, C.mp3, d.mp3, b.mp3 | a.mp3, C.mp3, d.mp3, b.mp3 | a.mp3, C.mp3, d.mp3, b.mp3 | ✅ |
| SORT-02 | `mediatype:audio` reads `by size descending, a tie still in the order of the ids` | b.mp3, C.mp3, d.mp3, a.mp3 | b.mp3, C.mp3, d.mp3, a.mp3 | b.mp3, C.mp3, d.mp3, a.mp3 | ✅ |
| SORT-03 | `mediatype:audio` reads `newest first` | d.mp3, b.mp3, C.mp3, a.mp3 | d.mp3, b.mp3, C.mp3, a.mp3 | d.mp3, b.mp3, C.mp3, a.mp3 | ✅ |
| SORT-04 | `mediatype:audio` reads `shortest track first, a file without a duration last` | C.mp3, b.mp3, a.mp3, d.mp3 | C.mp3, b.mp3, a.mp3, d.mp3 | C.mp3, b.mp3, a.mp3, d.mp3 | ✅ |
| SORT-05 | `mediatype:audio` reads `longest track first, a file without a duration still last` | a.mp3, b.mp3, C.mp3, d.mp3 | a.mp3, b.mp3, C.mp3, d.mp3 | a.mp3, b.mp3, C.mp3, d.mp3 | ✅ |
| SORT-06 | `mediatype:audio` reads `by year, within a year the longest track first` | b.mp3, C.mp3, a.mp3, d.mp3 | b.mp3, C.mp3, a.mp3, d.mp3 | b.mp3, C.mp3, a.mp3, d.mp3 | ✅ |
| SORT-07 | `name:"*.txt"` reads `by name in code point order: upper case before lower case, an umlaut after z` | Zebra.txt, apple.txt, Übung.txt | Zebra.txt, apple.txt, Übung.txt | Zebra.txt, apple.txt, Übung.txt | ✅ |
| SORT-08 | `mediatype:image` reads `latest photo first, a file without a date last` | x.jpg, y.jpg, z.jpg | x.jpg, y.jpg, z.jpg | x.jpg, y.jpg, z.jpg | ✅ |
| SORT-09 | `mediatype:image` reads `earliest photo first, a file without a date still last` | y.jpg, x.jpg, z.jpg | y.jpg, x.jpg, z.jpg | y.jpg, x.jpg, z.jpg | ✅ |
| SORT-10 | `mediatype:audio` reads `a field with several values is not sortable` | bad request | bad request | bad request | ✅ |
| SORT-11 | `mediatype:audio` reads `an unknown field is not sortable` | bad request | bad request | bad request | ✅ |
+36 -4
View File
@@ -39,6 +39,8 @@ type matrixRow struct {
WantBadRequest bool
// Overrides is what an engine is held to instead, rendered like expected
Overrides map[string]string
// Ordered keeps the names in the order of the answer, for rows about it
Ordered bool
GroupAt, CaseAt, QueryAt int
}
@@ -213,7 +215,7 @@ func writeMatrix(report types.Report) {
query = row.Context + ", then " + query
}
expected := matrixNames(row.Want)
expected := row.names(row.Want)
switch {
case row.WantBadRequest:
expected = "bad request"
@@ -223,7 +225,7 @@ func writeMatrix(report types.Report) {
fmt.Fprintf(out, "| %s | %s | %s | %s | %s | %s |\n",
row.ID, query, expected,
matrixNames(row.answered["bleve"]), matrixNames(row.answered["opensearch"]), matrixVerdict(row))
row.names(row.answered["bleve"]), row.names(row.answered["opensearch"]), matrixVerdict(row))
}
if os.Getenv("UPDATE_SEARCH_PARITY_MATRIX") != "" {
@@ -284,6 +286,12 @@ func matrixFixtures(group string) string {
}
}
for _, g := range sortGroups() {
if g.name == group {
fixtures = g.fixtures
}
}
if len(fixtures) == 0 {
return "Fixtures: none"
}
@@ -356,6 +364,18 @@ func fixtureFields(f search.Resource, withID bool) string {
add("Mtime = %s", f.Mtime.Format(time.RFC3339))
}
if f.Audio != nil && f.Audio.Duration != nil {
add("audio.duration = %d", *f.Audio.Duration)
}
if f.Audio != nil && f.Audio.Year != nil {
add("audio.year = %d", *f.Audio.Year)
}
if f.Photo != nil && f.Photo.TakenDateTime != nil {
add("photo.takenDateTime = %s", f.Photo.TakenDateTime.Format(time.RFC3339))
}
if f.Hidden {
add("hidden")
}
@@ -389,6 +409,18 @@ func matrixScope(ref *searchMessage.Reference) string {
// its head plus a count instead of flooding the README.
const matrixNamesHead = 8
func (r matrixRow) names(names []string) string {
if !r.Ordered || len(names) == 0 {
return matrixNames(names)
}
shortened := make([]string, 0, len(names))
for _, name := range names {
shortened = append(shortened, shorten(name))
}
return strings.Join(shortened, ", ")
}
func matrixNames(names []string) string {
if len(names) == 0 {
return "no match"
@@ -428,9 +460,9 @@ func matrixVerdict(row *matrixResult) string {
var off []string
known := true
for _, engine := range engineNames {
answer := matrixNames(row.answered[engine])
answer := row.names(row.answered[engine])
agrees := answer == matrixNames(row.Want)
agrees := answer == row.names(row.Want)
switch {
case row.WantBadRequest:
agrees = answer == "bad request"
+159
View File
@@ -0,0 +1,159 @@
package parity
import (
"context"
"fmt"
"time"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
libregraph "github.com/opencloud-eu/libre-graph-api-go"
"github.com/opencloud-eu/reva/v3/pkg/errtypes"
searchService "github.com/opencloud-eu/opencloud/protogen/gen/opencloud/services/search/v0"
"github.com/opencloud-eu/opencloud/services/search/pkg/search"
)
// sortCase holds the engines to the order of their matches.
type sortCase struct {
id int
query string
orderBy []*searchService.SortProperty
reads string
want []string
wantBadRequest bool
}
type sortGroup struct {
name string
fixtures []search.Resource
cases []sortCase
}
func (c sortCase) label() string { return fmt.Sprintf("SORT-%02d", c.id) }
func asc(name string) *searchService.SortProperty {
return &searchService.SortProperty{Name: name}
}
func desc(name string) *searchService.SortProperty {
return &searchService.SortProperty{Name: name, IsDescending: true}
}
func track(name string, size uint64, mtime string, duration int64, year int32) search.Resource {
return fixtureDoc(name, withMime("audio/mpeg"), withSize(size), withMtime(mtime),
withAudio(&libregraph.Audio{Duration: libregraph.PtrInt64(duration), Year: libregraph.PtrInt32(year)}))
}
func takenPhoto(name string, taken string) search.Resource {
t, err := time.Parse(time.RFC3339, taken)
if err != nil {
panic(err)
}
return fixtureDoc(name, withMime("image/jpeg"), withPhoto(&libregraph.Photo{TakenDateTime: &t}))
}
func sortGroups() []sortGroup {
return []sortGroup{
{
name: "sorting",
fixtures: []search.Resource{
track("b.mp3", 300, "2024-03-01T00:00:00Z", 200000, 1999),
track("a.mp3", 100, "2024-01-01T00:00:00Z", 300000, 2005),
track("C.mp3", 200, "2024-02-01T00:00:00Z", 100000, 1999),
fixtureDoc("d.mp3", withMime("audio/mpeg"), withSize(200), withMtime("2024-04-01T00:00:00Z")),
takenPhoto("x.jpg", "2020-06-01T12:00:00Z"),
takenPhoto("y.jpg", "2010-06-01T12:00:00Z"),
fixtureDoc("z.jpg", withMime("image/jpeg")),
fixtureDoc("apple.txt"),
fixtureDoc("Zebra.txt"),
fixtureDoc("Übung.txt"),
},
cases: []sortCase{
{id: 1, query: `mediatype:audio`, orderBy: []*searchService.SortProperty{asc("size")},
reads: "by size, a tie in the order of the ids",
want: []string{"a.mp3", "C.mp3", "d.mp3", "b.mp3"}},
{id: 2, query: `mediatype:audio`, orderBy: []*searchService.SortProperty{desc("size")},
reads: "by size descending, a tie still in the order of the ids",
want: []string{"b.mp3", "C.mp3", "d.mp3", "a.mp3"}},
{id: 3, query: `mediatype:audio`, orderBy: []*searchService.SortProperty{desc("lastModifiedDateTime")},
reads: "newest first",
want: []string{"d.mp3", "b.mp3", "C.mp3", "a.mp3"}},
{id: 4, query: `mediatype:audio`, orderBy: []*searchService.SortProperty{asc("audio.duration")},
reads: "shortest track first, a file without a duration last",
want: []string{"C.mp3", "b.mp3", "a.mp3", "d.mp3"}},
{id: 5, query: `mediatype:audio`, orderBy: []*searchService.SortProperty{desc("audio.duration")},
reads: "longest track first, a file without a duration still last",
want: []string{"a.mp3", "b.mp3", "C.mp3", "d.mp3"}},
{id: 6, query: `mediatype:audio`, orderBy: []*searchService.SortProperty{asc("audio.year"), desc("audio.duration")},
reads: "by year, within a year the longest track first",
want: []string{"b.mp3", "C.mp3", "a.mp3", "d.mp3"}},
{id: 7, query: `name:"*.txt"`, orderBy: []*searchService.SortProperty{asc("name")},
reads: "by name in code point order: upper case before lower case, an umlaut after z",
want: []string{"Zebra.txt", "apple.txt", "Übung.txt"}},
{id: 8, query: `mediatype:image`, orderBy: []*searchService.SortProperty{desc("photo.takenDateTime")},
reads: "latest photo first, a file without a date last",
want: []string{"x.jpg", "y.jpg", "z.jpg"}},
{id: 9, query: `mediatype:image`, orderBy: []*searchService.SortProperty{asc("photo.takenDateTime")},
reads: "earliest photo first, a file without a date still last",
want: []string{"y.jpg", "x.jpg", "z.jpg"}},
{id: 10, query: `mediatype:audio`, orderBy: []*searchService.SortProperty{asc("Tags")},
reads: "a field with several values is not sortable", wantBadRequest: true},
{id: 11, query: `mediatype:audio`, orderBy: []*searchService.SortProperty{asc("nonexistent")},
reads: "an unknown field is not sortable", wantBadRequest: true},
},
},
}
}
var _ = Describe("Sorting", func() {
for groupAt, group := range sortGroups() {
Describe(group.name, Ordered, ContinueOnFailure, func() {
var engines []testEngine
BeforeAll(func() {
engines = newEngines("opencloud-test-engine-parity-sort-"+group.name, group.fixtures)
})
for caseAt, c := range group.cases {
row := matrixRow{
Section: "Sorting", Group: group.name, ID: c.label(),
Query: c.query, Reads: c.reads,
Want: c.want, WantBadRequest: c.wantBadRequest, Ordered: true,
GroupAt: 200 + groupAt, CaseAt: caseAt,
}
planRow(row)
Describe(c.label()+" "+c.reads, func() {
for _, name := range engineNames {
It("on "+name, func() {
e := engineNamed(engines, name)
if e.unavailable != "" {
recordSkip(row, name)
Skip(e.unavailable)
}
request, err := query(c.query, nil, 0)
Expect(err).NotTo(HaveOccurred(), "the query of a sort case has to parse")
request.OrderBy = c.orderBy
resp, err := e.backend.Search(context.Background(), request)
if c.wantBadRequest {
recordAnswer(row, name, badRequestAnswer(err))
Expect(err).To(BeAssignableToTypeOf(errtypes.BadRequest("")))
return
}
Expect(err).NotTo(HaveOccurred(), "the query has to answer")
answer := make([]string, 0, len(resp.Matches))
for _, m := range resp.Matches {
answer = append(answer, m.GetEntity().GetName())
}
recordAnswer(row, name, answer)
Expect(answer).To(Equal(c.want))
})
}
})
}
})
}
})
+1
View File
@@ -55,6 +55,7 @@ type IndexQuery struct {
PageSize *int32
Aggregations []*searchsvc.AggregationOption
AggregationFilters []*searchsvc.AggregationFilter
OrderBy []*searchsvc.SortProperty
}
// IndexResult is what the engine answers: the matches of one space and how
+10 -2
View File
@@ -356,8 +356,15 @@ func (s *Service) Search(ctx context.Context, req *searchsvc.SearchRequest) (*se
return nil, errtypes.BadRequest(err.Error())
}
// compile one sorted list of matches from all spaces and apply from/limit if needed
sort.Sort(matches)
// every engine answers in order_by order (by score without one); the merge
// re-establishes it across spaces, ties by score and id
orderBy := req.GetOrderBy()
sort.SliceStable(matches, func(i, j int) bool {
if c := CompareMatches(matches[i], matches[j], orderBy); c != 0 {
return c < 0
}
return matches.Less(i, j)
})
limit := PageSizeOrDefault(req.PageSize)
if from := int(req.GetFrom()); from > 0 {
if from < len(matches) {
@@ -528,6 +535,7 @@ func (s *Service) searchIndex(ctx context.Context, req *searchsvc.SearchRequest,
Query: expanded,
Aggregations: req.GetAggregations(),
AggregationFilters: req.GetAggregationFilters(),
OrderBy: req.GetOrderBy(),
Ref: &searchmsg.Reference{
ResourceId: searchRootID,
Path: searchPathPrefix,
@@ -22,6 +22,7 @@ import (
"github.com/stretchr/testify/mock"
"google.golang.org/grpc"
"google.golang.org/protobuf/testing/protocmp"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/opencloud-eu/opencloud/pkg/conversions"
"github.com/opencloud-eu/opencloud/pkg/log"
@@ -1013,6 +1014,48 @@ var _ = Describe("Searchprovider", func() {
})
})
Context("with two personal spaces returning photos", func() {
photoMatch := func(space, name string, taken int64, score float32) *searchmsg.Match {
return &searchmsg.Match{Score: score, Entity: &searchmsg.Entity{
Id: &searchmsg.ResourceID{StorageId: "storageid", SpaceId: space, OpaqueId: name},
Ref: &searchmsg.Reference{ResourceId: &searchmsg.ResourceID{StorageId: "storageid", SpaceId: space, OpaqueId: space}, Path: "./" + name},
Name: name,
Photo: &searchmsg.Photo{TakenDateTime: &timestamppb.Timestamp{Seconds: taken}},
}}
}
names := func(req *searchsvc.SearchRequest) []string {
res, err := s.Search(ctx, req)
Expect(err).ToNot(HaveOccurred())
out := []string{}
for _, m := range res.Matches {
out = append(out, m.GetEntity().GetName())
}
return out
}
BeforeEach(func() {
listsSpacesAB()
searchOfSpace("a").Return(&search.IndexResult{TotalMatches: 2, Matches: []*searchmsg.Match{
photoMatch("a", "a-old.jpg", 100, 0.9), photoMatch("a", "a-new.jpg", 300, 0.1),
}}, nil)
searchOfSpace("b").Return(&search.IndexResult{TotalMatches: 2, Matches: []*searchmsg.Match{
photoMatch("b", "b-newest.jpg", 400, 0.5), photoMatch("b", "b-mid.jpg", 200, 0.4),
}}, nil)
})
It("forwards order_by to the engine and merges matches across spaces in that order", func() {
byTaken := []*searchsvc.SortProperty{{Name: "photo.takenDateTime", IsDescending: true}}
Expect(names(&searchsvc.SearchRequest{Query: "mediatype:image", OrderBy: byTaken})).To(Equal([]string{"b-newest.jpg", "a-new.jpg", "b-mid.jpg", "a-old.jpg"}))
indexClient.AssertCalled(GinkgoT(), "Search", mock.Anything, mock.MatchedBy(func(req *search.IndexQuery) bool {
return len(req.OrderBy) == 1 && req.OrderBy[0].GetName() == "photo.takenDateTime" && req.OrderBy[0].GetIsDescending()
}))
})
It("merges matches by score when no order_by is given", func() {
Expect(names(&searchsvc.SearchRequest{Query: "mediatype:image"})).To(Equal([]string{"a-old.jpg", "b-newest.jpg", "b-mid.jpg", "a-new.jpg"}))
})
})
Context("with two personal spaces returning matches of the same score", func() {
match := func(space, name string) *searchmsg.Match {
return &searchmsg.Match{Score: 1, Entity: &searchmsg.Entity{
+268
View File
@@ -0,0 +1,268 @@
package search
import (
"reflect"
"strings"
"time"
"google.golang.org/protobuf/reflect/protoreflect"
searchmsg "github.com/opencloud-eu/opencloud/protogen/gen/opencloud/messages/search/v0"
searchsvc "github.com/opencloud-eu/opencloud/protogen/gen/opencloud/services/search/v0"
)
// Sorting support for search results (graph sortProperties / proto order_by).
//
// A field is sortable when both of the following hold:
// - it is indexed as a scalar (string, number, bool or time), so the
// engines can sort on it natively; multivalued fields like Tags are not
// sortable
// - it is carried on the match entity, so the service layer can read the
// sort key when merging the per-space result streams
//
// Both sets are derived by reflection (index side: the Resource type, match
// side: the Entity proto), so new facet fields become sortable automatically.
// sortIndexAliases maps the graph-facing names of top-level fields to their
// index field names. Facet fields (photo.*, audio.*, ...) share the same
// dotted names in both worlds and need no alias. Top-level fields are only
// exposed under these graph names; internal fields like RootID or Deleted
// stay unsortable.
var sortIndexAliases = map[string]string{
"name": "Name",
"size": "Size",
"lastModifiedDateTime": "Mtime",
"mimeType": "MimeType",
}
// entityJSONAliases maps graph-facing names to the Entity proto's JSON names
// where the two disagree.
var entityJSONAliases = map[string]string{
"lastModifiedDateTime": "lastModifiedTime",
}
// IsSortableField reports whether results can be sorted by the field.
func IsSortableField(name string) bool {
_, ok := SortIndexField(name)
return ok
}
// SortIndexField translates a graph sortProperties name into the index field
// name to sort on, reporting whether the field is sortable at all.
func SortIndexField(name string) (string, bool) {
field := name
if alias, ok := sortIndexAliases[name]; ok {
field = alias
} else if !strings.Contains(name, ".") {
return "", false
}
if !sortableIndexFields[field] {
return "", false
}
if !entityFieldResolvable(name) {
return "", false
}
return field, true
}
// CompareMatches orders match a relative to b according to orderBy: -1 when a
// comes first, 1 when b comes first, 0 when the sort keys tie (callers fall
// back to the score). Matches missing a sort key sort after those that have
// it, regardless of direction.
func CompareMatches(a, b *searchmsg.Match, orderBy []*searchsvc.SortProperty) int {
for _, sp := range orderBy {
ka := matchSortKey(a, sp.GetName())
kb := matchSortKey(b, sp.GetName())
if !ka.present && !kb.present {
continue
}
if !ka.present {
return 1
}
if !kb.present {
return -1
}
c := 0
switch {
case ka.isString:
c = strings.Compare(ka.str, kb.str)
case ka.num < kb.num:
c = -1
case ka.num > kb.num:
c = 1
}
if c == 0 {
continue
}
if sp.GetIsDescending() {
c = -c
}
return c
}
return 0
}
// sortableIndexFields is the set of scalar indexed fields, keyed by index
// field name.
var sortableIndexFields = buildSortableFieldSet()
var timeType = reflect.TypeOf(time.Time{})
func jsonFieldName(f reflect.StructField) string {
tag := f.Tag.Get("json")
if tag == "" {
return f.Name
}
return strings.Split(tag, ",")[0]
}
func buildSortableFieldSet() map[string]bool {
out := map[string]bool{}
collectScalarFields(out, "", reflect.TypeOf(Resource{}))
return out
}
func collectScalarFields(out map[string]bool, prefix string, t reflect.Type) {
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
if t.Kind() != reflect.Struct {
return
}
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
if !f.IsExported() {
continue
}
if f.Anonymous {
collectScalarFields(out, prefix, f.Type)
continue
}
path := prefix + jsonFieldName(f)
ft := f.Type
for ft.Kind() == reflect.Ptr {
ft = ft.Elem()
}
switch ft.Kind() {
case reflect.String, reflect.Bool,
reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
reflect.Float32, reflect.Float64:
out[path] = true
case reflect.Struct:
if ft == timeType {
out[path] = true
continue
}
collectScalarFields(out, path+".", ft)
}
}
}
func entityPath(name string) []string {
if alias, ok := entityJSONAliases[name]; ok {
name = alias
}
return strings.Split(name, ".")
}
const timestampFullName = protoreflect.FullName("google.protobuf.Timestamp")
// entityFieldResolvable reports whether the graph field name resolves to a
// scalar (or timestamp) field on the match entity.
func entityFieldResolvable(name string) bool {
md := (&searchmsg.Entity{}).ProtoReflect().Descriptor()
segments := entityPath(name)
for i, seg := range segments {
fd := md.Fields().ByJSONName(seg)
if fd == nil || fd.IsList() || fd.IsMap() {
return false
}
if i < len(segments)-1 {
if fd.Kind() != protoreflect.MessageKind {
return false
}
md = fd.Message()
continue
}
switch fd.Kind() {
case protoreflect.StringKind, protoreflect.BoolKind,
protoreflect.Int32Kind, protoreflect.Int64Kind,
protoreflect.Sint32Kind, protoreflect.Sint64Kind,
protoreflect.Sfixed32Kind, protoreflect.Sfixed64Kind,
protoreflect.Uint32Kind, protoreflect.Uint64Kind,
protoreflect.Fixed32Kind, protoreflect.Fixed64Kind,
protoreflect.FloatKind, protoreflect.DoubleKind:
return true
case protoreflect.MessageKind:
return fd.Message().FullName() == timestampFullName
}
return false
}
return false
}
// sortKey is the comparable value of a sort field on a concrete match.
type sortKey struct {
present bool
isString bool
str string
num float64
}
// matchSortKey extracts the sort key for the graph field name from a match by
// walking the entity proto along the field's JSON names.
func matchSortKey(m *searchmsg.Match, name string) sortKey {
entity := m.GetEntity()
if entity == nil {
return sortKey{}
}
msg := entity.ProtoReflect()
segments := entityPath(name)
for i, seg := range segments {
fd := msg.Descriptor().Fields().ByJSONName(seg)
if fd == nil || fd.IsList() || fd.IsMap() {
return sortKey{}
}
if i < len(segments)-1 {
if fd.Kind() != protoreflect.MessageKind || !msg.Has(fd) {
return sortKey{}
}
msg = msg.Get(fd).Message()
continue
}
if fd.HasPresence() && !msg.Has(fd) {
return sortKey{}
}
v := msg.Get(fd)
switch fd.Kind() {
case protoreflect.StringKind:
return sortKey{present: true, isString: true, str: v.String()}
case protoreflect.BoolKind:
num := 0.0
if v.Bool() {
num = 1.0
}
return sortKey{present: true, num: num}
case protoreflect.Int32Kind, protoreflect.Int64Kind,
protoreflect.Sint32Kind, protoreflect.Sint64Kind,
protoreflect.Sfixed32Kind, protoreflect.Sfixed64Kind:
return sortKey{present: true, num: float64(v.Int())}
case protoreflect.Uint32Kind, protoreflect.Uint64Kind,
protoreflect.Fixed32Kind, protoreflect.Fixed64Kind:
return sortKey{present: true, num: float64(v.Uint())}
case protoreflect.FloatKind, protoreflect.DoubleKind:
return sortKey{present: true, num: v.Float()}
case protoreflect.MessageKind:
if fd.Message().FullName() != timestampFullName {
return sortKey{}
}
ts := v.Message()
seconds := ts.Get(ts.Descriptor().Fields().ByName("seconds")).Int()
nanos := ts.Get(ts.Descriptor().Fields().ByName("nanos")).Int()
return sortKey{present: true, num: float64(seconds) + float64(nanos)/1e9}
}
return sortKey{}
}
return sortKey{}
}
+125
View File
@@ -0,0 +1,125 @@
package search_test
import (
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"google.golang.org/protobuf/types/known/timestamppb"
searchmsg "github.com/opencloud-eu/opencloud/protogen/gen/opencloud/messages/search/v0"
searchsvc "github.com/opencloud-eu/opencloud/protogen/gen/opencloud/services/search/v0"
"github.com/opencloud-eu/opencloud/services/search/pkg/search"
)
var _ = Describe("SortIndexField", func() {
DescribeTable("maps graph field names to index fields",
func(name string, wantField string, wantOK bool) {
field, ok := search.SortIndexField(name)
Expect(ok).To(Equal(wantOK))
Expect(field).To(Equal(wantField))
},
// top-level fields are exposed under their graph names
Entry("name", "name", "Name", true),
Entry("size", "size", "Size", true),
Entry("lastModifiedDateTime", "lastModifiedDateTime", "Mtime", true),
Entry("mimeType", "mimeType", "MimeType", true),
// facet fields keep their dotted names
Entry("photo.takenDateTime", "photo.takenDateTime", "photo.takenDateTime", true),
Entry("photo.iso", "photo.iso", "photo.iso", true),
Entry("photo.cameraModel", "photo.cameraModel", "photo.cameraModel", true),
Entry("audio.artist", "audio.artist", "audio.artist", true),
Entry("audio.year", "audio.year", "audio.year", true),
Entry("image.width", "image.width", "image.width", true),
Entry("location.latitude", "location.latitude", "location.latitude", true),
// bare facets (message-typed, no scalar value) are not sortable
Entry("audio (bare facet)", "audio", "", false),
Entry("photo (bare facet)", "photo", "", false),
Entry("location (bare facet)", "location", "", false),
Entry("location (dotted but not scalar)", "location.", "", false),
// multivalued fields are not sortable
Entry("tags (repeated)", "tags", "", false),
Entry("Tags (index name, repeated)", "Tags", "", false),
// internal index fields are not exposed under their index names
Entry("Name (index name)", "Name", "", false),
Entry("Mtime (index name)", "Mtime", "", false),
Entry("RootID", "RootID", "", false),
Entry("Deleted", "Deleted", "", false),
// unknown fields
Entry("unknown", "definitelyNotAField", "", false),
Entry("unknown facet field", "photo.definitelyNotAField", "", false),
Entry("empty", "", "", false),
)
})
var _ = Describe("CompareMatches", func() {
match := func(mutate func(e *searchmsg.Entity)) *searchmsg.Match {
e := &searchmsg.Entity{}
mutate(e)
return &searchmsg.Match{Entity: e}
}
asc := func(name string) []*searchsvc.SortProperty {
return []*searchsvc.SortProperty{{Name: name}}
}
desc := func(name string) []*searchsvc.SortProperty {
return []*searchsvc.SortProperty{{Name: name, IsDescending: true}}
}
It("compares string fields lexicographically", func() {
a := match(func(e *searchmsg.Entity) { e.Name = "a.jpg" })
b := match(func(e *searchmsg.Entity) { e.Name = "b.jpg" })
Expect(search.CompareMatches(a, b, asc("name"))).To(Equal(-1))
Expect(search.CompareMatches(b, a, asc("name"))).To(Equal(1))
Expect(search.CompareMatches(a, b, desc("name"))).To(Equal(1))
})
It("compares numeric fields numerically", func() {
small := match(func(e *searchmsg.Entity) { e.Size = 9 })
big := match(func(e *searchmsg.Entity) { e.Size = 10 })
Expect(search.CompareMatches(small, big, asc("size"))).To(Equal(-1))
Expect(search.CompareMatches(small, big, desc("size"))).To(Equal(1))
})
It("compares timestamps", func() {
older := match(func(e *searchmsg.Entity) {
e.Photo = &searchmsg.Photo{TakenDateTime: &timestamppb.Timestamp{Seconds: 100}}
})
newer := match(func(e *searchmsg.Entity) {
e.Photo = &searchmsg.Photo{TakenDateTime: &timestamppb.Timestamp{Seconds: 200}}
})
Expect(search.CompareMatches(older, newer, asc("photo.takenDateTime"))).To(Equal(-1))
Expect(search.CompareMatches(older, newer, desc("photo.takenDateTime"))).To(Equal(1))
})
It("compares lastModifiedDateTime via the entity's lastModifiedTime", func() {
older := match(func(e *searchmsg.Entity) {
e.LastModifiedTime = &timestamppb.Timestamp{Seconds: 100}
})
newer := match(func(e *searchmsg.Entity) {
e.LastModifiedTime = &timestamppb.Timestamp{Seconds: 200}
})
Expect(search.CompareMatches(older, newer, asc("lastModifiedDateTime"))).To(Equal(-1))
})
It("sorts matches missing the field after those that have it, in both directions", func() {
has := match(func(e *searchmsg.Entity) {
e.Photo = &searchmsg.Photo{TakenDateTime: &timestamppb.Timestamp{Seconds: 100}}
})
missing := match(func(e *searchmsg.Entity) {})
Expect(search.CompareMatches(has, missing, asc("photo.takenDateTime"))).To(Equal(-1))
Expect(search.CompareMatches(missing, has, asc("photo.takenDateTime"))).To(Equal(1))
Expect(search.CompareMatches(has, missing, desc("photo.takenDateTime"))).To(Equal(-1))
})
It("falls through to the next sort property on ties", func() {
a := match(func(e *searchmsg.Entity) { e.Size = 5; e.Name = "a" })
b := match(func(e *searchmsg.Entity) { e.Size = 5; e.Name = "b" })
orderBy := []*searchsvc.SortProperty{{Name: "size"}, {Name: "name"}}
Expect(search.CompareMatches(a, b, orderBy)).To(Equal(-1))
})
It("returns 0 for full ties and empty orderBy", func() {
a := match(func(e *searchmsg.Entity) { e.Size = 5 })
b := match(func(e *searchmsg.Entity) { e.Size = 5 })
Expect(search.CompareMatches(a, b, asc("size"))).To(Equal(0))
Expect(search.CompareMatches(a, b, nil)).To(Equal(0))
})
})