suggest_field.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. import (
  6. "encoding/json"
  7. "errors"
  8. )
  9. // SuggestField can be used by the caller to specify a suggest field
  10. // at index time. For a detailed example, see e.g.
  11. // https://www.elastic.co/blog/you-complete-me.
  12. type SuggestField struct {
  13. inputs []string
  14. weight int
  15. contextQueries []SuggesterContextQuery
  16. }
  17. func NewSuggestField(input ...string) *SuggestField {
  18. return &SuggestField{
  19. inputs: input,
  20. weight: -1,
  21. }
  22. }
  23. func (f *SuggestField) Input(input ...string) *SuggestField {
  24. if f.inputs == nil {
  25. f.inputs = make([]string, 0)
  26. }
  27. f.inputs = append(f.inputs, input...)
  28. return f
  29. }
  30. func (f *SuggestField) Weight(weight int) *SuggestField {
  31. f.weight = weight
  32. return f
  33. }
  34. func (f *SuggestField) ContextQuery(queries ...SuggesterContextQuery) *SuggestField {
  35. f.contextQueries = append(f.contextQueries, queries...)
  36. return f
  37. }
  38. // MarshalJSON encodes SuggestField into JSON.
  39. func (f *SuggestField) MarshalJSON() ([]byte, error) {
  40. source := make(map[string]interface{})
  41. if f.inputs != nil {
  42. switch len(f.inputs) {
  43. case 1:
  44. source["input"] = f.inputs[0]
  45. default:
  46. source["input"] = f.inputs
  47. }
  48. }
  49. if f.weight >= 0 {
  50. source["weight"] = f.weight
  51. }
  52. switch len(f.contextQueries) {
  53. case 0:
  54. case 1:
  55. src, err := f.contextQueries[0].Source()
  56. if err != nil {
  57. return nil, err
  58. }
  59. source["context"] = src
  60. default:
  61. ctxq := make(map[string]interface{})
  62. for _, query := range f.contextQueries {
  63. src, err := query.Source()
  64. if err != nil {
  65. return nil, err
  66. }
  67. m, ok := src.(map[string]interface{})
  68. if !ok {
  69. return nil, errors.New("SuggesterContextQuery must be of type map[string]interface{}")
  70. }
  71. for k, v := range m {
  72. ctxq[k] = v
  73. }
  74. }
  75. source["context"] = ctxq
  76. }
  77. return json.Marshal(source)
  78. }