Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

facet_builder_terms.go 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // Copyright (c) 2014 Couchbase, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package facet
  15. import (
  16. "sort"
  17. "github.com/blevesearch/bleve/search"
  18. )
  19. type TermsFacetBuilder struct {
  20. size int
  21. field string
  22. termsCount map[string]int
  23. total int
  24. missing int
  25. sawValue bool
  26. }
  27. func NewTermsFacetBuilder(field string, size int) *TermsFacetBuilder {
  28. return &TermsFacetBuilder{
  29. size: size,
  30. field: field,
  31. termsCount: make(map[string]int),
  32. }
  33. }
  34. func (fb *TermsFacetBuilder) Field() string {
  35. return fb.field
  36. }
  37. func (fb *TermsFacetBuilder) UpdateVisitor(field string, term []byte) {
  38. if field == fb.field {
  39. fb.sawValue = true
  40. fb.termsCount[string(term)] = fb.termsCount[string(term)] + 1
  41. fb.total++
  42. }
  43. }
  44. func (fb *TermsFacetBuilder) StartDoc() {
  45. fb.sawValue = false
  46. }
  47. func (fb *TermsFacetBuilder) EndDoc() {
  48. if !fb.sawValue {
  49. fb.missing++
  50. }
  51. }
  52. func (fb *TermsFacetBuilder) Result() *search.FacetResult {
  53. rv := search.FacetResult{
  54. Field: fb.field,
  55. Total: fb.total,
  56. Missing: fb.missing,
  57. }
  58. rv.Terms = make([]*search.TermFacet, 0, len(fb.termsCount))
  59. for term, count := range fb.termsCount {
  60. tf := &search.TermFacet{
  61. Term: term,
  62. Count: count,
  63. }
  64. rv.Terms = append(rv.Terms, tf)
  65. }
  66. sort.Sort(rv.Terms)
  67. // we now have the list of the top N facets
  68. trimTopN := fb.size
  69. if trimTopN > len(rv.Terms) {
  70. trimTopN = len(rv.Terms)
  71. }
  72. rv.Terms = rv.Terms[:trimTopN]
  73. notOther := 0
  74. for _, tf := range rv.Terms {
  75. notOther += tf.Count
  76. }
  77. rv.Other = fb.total - notOther
  78. return &rv
  79. }