From 1c8d8628451bbc10476b361232885823adf0642b Mon Sep 17 00:00:00 2001
From: Jan Semmelink <jan@uafrica.com>
Date: Tue, 23 Nov 2021 13:49:04 +0200
Subject: [PATCH] Added parameter to search to specify sort order of search
 results

---
 search/opensearch_types.go | 5 +++--
 search/search_test.go      | 2 +-
 search/time_series.go      | 6 ++++--
 3 files changed, 8 insertions(+), 5 deletions(-)

diff --git a/search/opensearch_types.go b/search/opensearch_types.go
index cdbe211..6829316 100644
--- a/search/opensearch_types.go
+++ b/search/opensearch_types.go
@@ -34,8 +34,9 @@ type MappingKeyword struct {
 }
 
 type SearchRequestBody struct {
-	Size  int64 `json:"size,omitempty"`
-	Query Query `json:"query"`
+	Size  int64               `json:"size,omitempty"`
+	Query Query               `json:"query"`
+	Sort  []map[string]string `json:"sort,omitempty" doc:"List of name:<asc|desc> e.g. \"@timestamp\":\"desc\""`
 }
 
 type Query struct {
diff --git a/search/search_test.go b/search/search_test.go
index 8a03042..342f68d 100644
--- a/search/search_test.go
+++ b/search/search_test.go
@@ -74,7 +74,7 @@ func test(t *testing.T, c search.Config) {
 		},
 	}
 
-	docs, totalCount, err := ts.Search(query, 10)
+	docs, totalCount, err := ts.Search(query, nil, 10)
 	if err != nil {
 		t.Errorf("failed to search: %+v", err)
 	} else {
diff --git a/search/time_series.go b/search/time_series.go
index 1b39cb9..b33a354 100644
--- a/search/time_series.go
+++ b/search/time_series.go
@@ -27,7 +27,7 @@ type TimeSeriesHeader struct {
 
 type TimeSeries interface {
 	Write(StartTime time.Time, EndTime time.Time, data interface{}) error
-	Search(query Query, limit int64) (docs interface{}, totalCount int, err error)
+	Search(query Query, sort []map[string]string, limit int64) (docs interface{}, totalCount int, err error)
 }
 
 type timeSeries struct {
@@ -360,7 +360,7 @@ type IndexSettings struct {
 //Search
 //Return:
 //	docs will be a slice of the TimeSeries data type
-func (ts *timeSeries) Search(query Query, limit int64) (docs interface{}, totalCount int, err error) {
+func (ts *timeSeries) Search(query Query, sort []map[string]string, limit int64) (docs interface{}, totalCount int, err error) {
 	if ts == nil {
 		return nil, 0, errors.Errorf("time series == nil")
 	}
@@ -372,6 +372,7 @@ func (ts *timeSeries) Search(query Query, limit int64) (docs interface{}, totalC
 	// example search request body for free text
 	// 	{
 	// 		"size": 5,
+	//		"sort": [{"@timestamp":"desc"}]
 	// 		"query": {
 	// 			"multi_match": {
 	// 				"query": "miller",
@@ -382,6 +383,7 @@ func (ts *timeSeries) Search(query Query, limit int64) (docs interface{}, totalC
 	body := SearchRequestBody{
 		Size:  limit,
 		Query: query,
+		Sort:  sort,
 	}
 
 	jsonBody, _ := json.Marshal(body)
-- 
GitLab