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