1// Copyright 2012-2015 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
5package elastic
6
7// WildcardQuery matches documents that have fields matching a wildcard
8// expression (not analyzed). Supported wildcards are *, which matches
9// any character sequence (including the empty one), and ?, which matches
10// any single character. Note this query can be slow, as it needs to iterate
11// over many terms. In order to prevent extremely slow wildcard queries,
12// a wildcard term should not start with one of the wildcards * or ?.
13// The wildcard query maps to Lucene WildcardQuery.
14//
15// For more details, see
16// http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-wildcard-query.html.
17type WildcardQuery struct {
18	Query
19
20	name      string
21	wildcard  string
22	boost     float32
23	rewrite   string
24	queryName string
25}
26
27// NewWildcardQuery creates a new wildcard query.
28func NewWildcardQuery(name, wildcard string) WildcardQuery {
29	q := WildcardQuery{
30		name:     name,
31		wildcard: wildcard,
32		boost:    -1.0,
33	}
34	return q
35}
36
37// Name is the name of the field name.
38func (q WildcardQuery) Name(name string) WildcardQuery {
39	q.name = name
40	return q
41}
42
43// Wildcard is the wildcard to be used in the query, e.g. ki*y??.
44func (q WildcardQuery) Wildcard(wildcard string) WildcardQuery {
45	q.wildcard = wildcard
46	return q
47}
48
49// Boost sets the boost for this query.
50func (q WildcardQuery) Boost(boost float32) WildcardQuery {
51	q.boost = boost
52	return q
53}
54
55// Rewrite controls the rewriting.
56// See http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-multi-term-rewrite.html
57// for details.
58func (q WildcardQuery) Rewrite(rewrite string) WildcardQuery {
59	q.rewrite = rewrite
60	return q
61}
62
63// QueryName sets the name of this query.
64func (q WildcardQuery) QueryName(queryName string) WildcardQuery {
65	q.queryName = queryName
66	return q
67}
68
69// Source returns the JSON serializable body of this query.
70func (q WildcardQuery) Source() interface{} {
71	// {
72	//	"wildcard" : {
73	//		"user" : {
74	//      "wildcard" : "ki*y",
75	//      "boost" : 1.0
76	//    }
77	// }
78
79	source := make(map[string]interface{})
80
81	query := make(map[string]interface{})
82	source["wildcard"] = query
83
84	wq := make(map[string]interface{})
85	query[q.name] = wq
86
87	wq["wildcard"] = q.wildcard
88
89	if q.boost != -1.0 {
90		wq["boost"] = q.boost
91	}
92	if q.rewrite != "" {
93		wq["rewrite"] = q.rewrite
94	}
95	if q.queryName != "" {
96		wq["_name"] = q.queryName
97	}
98
99	return source
100}
101