search_facets_statistical.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. // Statistical facet allows to compute statistical data on a numeric fields.
  6. // The statistical data include count, total, sum of squares, mean (average),
  7. // minimum, maximum, variance, and standard deviation.
  8. // See: http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-facets-statistical-facet.html
  9. type StatisticalFacet struct {
  10. facetFilter Filter
  11. global *bool
  12. nested string
  13. mode string
  14. fieldName string
  15. fieldNames []string
  16. }
  17. func NewStatisticalFacet() StatisticalFacet {
  18. return StatisticalFacet{
  19. fieldNames: make([]string, 0),
  20. }
  21. }
  22. func (f StatisticalFacet) FacetFilter(filter Facet) StatisticalFacet {
  23. f.facetFilter = filter
  24. return f
  25. }
  26. func (f StatisticalFacet) Global(global bool) StatisticalFacet {
  27. f.global = &global
  28. return f
  29. }
  30. func (f StatisticalFacet) Nested(nested string) StatisticalFacet {
  31. f.nested = nested
  32. return f
  33. }
  34. func (f StatisticalFacet) Mode(mode string) StatisticalFacet {
  35. f.mode = mode
  36. return f
  37. }
  38. func (f StatisticalFacet) Field(fieldName string) StatisticalFacet {
  39. f.fieldName = fieldName
  40. return f
  41. }
  42. func (f StatisticalFacet) Fields(fieldNames ...string) StatisticalFacet {
  43. f.fieldNames = append(f.fieldNames, fieldNames...)
  44. return f
  45. }
  46. func (f StatisticalFacet) addFilterFacetAndGlobal(source map[string]interface{}) {
  47. if f.facetFilter != nil {
  48. source["facet_filter"] = f.facetFilter.Source()
  49. }
  50. if f.nested != "" {
  51. source["nested"] = f.nested
  52. }
  53. if f.global != nil {
  54. source["global"] = *f.global
  55. }
  56. if f.mode != "" {
  57. source["mode"] = f.mode
  58. }
  59. }
  60. func (f StatisticalFacet) Source() interface{} {
  61. source := make(map[string]interface{})
  62. f.addFilterFacetAndGlobal(source)
  63. opts := make(map[string]interface{})
  64. source["statistical"] = opts
  65. if len(f.fieldNames) > 0 {
  66. if len(f.fieldNames) == 1 {
  67. opts["field"] = f.fieldNames[0]
  68. } else {
  69. opts["fields"] = f.fieldNames
  70. }
  71. } else {
  72. opts["field"] = f.fieldName
  73. }
  74. return source
  75. }