forked from mattbaird/elastigo
/
searchfilter.go
401 lines (343 loc) · 11.9 KB
/
searchfilter.go
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
// Copyright 2013 Matthew Baird
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package elastigo
import (
"encoding/json"
"fmt"
"github.com/araddon/gou"
)
var (
_ = gou.DEBUG
)
// BoolClause represents aa bool (and/or) clause for use with FilterWrap
// Legacy, use new FilterOp functions instead
type BoolClause string
// TermExecutionMode refers to how a terms (not term) filter should behave
// The acceptable options are all prefixed with TEM
// See https://www.elastic.co/guide/en/elasticsearch/reference/1.5/query-dsl-terms-filter.html
type TermExecutionMode string
const (
// TEMDefault default ES term filter behavior (plain)
TEMDefault TermExecutionMode = ""
// TEMPlain default ES term filter behavior
TEMPlain TermExecutionMode = "plain"
// TEMField field_data execution mode
TEMField TermExecutionMode = "field_data"
// TEMBool bool execution mode
TEMBool TermExecutionMode = "bool"
// TEMAnd and execution mode
TEMAnd TermExecutionMode = "and"
// TEMOr or execution mode
TEMOr TermExecutionMode = "or"
)
// FilterClause is either a boolClause or FilterOp for use with FilterWrap
type FilterClause interface {
String() string
}
// FilterWrap is the legacy struct for chaining multiple filters with a bool
// Legacy, use new FilterOp functions instead
type FilterWrap struct {
boolClause string
filters []interface{}
}
// NewFilterWrap creates a new FilterWrap struct
func NewFilterWrap() *FilterWrap {
return &FilterWrap{filters: make([]interface{}, 0), boolClause: "and"}
}
func (f *FilterWrap) String() string {
return fmt.Sprintf(`fopv: %d:%v`, len(f.filters), f.filters)
}
// Bool sets the type of boolean filter to use.
// Accepted values are "and" and "or".
// Legacy, use new FilterOp functions instead
func (f *FilterWrap) Bool(s string) {
f.boolClause = s
}
// Custom marshalling to support the query dsl
func (f *FilterWrap) addFilters(fl []interface{}) {
if len(fl) > 1 {
fc := fl[0]
switch fc.(type) {
case BoolClause, string:
f.boolClause = fc.(string)
fl = fl[1:]
}
}
f.filters = append(f.filters, fl...)
}
// MarshalJSON override for FilterWrap to match the expected ES syntax with the bool at the root
func (f *FilterWrap) MarshalJSON() ([]byte, error) {
var root interface{}
if len(f.filters) > 1 {
root = map[string]interface{}{f.boolClause: f.filters}
} else if len(f.filters) == 1 {
root = f.filters[0]
}
return json.Marshal(root)
}
/*
"filter": {
"range": {
"@timestamp": {
"from": "2012-12-29T16:52:48+00:00",
"to": "2012-12-29T17:52:48+00:00"
}
}
}
"filter": {
"missing": {
"field": "repository.name"
}
}
"filter" : {
"terms" : {
"user" : ["kimchy", "elasticsearch"],
"execution" : "bool",
"_cache": true
}
}
"filter" : {
"term" : { "user" : "kimchy"}
}
"filter" : {
"and" : [
{
"range" : {
"postDate" : {
"from" : "2010-03-01",
"to" : "2010-04-01"
}
}
},
{
"prefix" : { "name.second" : "ba" }
}
]
}
*/
// Filter creates a blank FilterOp that can be customized with further function calls
// This is the starting point for constructing any filter query
// Examples:
//
// Filter().Term("user","kimchy")
//
// // we use variadics to allow n arguments, first is the "field" rest are values
// Filter().Terms("user", "kimchy", "elasticsearch")
//
// Filter().Exists("repository.name")
func Filter() *FilterOp {
return &FilterOp{}
}
// CompoundFilter creates a complete FilterWrap given multiple filters
// Legacy, use new FilterOp functions instead
func CompoundFilter(fl ...interface{}) *FilterWrap {
FilterVal := NewFilterWrap()
FilterVal.addFilters(fl)
return FilterVal
}
// FilterOp holds all the information for a filter query
// Properties should not be set directly, but instead via the fluent-style API.
type FilterOp struct {
TermsMap map[string]interface{} `json:"terms,omitempty"`
TermMap map[string]interface{} `json:"term,omitempty"`
RangeMap map[string]RangeFilter `json:"range,omitempty"`
ExistsProp *propertyPathMarker `json:"exists,omitempty"`
MissingProp *propertyPathMarker `json:"missing,omitempty"`
AndFilters []*FilterOp `json:"and,omitempty"`
OrFilters []*FilterOp `json:"or,omitempty"`
NotFilters []*FilterOp `json:"not,omitempty"`
LimitProp *LimitFilter `json:"limit,omitempty"`
TypeProp *TypeFilter `json:"type,omitempty"`
IdsProp *IdsFilter `json:"ids,omitempty"`
ScriptProp *ScriptFilter `json:"script,omitempty"`
GeoDistMap map[string]interface{} `json:"geo_distance,omitempty"`
GeoDistRangeMap map[string]interface{} `json:"geo_distance_range,omitempty"`
}
type propertyPathMarker struct {
Field string `json:"field"`
}
// LimitFilter holds the Limit filter information
// Value: number of documents to limit
type LimitFilter struct {
Value int `json:"value"`
}
// TypeFilter filters on the document type
// Value: the document type to filter
type TypeFilter struct {
Value string `json:"value"`
}
// IdsFilter holds the type and ids (on the _id field) to filter
// Type: a string or an array of string types. Optional.
// Values: Array of ids to match
type IdsFilter struct {
Type []string `json:"type,omitempty"`
Values []interface{} `json:"values,omitempty"`
}
// ScriptFilter will filter using a custom javascript function
// Script: the javascript to run
// Params: map of custom parameters to pass into the function (JSON), if any
// IsCached: whether to cache the results of the filter
type ScriptFilter struct {
Script string `json:"script"`
Params map[string]interface{} `json:"params,omitempty"`
IsCached bool `json:"_cache,omitempty"`
}
// RangeFilter filters given a range. Parameters need to be comparable for ES to accept.
// Only a minimum of one comparison parameter is required. You probably shouldn't mix GT and GTE parameters.
// Gte: the greater-than-or-equal to value. Should be a number or date.
// Lte: the less-than-or-equal to value. Should be a number or date.
// Gt: the greater-than value. Should be a number or date.
// Lt: the less-than value. Should be a number or date.
// TimeZone: the timezone to use (+|-h:mm format), if the other parameters are dates
type RangeFilter struct {
Gte interface{} `json:"gte,omitempty"`
Lte interface{} `json:"lte,omitempty"`
Gt interface{} `json:"gt,omitempty"`
Lt interface{} `json:"lt,omitempty"`
TimeZone string `json:"time_zone,omitempty"` //Ideally this would be an int
}
// GeoLocation holds the coordinates for a geo query. Currently hashes are not supported.
type GeoLocation struct {
Latitude float32 `json:"lat"`
Longitude float32 `json:"lon"`
}
// GeoField holds a GeoLocation and a field to match to.
// This exists so the struct will match the ES schema.
type GeoField struct {
GeoLocation
Field string
}
// Term will add a term to the filter.
// Multiple Term filters can be added, and ES will OR them.
// If the term already exists in the FilterOp, the value will be overridden.
func (f *FilterOp) Term(field string, value interface{}) *FilterOp {
if len(f.TermMap) == 0 {
f.TermMap = make(map[string]interface{})
}
f.TermMap[field] = value
return f
}
// And will add an AND op to the filter. One or more FilterOps can be passed in.
func (f *FilterOp) And(filters ...*FilterOp) *FilterOp {
if len(f.AndFilters) == 0 {
f.AndFilters = filters[:]
} else {
f.AndFilters = append(f.AndFilters, filters...)
}
return f
}
// Or will add an OR op to the filter. One or more FilterOps can be passed in.
func (f *FilterOp) Or(filters ...*FilterOp) *FilterOp {
if len(f.OrFilters) == 0 {
f.OrFilters = filters[:]
} else {
f.OrFilters = append(f.OrFilters, filters...)
}
return f
}
// Not will add a NOT op to the filter. One or more FilterOps can be passed in.
func (f *FilterOp) Not(filters ...*FilterOp) *FilterOp {
if len(f.NotFilters) == 0 {
f.NotFilters = filters[:]
} else {
f.NotFilters = append(f.NotFilters, filters...)
}
return f
}
// GeoDistance will add a GEO DISTANCE op to the filter.
// distance: distance in ES distance format, i.e. "100km" or "100mi".
// fields: an array of GeoField origin coordinates. Only one coordinate needs to match.
func (f *FilterOp) GeoDistance(distance string, fields ...GeoField) *FilterOp {
f.GeoDistMap = make(map[string]interface{})
f.GeoDistMap["distance"] = distance
for _, val := range fields {
f.GeoDistMap[val.Field] = val.GeoLocation
}
return f
}
// GeoDistanceRange will add a GEO DISTANCE RANGE op to the filter.
// from: minimum distance in ES distance format, i.e. "100km" or "100mi".
// to: maximum distance in ES distance format, i.e. "100km" or "100mi".
// fields: an array of GeoField origin coordinates. Only one coor
func (f *FilterOp) GeoDistanceRange(from string, to string, fields ...GeoField) *FilterOp {
f.GeoDistRangeMap = make(map[string]interface{})
f.GeoDistRangeMap["from"] = from
f.GeoDistRangeMap["to"] = to
for _, val := range fields {
f.GeoDistRangeMap[val.Field] = val.GeoLocation
}
return f
}
// NewGeoField is a helper function to create values for the GeoDistance filters
func NewGeoField(field string, latitude float32, longitude float32) GeoField {
return GeoField{
GeoLocation: GeoLocation{Latitude: latitude, Longitude: longitude},
Field: field}
}
// Terms adds a TERMS op to the filter.
// field: the document field
// executionMode Term execution mode, starts with TEM
// values: array of values to match
// Note: you can only have one terms clause in a filter. Use a bool filter to combine multiple.
func (f *FilterOp) Terms(field string, executionMode TermExecutionMode, values ...interface{}) *FilterOp {
//You can only have one terms in a filter
f.TermsMap = make(map[string]interface{})
if executionMode != "" {
f.TermsMap["execution"] = executionMode
}
f.TermsMap[field] = values
return f
}
// Range adds a range filter for the given field.
// See the RangeFilter struct documentation for information about the parameters.
func (f *FilterOp) Range(field string, gte interface{},
gt interface{}, lte interface{}, lt interface{}, timeZone string) *FilterOp {
if f.RangeMap == nil {
f.RangeMap = make(map[string]RangeFilter)
}
f.RangeMap[field] = RangeFilter{
Gte: gte,
Gt: gt,
Lte: lte,
Lt: lt,
TimeZone: timeZone}
return f
}
// Type adds a TYPE op to the filter.
func (f *FilterOp) Type(fieldType string) *FilterOp {
f.TypeProp = &TypeFilter{Value: fieldType}
return f
}
// Ids adds a IDS op to the filter.
func (f *FilterOp) Ids(ids ...interface{}) *FilterOp {
f.IdsProp = &IdsFilter{Values: ids}
return f
}
// IdsByTypes adds a IDS op to the filter, but also allows passing in an array of types for the query.
func (f *FilterOp) IdsByTypes(types []string, ids ...interface{}) *FilterOp {
f.IdsProp = &IdsFilter{Type: types, Values: ids}
return f
}
// Exists adds an EXISTS op to the filter.
func (f *FilterOp) Exists(field string) *FilterOp {
f.ExistsProp = &propertyPathMarker{Field: field}
return f
}
// Missing adds an MISSING op to the filter.
func (f *FilterOp) Missing(field string) *FilterOp {
f.MissingProp = &propertyPathMarker{Field: field}
return f
}
// Limit adds an LIMIT op to the filter.
func (f *FilterOp) Limit(maxResults int) *FilterOp {
f.LimitProp = &LimitFilter{Value: maxResults}
return f
}