# Hyperbee



<Status level="stable" />

`Hyperbee` stores sorted key/value entries in an append-only B-tree backed by [`Hypercore`](/p2p/reference/building-blocks/hypercore). Use it when you need ordered lookups, range scans, atomic batches, namespaces, and point-in-time snapshots over one replicated log.

## Install [#install]

```sh
npm i hyperbee
```

## Quickstart [#quickstart]

```js
import Hypercore from 'hypercore'
import Hyperbee from 'hyperbee'

const core = new Hypercore('./bee-storage')
const db = new Hyperbee(core, {
  keyEncoding: 'utf-8',
  valueEncoding: 'json'
})

await db.ready()
await db.put('config', { theme: 'dark', retries: 3 })

const entry = await db.get('config')
console.log(entry.value.theme)

await db.close()
```

## API Reference [#api-reference]

### Constructor and readiness [#constructor-and-readiness]

#### `new Hyperbee(core, [options])` [#new-hyperbeecore-options]

[src](https://github.com/holepunchto/hyperbee/blob/v2.27.3/index.js#L405)

Make a new Hyperbee instance. `core` should be a [Hypercore](https://github.com/holepunchto/hypercore).

| Parameter | Type                                                    | Default |
| --------- | ------------------------------------------------------- | ------- |
| `core`    | [`Hypercore`](/p2p/reference/building-blocks/hypercore) | —       |
| `options` | [`HyperbeeOptions`](#hyperbeeoptions)                   | `{}`    |

Read and diff streams sort keys by their encoded byte values, so choose `keyEncoding` deliberately if lexicographic order matters.

#### `await db.ready()` [#await-dbready]

Waits until internal state is loaded.

### Properties and identity [#properties-and-identity]

#### `db.core` [#dbcore]

[src](https://github.com/holepunchto/hyperbee/blob/v2.27.3/index.js#L409)

The underlying Hypercore backing this bee.

* Returns: [`Hypercore`](/p2p/reference/building-blocks/hypercore)

#### `db.version` [#dbversion]

[src](https://github.com/holepunchto/hyperbee/blob/v2.27.3/index.js#L467)

Number that indicates how many modifications were made, useful as a version identifier.

* Returns: `number`

#### `db.id` [#dbid]

[src](https://github.com/holepunchto/hyperbee/blob/v2.27.3/index.js#L471)

String containing the id (z-base-32 of the public key) identifying this bee.

* Returns: `string`

#### `db.key` [#dbkey]

[src](https://github.com/holepunchto/hyperbee/blob/v2.27.3/index.js#L475)

Buffer containing the public key identifying this bee.

* Returns: [`Buffer`](https://nodejs.org/api/buffer.html#class-buffer)

#### `db.discoveryKey` [#dbdiscoverykey]

[src](https://github.com/holepunchto/hyperbee/blob/v2.27.3/index.js#L479)

Buffer containing a key derived from `db.key`.

* Returns: [`Buffer`](https://nodejs.org/api/buffer.html#class-buffer)

#### `db.writable` [#dbwritable]

[src](https://github.com/holepunchto/hyperbee/blob/v2.27.3/index.js#L483)

Boolean indicating if we can put or delete data in this bee.

* Returns: `boolean`

#### `db.readable` [#dbreadable]

[src](https://github.com/holepunchto/hyperbee/blob/v2.27.3/index.js#L487)

Boolean indicating if we can read from this bee. After closing the bee this will be `false`.

* Returns: `boolean`

### Writes and batches [#writes-and-batches]

#### `await db.put(key, [value], [options])` [#await-dbputkey-value-options]

[src](https://github.com/holepunchto/hyperbee/blob/v2.27.3/index.js#L647)

Insert a new key. Value can be optional.

| Parameter | Type                        | Description                                        |
| --------- | --------------------------- | -------------------------------------------------- |
| `key`     | `*`                         | The key to insert (encoded per `keyEncoding`).     |
| `value`   | `*`                         | The value to store; optional for key-only entries. |
| `options` | [`PutOptions`](#putoptions) | —                                                  |

* Returns: [`Promise<void>`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) — Resolves once the write is committed to the core.

```js
{
  cas (prev, next) { return true }
}
```

```js
await db.put('number', '123', { cas })
console.log(await db.get('number')) // => { seq: 1, key: 'number', value: '123' }

await db.put('number', '123', { cas })
console.log(await db.get('number')) // => { seq: 1, key: 'number', value: '123' }
// Without cas this would have been { seq: 2, ... }, and the next { seq: 3 }

await db.put('number', '456', { cas })
console.log(await db.get('number')) // => { seq: 2, key: 'number', value: '456' }

function cas(prev, next) {
  // You can use same-data or same-object lib, depending on the value complexity
  return prev.value !== next.value
}
```

The `cas` comparator receives the current node as `prev` and the potential new node as `next`. It runs only when the key already exists.

#### `await db.del(key, [options])` [#await-dbdelkey-options]

[src](https://github.com/holepunchto/hyperbee/blob/v2.27.3/index.js#L656)

Delete a key.

| Parameter | Type                        | Description                                    |
| --------- | --------------------------- | ---------------------------------------------- |
| `key`     | `*`                         | The key to delete (encoded per `keyEncoding`). |
| `options` | [`PutOptions`](#putoptions) | —                                              |

* Returns: [`Promise<void>`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) — Resolves once the deletion is committed to the core.

```js
{
  cas (prev, next) { return true }
}
```

```js
// This won't get deleted
await db.del('number', { cas })
console.log(await db.get('number')) // => { seq: 1, key: 'number', value: 'value' }

// Change the value so the next time we try to delete it then "cas" will return true
await db.put('number', 'can-be-deleted')

await db.del('number', { cas })
console.log(await db.get('number')) // => null

function cas(prev) {
  return prev.value === 'can-be-deleted'
}
```

The delete comparator runs only when the key exists. Deleting a missing key succeeds without calling `cas`.

#### `db.batch()` [#dbbatch]

[src](https://github.com/holepunchto/hyperbee/blob/v2.27.3/index.js#L652)

Make a new atomic batch that is either fully processed or not processed at all.

| Parameter | Type                            | Description    |
| --------- | ------------------------------- | -------------- |
| `opts`    | [`BatchOptions`](#batchoptions) | Batch options. |

* Returns: [`Batch`](/p2p/reference/building-blocks/hyperbee) — A new batch; queue writes on it and call `flush()` to commit.

```js
const batch = db.batch()
await batch.put('key', 'value')
await batch.flush()
```

Use batches when you need grouped writes or lower overhead for many updates.

#### `await batch.put(key, [value], [options])` [#await-batchputkey-value-options]

[src](https://github.com/holepunchto/hyperbee/blob/v2.27.3/index.js#L1117)

Insert a key into a batch.

| Parameter | Type                        | Description                                                             |
| --------- | --------------------------- | ----------------------------------------------------------------------- |
| `key`     | `*`                         | The key to insert (encoded per the batch's `keyEncoding`).              |
| `value`   | `*`                         | The value to store (encoded per the batch's `valueEncoding`); optional. |
| `options` | [`PutOptions`](#putoptions) | `options` are the same as `db.put` method.                              |

* Returns: [`Promise<void>`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) — Resolves after queuing the write inside the batch.

```js
await batch.put('key', 'value')
```

#### `await batch.get(key)` [#await-batchgetkey]

[src](https://github.com/holepunchto/hyperbee/blob/v2.27.3/index.js#L1033)

Get a key, value out of a batch.

| Parameter | Type                        | Description                                                 |
| --------- | --------------------------- | ----------------------------------------------------------- |
| `key`     | `*`                         | The key to look up (encoded per the batch's `keyEncoding`). |
| `opts`    | [`GetOptions`](#getoptions) | Read options.                                               |

* Returns: [`Promise<Entry\|null>`](#entry) — The pending or committed entry visible within the batch, or `null` when missing.

```js
const entry = await batch.get('key')
```

#### `await batch.del(key, [options])` [#await-batchdelkey-options]

[src](https://github.com/holepunchto/hyperbee/blob/v2.27.3/index.js#L1206)

Delete a key into the batch.

| Parameter | Type                        | Description                                                |
| --------- | --------------------------- | ---------------------------------------------------------- |
| `key`     | `*`                         | The key to delete (encoded per the batch's `keyEncoding`). |
| `options` | [`PutOptions`](#putoptions) | `options` are the same as `db.del` method.                 |

* Returns: [`Promise<void>`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) — Resolves after queuing the delete inside the batch.

```js
await batch.del('key')
```

#### `await batch.flush()` [#await-batchflush]

[src](https://github.com/holepunchto/hyperbee/blob/v2.27.3/index.js#L1327)

Commit the batch to the database, and releases any locks it has acquired.

* Returns: [`Promise<void>`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) — Resolves after committing the queued operations and releasing the batch lock.

```js
await batch.flush()
```

#### `await batch.close()` [#await-batchclose]

[src](https://github.com/holepunchto/hyperbee/blob/v2.27.3/index.js#L1278)

Destroy a batch, and releases any locks it has acquired on the db.

* Returns: [`Promise<void>`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) — Resolves after discarding the batch and releasing any lock it holds.

```js
await batch.close()
```

Call `batch.close()` when you want to abort a batch without writing it.

### Reads and iteration [#reads-and-iteration]

#### `await db.get(key)` [#await-dbgetkey]

[src](https://github.com/holepunchto/hyperbee/blob/v2.27.3/index.js#L637)

Get a key's value. Returns `null` if key doesn't exists.

| Parameter | Type                        | Description                                     |
| --------- | --------------------------- | ----------------------------------------------- |
| `key`     | `*`                         | The key to look up (encoded per `keyEncoding`). |
| `opts`    | [`GetOptions`](#getoptions) | Read options.                                   |

* Returns: [`Promise<Entry\|null>`](#entry) — The entry, or `null` if the key is not present.

```js
const entry = await db.get('key') // => { seq, key, value } or null
```

#### `await db.getBySeq(seq, [options])` [#await-dbgetbyseqseq-options]

[src](https://github.com/holepunchto/hyperbee/blob/v2.27.3/index.js#L642)

Get the key and value from a block number.

| Parameter | Type                        | Description             |
| --------- | --------------------------- | ----------------------- |
| `seq`     | `number`                    | is the Hypercore index. |
| `options` | [`GetOptions`](#getoptions) | Read options.           |

* Returns: [`Promise<{key: *, value: *}>`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) — The block's key and value.

```js
const { key, value } = await db.getBySeq(1)
```

#### `db.createReadStream([range], [options])` [#dbcreatereadstreamrange-options]

[src](https://github.com/holepunchto/hyperbee/blob/v2.27.3/index.js#L543)

Make a read stream. Sort order is based on the binary value of the keys.

| Parameter | Type                                      | Description                                                   |
| --------- | ----------------------------------------- | ------------------------------------------------------------- |
| `range`   | [`Range`](#range)                         | should specify the range you want to read and looks like this |
| `options` | [`ReadStreamOptions`](#readstreamoptions) | —                                                             |

* Returns: [`Readable`](https://nodejs.org/api/stream.html#class-streamreadable) — A stream of `Entry` objects.

#### `await db.peek([range], [options])` [#await-dbpeekrange-options]

[src](https://github.com/holepunchto/hyperbee/blob/v2.27.3/index.js#L499)

Similar to doing a read stream and returning the first value, but a bit faster than that.

| Parameter | Type                                      | Description                                                           |
| --------- | ----------------------------------------- | --------------------------------------------------------------------- |
| `range`   | [`Range`](#range)                         | bounds to search within.                                              |
| `options` | [`ReadStreamOptions`](#readstreamoptions) | Read options (`reverse` selects the last entry instead of the first). |

* Returns: [`Promise<Entry\|null>`](#entry) — The first matching entry, or `null` if the range is empty.

```js
const first = await db.peek({ gte: 'a', lt: 'd' })
```

### History and change tracking [#history-and-change-tracking]

#### `db.createHistoryStream([options])` [#dbcreatehistorystreamoptions]

[src](https://github.com/holepunchto/hyperbee/blob/v2.27.3/index.js#L548)

Create a stream of all entries ever inserted or deleted from the db.

| Parameter | Type                                            |
| --------- | ----------------------------------------------- |
| `options` | [`HistoryStreamOptions`](#historystreamoptions) |

* Returns: [`Readable`](https://nodejs.org/api/stream.html#class-streamreadable) — A stream of `Entry` objects, each with an added `type` (`'put'` or `'del'`).

#### `db.createDiffStream(otherVersion, [options])` [#dbcreatediffstreamotherversion-options]

[src](https://github.com/holepunchto/hyperbee/blob/v2.27.3/index.js#L557)

Efficiently create a stream of the shallow changes between two versions of the db.

| Parameter | Type                                                          | Description                                                                   |
| --------- | ------------------------------------------------------------- | ----------------------------------------------------------------------------- |
| `right`   | [`number\|Hyperbee`](/p2p/reference/building-blocks/hyperbee) | The other version to diff against: a version number, or another bee/snapshot. |
| `range`   | [`Range`](#range)                                             | `options` are the same as `db.createReadStream`, except for `reverse`.        |
| `opts`    | [`ReadStreamOptions`](#readstreamoptions)                     | Read options.                                                                 |

* Returns: [`Readable`](https://nodejs.org/api/stream.html#class-streamreadable) — A stream of `{ left, right }` pairs, where each side is an `Entry` or `null`.

| Property | Type     | Description                 |
| -------- | -------- | --------------------------- |
| `left`   | `Object` | The entry in the `db`       |
| `right`  | `Object` | The entry in `otherVersion` |

Causally equal entries are omitted from the diff, so the stream only yields actual changes between versions.

#### `await db.getAndWatch(key, [options])` [#await-dbgetandwatchkey-options]

[src](https://github.com/holepunchto/hyperbee/blob/v2.27.3/index.js#L666)

`entryWatcher.node` contains the current entry in the same format as the result of `bee.get(key)`, and will be updated as it changes.

| Parameter | Type                                      | Description                                   |
| --------- | ----------------------------------------- | --------------------------------------------- |
| `key`     | `*`                                       | The key to watch (encoded per `keyEncoding`). |
| `options` | [`EntryWatchOptions`](#entrywatchoptions) | Watch options.                                |

* Returns: [`Promise<EntryWatcher>`](/p2p/reference/building-blocks/hyperbee) — a watcher which listens to changes on the given key.
* Throws: if called on a non-main Hyperbee, or if the Hyperbee is closed.

```js
const w = await db.getAndWatch('config')
w.on('update', () => console.log(w.node.value))
```

Listen to `entryWatcher.on('update')` when you need push-style notifications for a single key.

#### `await entryWatcher.close()` [#await-entrywatcherclose]

Stop a single-key watcher.

* Returns: Resolves after stopping the watcher created by `db.getAndWatch(...)`.

```js
await entryWatcher.close()
```

#### `db.watch([range])` [#dbwatchrange]

[src](https://github.com/holepunchto/hyperbee/blob/v2.27.3/index.js#L661)

Listens to changes that are on the optional `range`.

| Parameter | Type                            | Description                                                                                |
| --------- | ------------------------------- | ------------------------------------------------------------------------------------------ |
| `range`   | [`Range`](#range)               | bounds to narrow what changes are watched; same as `db.createReadStream` except `reverse`. |
| `opts`    | [`WatchOptions`](#watchoptions) | Watch options.                                                                             |

* Returns: [`Watcher`](/p2p/reference/building-blocks/hyperbee) — a new value after a change, `current` and `previous` are snapshots that are auto-closed before next value.
* Throws: if called on a non-main Hyperbee (a sub, checkout, or snapshot).

```js
for await (const [current, previous] of watcher) {
  console.log(current.version)
  console.log(previous.version)
}
```

Watchers are not supported on subs or checkouts. Use `range` to narrow the scope on the root bee instead.

#### `await watcher.ready()` [#await-watcherready]

Wait for a range watcher to be tracking changes.

* Returns: Resolves when a range watcher has loaded and is actively tracking changes.

```js
await watcher.ready()
```

#### `await watcher.close()` [#await-watcherclose]

Stop a range watcher.

* Returns: Resolves after stopping the range watcher. Breaking out of the async iterator also stops it.

```js
await watcher.close()
```

### Snapshots and sub-bees [#snapshots-and-sub-bees]

#### `db.checkout(version)` [#dbcheckoutversion]

[src](https://github.com/holepunchto/hyperbee/blob/v2.27.3/index.js#L762)

Get a read-only snapshot of a previous version.

| Parameter | Type                                  | Default | Description                                  |
| --------- | ------------------------------------- | ------- | -------------------------------------------- |
| `version` | `number`                              | —       | The version (see `db.version`) to check out. |
| `opts`    | [`CheckoutOptions`](#checkoutoptions) | `{}`    | Snapshot options.                            |

* Returns: [`Hyperbee`](/p2p/reference/building-blocks/hyperbee) — A read-only bee pinned to that version.

```js
const old = db.checkout(5)
const entry = await old.get('key')
```

#### `db.snapshot()` [#dbsnapshot]

[src](https://github.com/holepunchto/hyperbee/blob/v2.27.3/index.js#L786)

Shorthand for getting a checkout for the current version.

| Parameter | Type                                  | Description       |
| --------- | ------------------------------------- | ----------------- |
| `opts`    | [`CheckoutOptions`](#checkoutoptions) | Snapshot options. |

* Returns: [`Hyperbee`](/p2p/reference/building-blocks/hyperbee) — A read-only bee pinned to the current version.

```js
const snap = db.snapshot()
```

#### `db.sub('sub-prefix', options = {})` [#dbsubsub-prefix-options--]

[src](https://github.com/holepunchto/hyperbee/blob/v2.27.3/index.js#L793)

Create a sub-database where all entries will be prefixed by a given value.

| Parameter | Type                                                                | Default | Description                                |
| --------- | ------------------------------------------------------------------- | ------- | ------------------------------------------ |
| `prefix`  | [`string\|Buffer`](https://nodejs.org/api/buffer.html#class-buffer) | —       | The namespace prefix applied to every key. |
| `opts`    | [`SubOptions`](#suboptions)                                         | `{}`    | —                                          |

* Returns: [`Hyperbee`](/p2p/reference/building-blocks/hyperbee) — A bee scoped to the prefixed keyspace.

```js
const root = new Hyperbee(core, { keyEncoding: 'utf-8', valueEncoding: 'utf-8' })
const sub = root.sub('a')

// In root, this will have the key ('a' + separator + 'b')
await sub.put('b', 'hello')

// Returns => { seq: 1, key: 'b', value: 'hello' }
await sub.get('b')
```

Sub-bees are useful when one Hyperbee needs multiple logical keyspaces without creating extra cores.

#### `await db.getHeader([options])` [#await-dbgetheaderoptions]

[src](https://github.com/holepunchto/hyperbee/blob/v2.27.3/index.js#L816)

`options` are the same as the `core.get` method.

| Parameter | Type                        |
| --------- | --------------------------- |
| `options` | [`GetOptions`](#getoptions) |

* Returns: [`Promise<object>`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) — the header contained in the first block.
* Throws: `DECODING_ERROR` if the stored header cannot be decoded.

```js
const header = await db.getHeader()
```

### Replication and lifecycle [#replication-and-lifecycle]

#### `db.replicate(isInitiator, [opts])` [#dbreplicateisinitiator-opts]

[src](https://github.com/holepunchto/hyperbee/blob/v2.27.3/index.js#L491)

See more about how replicate works at core.replicate.

| Parameter     | Type                                                    | Description                                                                                 |
| ------------- | ------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
| `isInitiator` | [`boolean\|Stream`](https://nodejs.org/api/stream.html) | `true`/`false` to open a fresh replication stream, or an existing stream to replicate over. |
| `opts`        | `object`                                                | Replication options, forwarded to `core.replicate`.                                         |

* Returns: [`Stream`](https://nodejs.org/api/stream.html) — The replication stream.

```js
const stream = db.replicate(true)
stream.pipe(remoteStream).pipe(stream)
```

In larger apps, replication is often handled through a shared [`Corestore`](/p2p/reference/helpers/corestore) rather than per-bee streams.

#### `await db.close()` [#await-dbclose]

Fully close this bee, including its core.

### Static helpers [#static-helpers]

#### `await Hyperbee.isHyperbee(core, [options])` [#await-hyperbeeishyperbeecore-options]

[src](https://github.com/holepunchto/hyperbee/blob/v2.27.3/index.js#L853)

This requests the first block on the core, so it can throw depending on the options.

| Parameter | Type                                                    | Description                                      |
| --------- | ------------------------------------------------------- | ------------------------------------------------ |
| `core`    | [`Hypercore`](/p2p/reference/building-blocks/hypercore) | The core to inspect.                             |
| `options` | [`GetOptions`](#getoptions)                             | `options` are the same as the `core.get` method. |

* Returns: [`Promise<boolean>`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) — `true` if the core contains a Hyperbee, `false` otherwise.

```js
if (await Hyperbee.isHyperbee(core)) {
  const db = new Hyperbee(core)
}
```

## Types [#types]

### Entry [#entry]

A single entry as returned by reads such as `db.get()`, `db.peek()`, and the
read stream. `key` and `value` are decoded with the bee's `keyEncoding` /
`valueEncoding` (raw `Buffer`s when no encoding is set).

| Property | Type     | Default | Description                                                                                                  |
| -------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------ |
| `seq`    | `number` | —       | [Hypercore](/p2p/reference/building-blocks/hypercore) index (block number) at which this entry was inserted. |
| `key`    | `*`      | —       | The entry's key, decoded per `keyEncoding`.                                                                  |
| `value`  | `*`      | —       | The entry's value, decoded per `valueEncoding` (`null` for a deletion).                                      |

### HyperbeeOptions [#hyperbeeoptions]

Options for `new Hyperbee()`.

| Property          | Type              | Default    | Description                                                                                                                                             |
| ----------------- | ----------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `keyEncoding`     | `string\|object`  | `'binary'` | Key encoding: `"binary"` (default), `"utf-8"`, `"ascii"`, `"json"`, or an abstract-encoding instance.                                                   |
| `valueEncoding`   | `string\|object`  | `'binary'` | Value encoding; same options as `keyEncoding`.                                                                                                          |
| `prefix`          | `Buffer`          | —          | Namespace prefix applied to every key; set internally by [`db.sub()`](#dbsubsub-prefix-options--) rather than passed directly in most apps.             |
| `sep`             | `Buffer\|string`  | —          | Separator placed between a `prefix` and each key.                                                                                                       |
| `readonly`        | `boolean`         | `false`    | Open the bee without acquiring the write lock.                                                                                                          |
| `checkout`        | `number`          | `0`        | Open the bee already checked out at this version, equivalent to calling [`db.checkout()`](#dbcheckoutversion) immediately after construction.           |
| `lock`            | `object`          | —          | A [`mutexify`](https://github.com/mafintosh/mutexify) instance to coordinate writes with; shared automatically between a bee and its subs.              |
| `metadata`        | `*`               | —          | Arbitrary value stored in the bee's header, returned by [`db.getHeader()`](#await-dbgetheaderoptions).                                                  |
| `extension`       | `boolean\|object` | —          | The [Protomux](/p2p/reference/helpers/protomux) extension used for range-watch notifications between peers; pass `false` to disable it.                 |
| `alwaysDuplicate` | `boolean`         | `true`     | Duplicate key/value buffers read from storage rather than returning views into the underlying block. Planned to default to `false` in a future version. |

### PutOptions [#putoptions]

Options for `db.put()`, `db.del()` and their batch equivalents.

| Property | Type            | Default | Description                                                                  |
| -------- | --------------- | ------- | ---------------------------------------------------------------------------- |
| `cas`    | `CASComparator` | —       | Compare-and-swap comparator; the write only proceeds when it returns `true`. |

### Range [#range]

Range bounds for read, diff, and watch streams. Keys are compared by their
encoded byte value.

| Property | Type | Default | Description                                     |
| -------- | ---- | ------- | ----------------------------------------------- |
| `gt`     | `*`  | —       | Only return keys greater than this.             |
| `gte`    | `*`  | —       | Only return keys greater than or equal to this. |
| `lt`     | `*`  | —       | Only return keys less than this.                |
| `lte`    | `*`  | —       | Only return keys less than or equal to this.    |

### ReadStreamOptions [#readstreamoptions]

Options for `db.createReadStream()` and `db.peek()`.

| Property  | Type      | Default | Description                                              |
| --------- | --------- | ------- | -------------------------------------------------------- |
| `reverse` | `boolean` | `false` | Yield entries in reverse (descending) order.             |
| `limit`   | `number`  | `-1`    | Maximum number of entries to return (`-1` for no limit). |

### HistoryStreamOptions [#historystreamoptions]

Options for `db.createHistoryStream()`.

| Property  | Type      | Default | Description                                                                      |
| --------- | --------- | ------- | -------------------------------------------------------------------------------- |
| `live`    | `boolean` | `false` | Keep the stream open and wait for new data instead of ending.                    |
| `reverse` | `boolean` | `false` | Iterate from newest to oldest.                                                   |
| `gte`     | `number`  | —       | Start at this seq (inclusive); negative values are added to the current version. |
| `gt`      | `number`  | —       | Start after this seq.                                                            |
| `lte`     | `number`  | —       | Stop at this seq (inclusive).                                                    |
| `lt`      | `number`  | —       | Stop before this seq.                                                            |
| `limit`   | `number`  | `-1`    | Maximum number of entries to return (`-1` for no limit).                         |

### SubOptions [#suboptions]

Options for `db.sub()`.

| Property        | Type                                                        | Default | Description                                                                                 |
| --------------- | ----------------------------------------------------------- | ------- | ------------------------------------------------------------------------------------------- |
| `sep`           | [`Buffer`](https://nodejs.org/api/buffer.html#class-buffer) | —       | Namespace separator placed between the prefix and key (defaults to the parent's separator). |
| `keyEncoding`   | `string\|object`                                            | —       | Key encoding for the sub (defaults to the parent's).                                        |
| `valueEncoding` | `string\|object`                                            | —       | Value encoding for the sub (defaults to the parent's).                                      |

### GetOptions [#getoptions]

Options for point reads such as `db.get()` and `db.getBySeq()`. The encoding
overrides apply to this call only; remaining options are forwarded to the
underlying `core.get()`.

| Property        | Type             | Default | Description                                                   |
| --------------- | ---------------- | ------- | ------------------------------------------------------------- |
| `keyEncoding`   | `string\|object` | —       | Override the key encoding for this read.                      |
| `valueEncoding` | `string\|object` | —       | Override the value encoding for this read.                    |
| `wait`          | `boolean`        | `true`  | Wait for the block to download from a peer if it isn't local. |
| `timeout`       | `number`         | `0`     | Max milliseconds to wait for a block (`0` = no timeout).      |

### BatchOptions [#batchoptions]

Options for `db.batch()`.

| Property        | Type             | Default | Description                                                     |
| --------------- | ---------------- | ------- | --------------------------------------------------------------- |
| `keyEncoding`   | `string\|object` | —       | Override the key encoding for this batch.                       |
| `valueEncoding` | `string\|object` | —       | Override the value encoding for this batch.                     |
| `update`        | `boolean`        | `true`  | Update the underlying core before the first operation resolves. |

### WatchOptions [#watchoptions]

Options for `db.watch()`.

| Property        | Type             | Default | Description                                                       |
| --------------- | ---------------- | ------- | ----------------------------------------------------------------- |
| `keyEncoding`   | `string\|object` | —       | Key encoding for the yielded snapshots (defaults to the bee's).   |
| `valueEncoding` | `string\|object` | —       | Value encoding for the yielded snapshots (defaults to the bee's). |

### EntryWatchOptions [#entrywatchoptions]

Options for `db.getAndWatch()`.

| Property        | Type             | Default | Description                                                   |
| --------------- | ---------------- | ------- | ------------------------------------------------------------- |
| `keyEncoding`   | `string\|object` | —       | Key encoding for the watched entry (defaults to the bee's).   |
| `valueEncoding` | `string\|object` | —       | Value encoding for the watched entry (defaults to the bee's). |

### CheckoutOptions [#checkoutoptions]

Options for `db.checkout()` and `db.snapshot()`.

| Property        | Type             | Default | Description                                              |
| --------------- | ---------------- | ------- | -------------------------------------------------------- |
| `keyEncoding`   | `string\|object` | —       | Key encoding for the snapshot (defaults to the bee's).   |
| `valueEncoding` | `string\|object` | —       | Value encoding for the snapshot (defaults to the bee's). |

## Errors [#errors]

Coded errors this module can throw — catch them via `err.code`.

| Error            | Thrown when                             |
| ---------------- | --------------------------------------- |
| `DECODING_ERROR` | if the stored header cannot be decoded. |

## See also [#see-also]

* [Share append-only databases with Hyperbee](/p2p/how-to/store-and-replicate/share-append-only-databases-with-hyperbee)—replication walkthrough with reader and writer peers.
* [Work with many Hypercores using Corestore](/p2p/how-to/store-and-replicate/work-with-many-hypercores-using-corestore)—recommended multi-core replication pattern.
* [Autobee](/p2p/reference/building-blocks/autobee)—the multiwriter form of this B-tree, where many peers write into one derived view.
* [Corestore](/p2p/reference/helpers/corestore)—manage many Hypercores and Hyperbees from one store.
* [Hypercore](/p2p/reference/building-blocks/hypercore)—append-only log that stores Hyperbee nodes.
* [Hyperdrive](/p2p/reference/building-blocks/hyperdrive)—filesystem abstraction that builds on Hyperbee-style metadata indexing.
