search_queries_match_phrase.go 2.1 KB

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