feat: add collapse search result function

This commit is contained in:
Hardy 2021-07-17 16:22:41 +08:00
parent 00431fc79f
commit 09ed23b5e5
2 changed files with 22 additions and 3 deletions

View File

@ -26,7 +26,7 @@ type SearchRequest struct {
sort Sort sort Sort
source Source source Source
timeout *time.Duration timeout *time.Duration
collapse map[string]interface{}
} }
// Search creates a new SearchRequest object, to be filled via method chaining. // Search creates a new SearchRequest object, to be filled via method chaining.
@ -76,6 +76,14 @@ func (req *SearchRequest) Sort(name string, order Order) *SearchRequest {
return req return req
} }
// Collapse the results
func (req *SearchRequest) Collapse(field string) *SearchRequest {
req.collapse = map[string]interface{}{
"field": field,
}
return req
}
// SearchAfter retrieve the sorted result // SearchAfter retrieve the sorted result
func (req *SearchRequest) SearchAfter(s ...interface{}) *SearchRequest { func (req *SearchRequest) SearchAfter(s ...interface{}) *SearchRequest {
req.searchAfter = append(req.searchAfter, s...) req.searchAfter = append(req.searchAfter, s...)
@ -113,8 +121,6 @@ func (req *SearchRequest) Highlight(highlight Mappable) *SearchRequest {
return req return req
} }
// Map implements the Mappable interface. It converts the request to into a // Map implements the Mappable interface. It converts the request to into a
// nested map[string]interface{}, as expected by the go-elasticsearch library. // nested map[string]interface{}, as expected by the go-elasticsearch library.
func (req *SearchRequest) Map() map[string]interface{} { func (req *SearchRequest) Map() map[string]interface{} {
@ -155,6 +161,9 @@ func (req *SearchRequest) Map() map[string]interface{} {
m["search_after"] = req.searchAfter m["search_after"] = req.searchAfter
} }
if req.collapse != nil {
m["collapse"] = req.collapse
}
source := req.source.Map() source := req.source.Map()
if len(source) > 0 { if len(source) > 0 {

View File

@ -14,6 +14,16 @@ func TestSearchMaps(t *testing.T) {
"search_after": []string{"_id", "name"}, "search_after": []string{"_id", "name"},
}, },
}, },
{
"a simple query with collapse",
Search().Query(Term("user.id", "Tony")).Collapse("user.id"),
map[string]interface{}{
"query": Term("user.id", "Tony").Map(),
"collapse": map[string]interface{}{
"field": "user.id",
},
},
},
{ {
"a simple match_all query with a size and no aggs", "a simple match_all query with a size and no aggs",
Search().Query(MatchAll()).Size(20), Search().Query(MatchAll()).Size(20),