forked from olivere/elastic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
search_queries_simple_query_string.go
100 lines (84 loc) · 2.55 KB
/
search_queries_simple_query_string.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
// Copyright 2012-2015 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 (
"fmt"
"strings"
)
// SimpleQueryStringQuery is a query that uses the SimpleQueryParser
// to parse its context. Unlike the regular query_string query,
// the simple_query_string query will never throw an exception,
// and discards invalid parts of the query.
// For more details, see
// http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-simple-query-string-query.html
type SimpleQueryStringQuery struct {
queryText string
analyzer string
operator string
fields []string
fieldBoosts map[string]*float32
}
// Creates a new simple query string query.
func NewSimpleQueryStringQuery(text string) SimpleQueryStringQuery {
q := SimpleQueryStringQuery{
queryText: text,
fields: make([]string, 0),
fieldBoosts: make(map[string]*float32),
}
return q
}
func (q SimpleQueryStringQuery) Field(field string) SimpleQueryStringQuery {
q.fields = append(q.fields, field)
return q
}
func (q SimpleQueryStringQuery) FieldWithBoost(field string, boost float32) SimpleQueryStringQuery {
q.fields = append(q.fields, field)
q.fieldBoosts[field] = &boost
return q
}
func (q SimpleQueryStringQuery) Analyzer(analyzer string) SimpleQueryStringQuery {
q.analyzer = analyzer
return q
}
func (q SimpleQueryStringQuery) DefaultOperator(defaultOperator string) SimpleQueryStringQuery {
q.operator = defaultOperator
return q
}
// Creates the query source for the query string query.
func (q SimpleQueryStringQuery) Source() interface{} {
// {
// "simple_query_string" : {
// "query" : "\"fried eggs\" +(eggplant | potato) -frittata",
// "analyzer" : "snowball",
// "fields" : ["body^5","_all"],
// "default_operator" : "and"
// }
// }
source := make(map[string]interface{})
query := make(map[string]interface{})
source["simple_query_string"] = query
query["query"] = q.queryText
if len(q.fields) > 0 {
fields := make([]string, 0)
for _, field := range q.fields {
if boost, found := q.fieldBoosts[field]; found {
if boost != nil {
fields = append(fields, fmt.Sprintf("%s^%f", field, *boost))
} else {
fields = append(fields, field)
}
} else {
fields = append(fields, field)
}
}
query["fields"] = fields
}
if q.analyzer != "" {
query["analyzer"] = q.analyzer
}
if q.operator != "" {
query["default_operator"] = strings.ToLower(q.operator)
}
return source
}