You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

101 lines
2.3 KiB

  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 document
  15. import (
  16. "fmt"
  17. "reflect"
  18. "github.com/blevesearch/bleve/size"
  19. )
  20. var reflectStaticSizeDocument int
  21. func init() {
  22. var d Document
  23. reflectStaticSizeDocument = int(reflect.TypeOf(d).Size())
  24. }
  25. type Document struct {
  26. ID string `json:"id"`
  27. Fields []Field `json:"fields"`
  28. CompositeFields []*CompositeField
  29. }
  30. func NewDocument(id string) *Document {
  31. return &Document{
  32. ID: id,
  33. Fields: make([]Field, 0),
  34. CompositeFields: make([]*CompositeField, 0),
  35. }
  36. }
  37. func (d *Document) Size() int {
  38. sizeInBytes := reflectStaticSizeDocument + size.SizeOfPtr +
  39. len(d.ID)
  40. for _, entry := range d.Fields {
  41. sizeInBytes += entry.Size()
  42. }
  43. for _, entry := range d.CompositeFields {
  44. sizeInBytes += entry.Size()
  45. }
  46. return sizeInBytes
  47. }
  48. func (d *Document) AddField(f Field) *Document {
  49. switch f := f.(type) {
  50. case *CompositeField:
  51. d.CompositeFields = append(d.CompositeFields, f)
  52. default:
  53. d.Fields = append(d.Fields, f)
  54. }
  55. return d
  56. }
  57. func (d *Document) GoString() string {
  58. fields := ""
  59. for i, field := range d.Fields {
  60. if i != 0 {
  61. fields += ", "
  62. }
  63. fields += fmt.Sprintf("%#v", field)
  64. }
  65. compositeFields := ""
  66. for i, field := range d.CompositeFields {
  67. if i != 0 {
  68. compositeFields += ", "
  69. }
  70. compositeFields += fmt.Sprintf("%#v", field)
  71. }
  72. return fmt.Sprintf("&document.Document{ID:%s, Fields: %s, CompositeFields: %s}", d.ID, fields, compositeFields)
  73. }
  74. func (d *Document) NumPlainTextBytes() uint64 {
  75. rv := uint64(0)
  76. for _, field := range d.Fields {
  77. rv += field.NumPlainTextBytes()
  78. }
  79. for _, compositeField := range d.CompositeFields {
  80. for _, field := range d.Fields {
  81. if compositeField.includesField(field.Name()) {
  82. rv += field.NumPlainTextBytes()
  83. }
  84. }
  85. }
  86. return rv
  87. }