第一节 boltdb的Bucket结构

先来看官方文档的一段描述Bucket的话。

Bucket represents a collection of key/value pairs inside the database.

下面是Bucket的详细定义,本节我们先暂时忽略事务Tx,后面章节会详细介绍事务

1. // 16 byte
2. const bucketHeaderSize = int(unsafe.Sizeof(bucket{}))

4. const (
5. minFillPercent = 0.1
6. maxFillPercent = 1.0
7. )

9. // DefaultFillPercent is the percentage that split pages are filled.
10. // This value can be changed by setting Bucket.FillPercent.
11. const DefaultFillPercent = 0.5

13. // Bucket represents a collection of key/value pairs inside the database.
14. // 一组key/value的集合,也就是一个b+树
15. type Bucket struct {
16. *bucket //在内联时bucket主要用来存储其桶的value并在后面拼接所有的元素,即所谓的内联
17. tx       *Tx                // the associated transaction
18. buckets  map[string]*Bucket // subbucket cache
19. page     *page              // inline page reference,内联页引用
20. rootNode *node              // materialized node for the root page.
21. nodes    map[pgid]*node     // node cache

23. // Sets the threshold for filling nodes when they split. By default,
24. // the bucket will fill to 50% but it can be useful to increase this
25. // amount if you know that your write workloads are mostly append-only.
26. //
27. // This is non-persisted across transactions so it must be set in every Tx.
28. // 填充率
29. FillPercent float64
30. }

32. // bucket represents the on-file representation of a bucket.
33. // This is stored as the "value" of a bucket key. If the bucket is small enough,
34. // then its root page can be stored inline in the "value", after the bucket
35. // header. In the case of inline buckets, the "root" will be 0.
36. type bucket struct {
37. root     pgid   // page id of the bucket's root-level page
38. sequence uint64 // monotonically incrementing, used by NextSequence()
39. }

41. // newBucket returns a new bucket associated with a transaction.
42. func newBucket(tx *Tx) Bucket {
43. var b = Bucket{tx: tx, FillPercent: DefaultFillPercent}
44. if tx.writable {
45. b.buckets = make(map[string]*Bucket)
46. b.nodes = make(map[pgid]*node)
47. }
48. return b
49. }

下图展现的是数据在bucket中的存储方式。

../imgs/bucket存储.png

上面是一个Bucket的定义,在开始下面的内容前,我们先提前介绍一下另一个角色Cursor,因为后面会频繁的用到它。大家在这里先知道,一个Bucket就是一个b+树就可以了。我们后面会对其进行详细的分析。