Overview
AComparator defines the total order across keys in RocksDB. Custom comparators allow you to implement application-specific key ordering beyond simple lexicographic byte comparison.
The Comparator Interface
TheComparator class from comparator.h:44 provides the core abstraction for key ordering:
Key Methods
Compare() - The core comparison function. Must be:- Thread-safe (may be called concurrently from multiple threads)
- Consistent (same inputs always produce same output)
- Transitive (if a < b and b < c, then a < c)
Names starting with “rocksdb.” are reserved. Use a custom prefix for your comparators.
Built-in Comparators
RocksDB provides several built-in comparators defined incomparator.h:187-208:
BytewiseComparator
ReverseBytewiseComparator
User-Defined Timestamp Comparators
Implementing a Custom Comparator
Example: Integer Key Comparator
Using Your Custom Comparator
User-Defined Timestamps
Starting from RocksDB 7.0, you can associate timestamps with keys. TheComparator constructor accepts a timestamp size:
Timestamp Handling
When timestamps are enabled (timestamp_size_ > 0):
Timestamp Utilities
Fromcomparator.h:216-234:
Advanced Features
Key Equivalence
false if your comparator ensures different byte sequences are always different keys. This enables optimizations like DataBlockHashIndex.
Same-Length Successor Detection
true if t is the immediate successor of s with the same length.
Best Practices
Thread Safety: Comparators must be thread-safe. All methods may be called concurrently from multiple threads.
Performance Considerations
- Optimize Compare() - This is called very frequently in hot paths
- Avoid memory allocations - Use stack variables when possible
- Keep it simple - Complex comparisons add overhead to all operations
Migration
Changing comparators requires careful planning:- Export data with old comparator
- Create new database with new comparator
- Import data into new database
Filter Integration
Fromfilter_policy.h:159-165:
If the comparator ignores trailing spaces, it would be incorrect to use a FilterPolicy (like NewBloomFilterPolicy) that does not ignore trailing spaces in keys.