Skip to main content
Iterators provide an efficient way to scan through RocksDB data in sorted order. This guide covers basic iteration patterns, seeking strategies, and performance considerations.

Creating an Iterator

Create an iterator using NewIterator():
You must delete the iterator when you’re done with it. Iterators hold resources that need to be released.

Basic Iteration Patterns

Forward Iteration

Iterate from beginning to end:

Reverse Iteration

Iterate from end to beginning:

Seeking Operations

Seek to Specific Key

SeekForPrev - Seek in Reverse

Positions iterator at the first key greater than or equal to target

Iterator API Reference

Core Methods

Key Iterator State Methods

1

Valid()

Returns true if the iterator is positioned at a valid key-value pair.
2

key()

Returns the current key. Only valid when Valid() is true.
3

value()

Returns the current value. Only valid when Valid() is true.
4

status()

Returns the iterator’s error status. Always check after iteration completes.

Range Queries

Bounded Range Iteration

Iterate over a specific key range:
Setting iterate_upper_bound can significantly improve performance by allowing RocksDB to skip unnecessary data.

Prefix Iteration

Efficiently iterate over keys with a common prefix:

Snapshot Iteration

Iterate over a consistent snapshot:
Iterators created with a snapshot will read data as it existed when the snapshot was created, even if the data is subsequently modified or deleted.

Performance Optimization

Read-Ahead

Enable read-ahead for sequential scans:

Skip Block Cache

For large scans that shouldn’t pollute the cache:

Tailing Iterator

For monitoring new data in real-time:

Multi-Column Family Iteration

NewIterators for Multiple Column Families

Error Handling

Always check iterator status after iteration:
An iterator can become invalid due to errors (I/O errors, corruption). Always check status() after iteration completes.

Common Patterns

Count Keys in Range

Batch Processing

Best Practices

1

Always delete iterators

Iterators hold resources. Delete them when done.
2

Check status after iteration

Errors can occur during iteration. Always check status() after the loop.
3

Use bounded iteration

Set iterate_upper_bound to improve performance for range queries.
4

Consider fill_cache

Set fill_cache = false for large scans to avoid cache pollution.
5

Use snapshots for consistency

Create a snapshot if you need a consistent view across multiple operations.

Next Steps

Basic Operations

Learn fundamental CRUD operations

Transactions

Implement ACID transactions

Performance Tuning

Optimize iterator performance