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