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// MatchPhraseQuery analyzes the text and creates a phrase query out of
8// the analyzed text.
9//
10// For more details, see
11// https://www.elastic.co/guide/en/elasticsearch/reference/6.7/query-dsl-match-query-phrase.html
12type MatchPhraseQuery struct {
13	name      string
14	value     interface{}
15	analyzer  string
16	slop      *int
17	boost     *float64
18	queryName string
19}
20
21// NewMatchPhraseQuery creates and initializes a new MatchPhraseQuery.
22func NewMatchPhraseQuery(name string, value interface{}) *MatchPhraseQuery {
23	return &MatchPhraseQuery{name: name, value: value}
24}
25
26// Analyzer explicitly sets the analyzer to use. It defaults to use explicit
27// mapping config for the field, or, if not set, the default search analyzer.
28func (q *MatchPhraseQuery) Analyzer(analyzer string) *MatchPhraseQuery {
29	q.analyzer = analyzer
30	return q
31}
32
33// Slop sets the phrase slop if evaluated to a phrase query type.
34func (q *MatchPhraseQuery) Slop(slop int) *MatchPhraseQuery {
35	q.slop = &slop
36	return q
37}
38
39// Boost sets the boost to apply to this query.
40func (q *MatchPhraseQuery) Boost(boost float64) *MatchPhraseQuery {
41	q.boost = &boost
42	return q
43}
44
45// QueryName sets the query name for the filter that can be used when
46// searching for matched filters per hit.
47func (q *MatchPhraseQuery) QueryName(queryName string) *MatchPhraseQuery {
48	q.queryName = queryName
49	return q
50}
51
52// Source returns JSON for the function score query.
53func (q *MatchPhraseQuery) Source() (interface{}, error) {
54	// {"match_phrase":{"name":{"query":"value","analyzer":"my_analyzer"}}}
55	source := make(map[string]interface{})
56
57	match := make(map[string]interface{})
58	source["match_phrase"] = match
59
60	query := make(map[string]interface{})
61	match[q.name] = query
62
63	query["query"] = q.value
64
65	if q.analyzer != "" {
66		query["analyzer"] = q.analyzer
67	}
68	if q.slop != nil {
69		query["slop"] = *q.slop
70	}
71	if q.boost != nil {
72		query["boost"] = *q.boost
73	}
74	if q.queryName != "" {
75		query["_name"] = q.queryName
76	}
77
78	return source, nil
79}
80