summaryrefslogtreecommitdiffstats
path: root/vendor/github.com/olivere/elastic/explain.go
blob: 2b975ad5d23e0a9c894c45d44a164273cf626e16 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
// Copyright 2012-present Oliver Eilhard. All rights reserved.
// Use of this source code is governed by a MIT-license.
// See http://olivere.mit-license.org/license.txt for details.

package elastic

import (
	"context"
	"fmt"
	"net/url"
	"strings"

	"github.com/olivere/elastic/uritemplates"
)

// ExplainService computes a score explanation for a query and
// a specific document.
// See https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-explain.html.
type ExplainService struct {
	client                 *Client
	pretty                 bool
	id                     string
	index                  string
	typ                    string
	q                      string
	routing                string
	lenient                *bool
	analyzer               string
	df                     string
	fields                 []string
	lowercaseExpandedTerms *bool
	xSourceInclude         []string
	analyzeWildcard        *bool
	parent                 string
	preference             string
	xSource                []string
	defaultOperator        string
	xSourceExclude         []string
	source                 string
	bodyJson               interface{}
	bodyString             string
}

// NewExplainService creates a new ExplainService.
func NewExplainService(client *Client) *ExplainService {
	return &ExplainService{
		client:         client,
		xSource:        make([]string, 0),
		xSourceExclude: make([]string, 0),
		fields:         make([]string, 0),
		xSourceInclude: make([]string, 0),
	}
}

// Id is the document ID.
func (s *ExplainService) Id(id string) *ExplainService {
	s.id = id
	return s
}

// Index is the name of the index.
func (s *ExplainService) Index(index string) *ExplainService {
	s.index = index
	return s
}

// Type is the type of the document.
func (s *ExplainService) Type(typ string) *ExplainService {
	s.typ = typ
	return s
}

// Source is the URL-encoded query definition (instead of using the request body).
func (s *ExplainService) Source(source string) *ExplainService {
	s.source = source
	return s
}

// XSourceExclude is a list of fields to exclude from the returned _source field.
func (s *ExplainService) XSourceExclude(xSourceExclude ...string) *ExplainService {
	s.xSourceExclude = append(s.xSourceExclude, xSourceExclude...)
	return s
}

// Lenient specifies whether format-based query failures
// (such as providing text to a numeric field) should be ignored.
func (s *ExplainService) Lenient(lenient bool) *ExplainService {
	s.lenient = &lenient
	return s
}

// Query in the Lucene query string syntax.
func (s *ExplainService) Q(q string) *ExplainService {
	s.q = q
	return s
}

// Routing sets a specific routing value.
func (s *ExplainService) Routing(routing string) *ExplainService {
	s.routing = routing
	return s
}

// AnalyzeWildcard specifies whether wildcards and prefix queries
// in the query string query should be analyzed (default: false).
func (s *ExplainService) AnalyzeWildcard(analyzeWildcard bool) *ExplainService {
	s.analyzeWildcard = &analyzeWildcard
	return s
}

// Analyzer is the analyzer for the query string query.
func (s *ExplainService) Analyzer(analyzer string) *ExplainService {
	s.analyzer = analyzer
	return s
}

// Df is the default field for query string query (default: _all).
func (s *ExplainService) Df(df string) *ExplainService {
	s.df = df
	return s
}

// Fields is a list of fields to return in the response.
func (s *ExplainService) Fields(fields ...string) *ExplainService {
	s.fields = append(s.fields, fields...)
	return s
}

// LowercaseExpandedTerms specifies whether query terms should be lowercased.
func (s *ExplainService) LowercaseExpandedTerms(lowercaseExpandedTerms bool) *ExplainService {
	s.lowercaseExpandedTerms = &lowercaseExpandedTerms
	return s
}

// XSourceInclude is a list of fields to extract and return from the _source field.
func (s *ExplainService) XSourceInclude(xSourceInclude ...string) *ExplainService {
	s.xSourceInclude = append(s.xSourceInclude, xSourceInclude...)
	return s
}

// DefaultOperator is the default operator for query string query (AND or OR).
func (s *ExplainService) DefaultOperator(defaultOperator string) *ExplainService {
	s.defaultOperator = defaultOperator
	return s
}

// Parent is the ID of the parent document.
func (s *ExplainService) Parent(parent string) *ExplainService {
	s.parent = parent
	return s
}

// Preference specifies the node or shard the operation should be performed on (default: random).
func (s *ExplainService) Preference(preference string) *ExplainService {
	s.preference = preference
	return s
}

// XSource is true or false to return the _source field or not, or a list of fields to return.
func (s *ExplainService) XSource(xSource ...string) *ExplainService {
	s.xSource = append(s.xSource, xSource...)
	return s
}

// Pretty indicates that the JSON response be indented and human readable.
func (s *ExplainService) Pretty(pretty bool) *ExplainService {
	s.pretty = pretty
	return s
}

// Query sets a query definition using the Query DSL.
func (s *ExplainService) Query(query Query) *ExplainService {
	src, err := query.Source()
	if err != nil {
		// Do nothing in case of an error
		return s
	}
	body := make(map[string]interface{})
	body["query"] = src
	s.bodyJson = body
	return s
}

// BodyJson sets the query definition using the Query DSL.
func (s *ExplainService) BodyJson(body interface{}) *ExplainService {
	s.bodyJson = body
	return s
}

// BodyString sets the query definition using the Query DSL as a string.
func (s *ExplainService) BodyString(body string) *ExplainService {
	s.bodyString = body
	return s
}

// buildURL builds the URL for the operation.
func (s *ExplainService) buildURL() (string, url.Values, error) {
	// Build URL
	path, err := uritemplates.Expand("/{index}/{type}/{id}/_explain", map[string]string{
		"id":    s.id,
		"index": s.index,
		"type":  s.typ,
	})
	if err != nil {
		return "", url.Values{}, err
	}

	// Add query string parameters
	params := url.Values{}
	if s.pretty {
		params.Set("pretty", "true")
	}
	if len(s.xSource) > 0 {
		params.Set("_source", strings.Join(s.xSource, ","))
	}
	if s.defaultOperator != "" {
		params.Set("default_operator", s.defaultOperator)
	}
	if s.parent != "" {
		params.Set("parent", s.parent)
	}
	if s.preference != "" {
		params.Set("preference", s.preference)
	}
	if s.source != "" {
		params.Set("source", s.source)
	}
	if len(s.xSourceExclude) > 0 {
		params.Set("_source_exclude", strings.Join(s.xSourceExclude, ","))
	}
	if s.lenient != nil {
		params.Set("lenient", fmt.Sprintf("%v", *s.lenient))
	}
	if s.q != "" {
		params.Set("q", s.q)
	}
	if s.routing != "" {
		params.Set("routing", s.routing)
	}
	if len(s.fields) > 0 {
		params.Set("fields", strings.Join(s.fields, ","))
	}
	if s.lowercaseExpandedTerms != nil {
		params.Set("lowercase_expanded_terms", fmt.Sprintf("%v", *s.lowercaseExpandedTerms))
	}
	if len(s.xSourceInclude) > 0 {
		params.Set("_source_include", strings.Join(s.xSourceInclude, ","))
	}
	if s.analyzeWildcard != nil {
		params.Set("analyze_wildcard", fmt.Sprintf("%v", *s.analyzeWildcard))
	}
	if s.analyzer != "" {
		params.Set("analyzer", s.analyzer)
	}
	if s.df != "" {
		params.Set("df", s.df)
	}
	return path, params, nil
}

// Validate checks if the operation is valid.
func (s *ExplainService) Validate() error {
	var invalid []string
	if s.index == "" {
		invalid = append(invalid, "Index")
	}
	if s.typ == "" {
		invalid = append(invalid, "Type")
	}
	if s.id == "" {
		invalid = append(invalid, "Id")
	}
	if len(invalid) > 0 {
		return fmt.Errorf("missing required fields: %v", invalid)
	}
	return nil
}

// Do executes the operation.
func (s *ExplainService) Do(ctx context.Context) (*ExplainResponse, error) {
	// Check pre-conditions
	if err := s.Validate(); err != nil {
		return nil, err
	}

	// Get URL for request
	path, params, err := s.buildURL()
	if err != nil {
		return nil, err
	}

	// Setup HTTP request body
	var body interface{}
	if s.bodyJson != nil {
		body = s.bodyJson
	} else {
		body = s.bodyString
	}

	// Get HTTP response
	res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
		Method: "GET",
		Path:   path,
		Params: params,
		Body:   body,
	})
	if err != nil {
		return nil, err
	}

	// Return operation response
	ret := new(ExplainResponse)
	if err := s.client.decoder.Decode(res.Body, ret); err != nil {
		return nil, err
	}
	return ret, nil
}

// ExplainResponse is the response of ExplainService.Do.
type ExplainResponse struct {
	Index       string                 `json:"_index"`
	Type        string                 `json:"_type"`
	Id          string                 `json:"_id"`
	Matched     bool                   `json:"matched"`
	Explanation map[string]interface{} `json:"explanation"`
}