第一节 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{}))
  3. const (
  4. minFillPercent = 0.1
  5. maxFillPercent = 1.0
  6. )
  7. // DefaultFillPercent is the percentage that split pages are filled.
  8. // This value can be changed by setting Bucket.FillPercent.
  9. const DefaultFillPercent = 0.5
  10. // Bucket represents a collection of key/value pairs inside the database.
  11. // 一组key/value的集合,也就是一个b+树
  12. type Bucket struct {
  13. *bucket //在内联时bucket主要用来存储其桶的value并在后面拼接所有的元素,即所谓的内联
  14. tx *Tx // the associated transaction
  15. buckets map[string]*Bucket // subbucket cache
  16. page *page // inline page reference,内联页引用
  17. rootNode *node // materialized node for the root page.
  18. nodes map[pgid]*node // node cache
  19. // Sets the threshold for filling nodes when they split. By default,
  20. // the bucket will fill to 50% but it can be useful to increase this
  21. // amount if you know that your write workloads are mostly append-only.
  22. //
  23. // This is non-persisted across transactions so it must be set in every Tx.
  24. // 填充率
  25. FillPercent float64
  26. }
  27. // bucket represents the on-file representation of a bucket.
  28. // This is stored as the "value" of a bucket key. If the bucket is small enough,
  29. // then its root page can be stored inline in the "value", after the bucket
  30. // header. In the case of inline buckets, the "root" will be 0.
  31. type bucket struct {
  32. root pgid // page id of the bucket's root-level page
  33. sequence uint64 // monotonically incrementing, used by NextSequence()
  34. }
  35. // newBucket returns a new bucket associated with a transaction.
  36. func newBucket(tx *Tx) Bucket {
  37. var b = Bucket{tx: tx, FillPercent: DefaultFillPercent}
  38. if tx.writable {
  39. b.buckets = make(map[string]*Bucket)
  40. b.nodes = make(map[pgid]*node)
  41. }
  42. return b
  43. }

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

../imgs/bucket存储.png

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