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
5package elastic
6
7// RegexpQuery allows you to use regular expression term queries.
8//
9// For more details, see
10// https://www.elastic.co/guide/en/elasticsearch/reference/6.7/query-dsl-regexp-query.html
11type RegexpQuery struct {
12	name                  string
13	regexp                string
14	flags                 string
15	boost                 *float64
16	rewrite               string
17	queryName             string
18	maxDeterminizedStates *int
19}
20
21// NewRegexpQuery creates and initializes a new RegexpQuery.
22func NewRegexpQuery(name string, regexp string) *RegexpQuery {
23	return &RegexpQuery{name: name, regexp: regexp}
24}
25
26// Flags sets the regexp flags.
27func (q *RegexpQuery) Flags(flags string) *RegexpQuery {
28	q.flags = flags
29	return q
30}
31
32// MaxDeterminizedStates protects against complex regular expressions.
33func (q *RegexpQuery) MaxDeterminizedStates(maxDeterminizedStates int) *RegexpQuery {
34	q.maxDeterminizedStates = &maxDeterminizedStates
35	return q
36}
37
38// Boost sets the boost for this query.
39func (q *RegexpQuery) Boost(boost float64) *RegexpQuery {
40	q.boost = &boost
41	return q
42}
43
44func (q *RegexpQuery) Rewrite(rewrite string) *RegexpQuery {
45	q.rewrite = rewrite
46	return q
47}
48
49// QueryName sets the query name for the filter that can be used
50// when searching for matched_filters per hit
51func (q *RegexpQuery) QueryName(queryName string) *RegexpQuery {
52	q.queryName = queryName
53	return q
54}
55
56// Source returns the JSON-serializable query data.
57func (q *RegexpQuery) Source() (interface{}, error) {
58	source := make(map[string]interface{})
59	query := make(map[string]interface{})
60	source["regexp"] = query
61
62	x := make(map[string]interface{})
63	x["value"] = q.regexp
64	if q.flags != "" {
65		x["flags"] = q.flags
66	}
67	if q.maxDeterminizedStates != nil {
68		x["max_determinized_states"] = *q.maxDeterminizedStates
69	}
70	if q.boost != nil {
71		x["boost"] = *q.boost
72	}
73	if q.rewrite != "" {
74		x["rewrite"] = q.rewrite
75	}
76	if q.queryName != "" {
77		x["name"] = q.queryName
78	}
79	query[q.name] = x
80
81	return source, nil
82}
83