suggest_field.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Copyright 2012-2015 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. )
  8. // SuggestField can be used by the caller to specify a suggest field
  9. // at index time. For a detailed example, see e.g.
  10. // http://www.elasticsearch.org/blog/you-complete-me/.
  11. type SuggestField struct {
  12. inputs []string
  13. output *string
  14. payload interface{}
  15. weight int
  16. }
  17. func NewSuggestField() *SuggestField {
  18. return &SuggestField{weight: -1}
  19. }
  20. func (f *SuggestField) Input(input ...string) *SuggestField {
  21. if f.inputs == nil {
  22. f.inputs = make([]string, 0)
  23. }
  24. f.inputs = append(f.inputs, input...)
  25. return f
  26. }
  27. func (f *SuggestField) Output(output string) *SuggestField {
  28. f.output = &output
  29. return f
  30. }
  31. func (f *SuggestField) Payload(payload interface{}) *SuggestField {
  32. f.payload = payload
  33. return f
  34. }
  35. func (f *SuggestField) Weight(weight int) *SuggestField {
  36. f.weight = weight
  37. return f
  38. }
  39. // MarshalJSON encodes SuggestField into JSON.
  40. func (f *SuggestField) MarshalJSON() ([]byte, error) {
  41. source := make(map[string]interface{})
  42. if f.inputs != nil {
  43. switch len(f.inputs) {
  44. case 1:
  45. source["input"] = f.inputs[0]
  46. default:
  47. source["input"] = f.inputs
  48. }
  49. }
  50. if f.output != nil {
  51. source["output"] = *f.output
  52. }
  53. if f.payload != nil {
  54. source["payload"] = f.payload
  55. }
  56. if f.weight >= 0 {
  57. source["weight"] = f.weight
  58. }
  59. return json.Marshal(source)
  60. }