Skip to content

Commit

Permalink
CBB-1170: add collapse support
Browse files Browse the repository at this point in the history
  • Loading branch information
mikesmitharoo committed Aug 27, 2024
1 parent 91b3efc commit 2490b6b
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 0 deletions.
14 changes: 14 additions & 0 deletions collapse.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package query

// Collapse represents the "collapse" param that can be applied to a request
// see: https://www.elastic.co/guide/en/elasticsearch/reference/current/collapse-search-results.html
type Collapse struct {
field string
}

// Map returns a map representation of the Source object.
func (source Collapse) Map() map[string]interface{} {
return map[string]interface{}{
"field": source.field,
}
}
22 changes: 22 additions & 0 deletions collapse_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package query

import (
"testing"
)

func TestCollapse_Map(t *testing.T) {
runMapTests(
t,
[]mapTest{
{
name: "collapse",
q: Collapse{
field: "collapse_field",
},
exp: map[string]interface{}{
"field": "collapse_field",
},
},
},
)
}
11 changes: 11 additions & 0 deletions search.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ type SearchRequest struct {
sorts Sorts
source Source
timeout *time.Duration
collapse *Collapse
}

// Search creates a new SearchRequest object, to be filled via method chaining.
Expand Down Expand Up @@ -107,6 +108,13 @@ func (req *SearchRequest) Highlight(highlight Mappable) *SearchRequest {
return req
}

// Collapse sets the collapse param for the request.
// See:https://www.elastic.co/guide/en/elasticsearch/reference/current/collapse-search-results.html
func (req *SearchRequest) Collapse(collapse *Collapse) *SearchRequest {
req.collapse = collapse
return req
}

// Map implements the Mappable interface. It converts the request to into a
// nested map[string]interface{}, as expected by the go-elasticsearch library.
func (req *SearchRequest) Map() map[string]interface{} {
Expand Down Expand Up @@ -146,6 +154,9 @@ func (req *SearchRequest) Map() map[string]interface{} {
if req.searchAfter != nil {
m["search_after"] = req.searchAfter
}
if req.collapse != nil {
m["collapse"] = req.collapse.Map()
}

source := req.source.Map()
if len(source) > 0 {
Expand Down
13 changes: 13 additions & 0 deletions search_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,5 +132,18 @@ func TestSearchMaps(t *testing.T) {
},
},
},
{
"a simple match_all query with a size and collapse",
Search().Query(MatchAll()).Size(20).Collapse(&Collapse{field: "collapse_field"}),
map[string]interface{}{
"query": map[string]interface{}{
"match_all": map[string]interface{}{},
},
"collapse": map[string]interface{}{
"field": "collapse_field",
},
"size": 20,
},
},
})
}

0 comments on commit 2490b6b

Please sign in to comment.