| 1 |
// Copyright 2012-present Oliver Eilhard. All rights reserved. |
| 2 |
// Use of this source code is governed by a MIT-license. |
| 3 |
// See http://olivere.mit-license.org/license.txt for details. |
| 4 |
|
| 5 |
package elastic |
| 6 |
|
| 7 |
import "errors" |
| 8 |
|
| 9 |
// ScriptQuery allows to define scripts as filters. |
| 10 |
// |
| 11 |
// For details, see |
| 12 |
// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-script-query.html |
| 13 |
type ScriptQuery struct { |
| 14 |
script *Script |
| 15 |
queryName string |
| 16 |
} |
| 17 |
|
| 18 |
// NewScriptQuery creates and initializes a new ScriptQuery. |
| 19 |
func NewScriptQuery(script *Script) *ScriptQuery { |
| 20 |
return &ScriptQuery{ |
| 21 |
script: script, |
| 22 |
} |
| 23 |
} |
| 24 |
|
| 25 |
// QueryName sets the query name for the filter that can be used |
| 26 |
// when searching for matched_filters per hit |
| 27 |
func (q *ScriptQuery) QueryName(queryName string) *ScriptQuery { |
| 28 |
q.queryName = queryName |
| 29 |
return q |
| 30 |
} |
| 31 |
|
| 32 |
// Source returns JSON for the query. |
| 33 |
func (q *ScriptQuery) Source() (interface{}, error) { |
| 34 |
if q.script == nil { |
| 35 |
return nil, errors.New("ScriptQuery expected a script") |
| 36 |
} |
| 37 |
source := make(map[string]interface{}) |
| 38 |
params := make(map[string]interface{}) |
| 39 |
source["script"] = params |
| 40 |
|
| 41 |
src, err := q.script.Source() |
| 42 |
if err != nil { |
| 43 |
return nil, err |
| 44 |
} |
| 45 |
params["script"] = src |
| 46 |
|
| 47 |
if q.queryName != "" { |
| 48 |
params["_name"] = q.queryName |
| 49 |
} |
| 50 |
return source, nil |
| 51 |
} |