esquery/queries.go
Ido Perlmuter 48ad6f919c Bugfix: Run() fails for queries, add MarshalJSON()
The `Run()` method on the `QueryRequest` type would fail, since it would
encode the _inner_ body of the query to JSON and not the complete, outer
body (i.e. including the "body: {}" portion).

The commit also adds `MarshalJSON()` methods to both `QueryRequest` and
`AggregationRequest`, allowing them to implement the `json.Marshaller`
interface, and providing easier debugging of the library. A test
skeleton for this is also added.
2020-02-20 16:46:27 +02:00

43 lines
814 B
Go

package esquery
import (
"bytes"
"encoding/json"
"github.com/elastic/go-elasticsearch/v7"
"github.com/elastic/go-elasticsearch/v7/esapi"
)
type QueryRequest struct {
Query Mappable
}
func Query(q Mappable) *QueryRequest {
return &QueryRequest{q}
}
func (req *QueryRequest) Map() map[string]interface{} {
return map[string]interface{}{
"query": req.Query.Map(),
}
}
func (req *QueryRequest) MarshalJSON() ([]byte, error) {
return json.Marshal(req.Map())
}
func (req *QueryRequest) Run(
api *elasticsearch.Client,
o ...func(*esapi.SearchRequest),
) (res *esapi.Response, err error) {
var b bytes.Buffer
err = json.NewEncoder(&b).Encode(req.Map())
if err != nil {
return nil, err
}
opts := append([]func(*esapi.SearchRequest){api.Search.WithBody(&b)}, o...)
return api.Search(opts...)
}