Why Use Merge Operators?
Performance
Merge operations are faster than read-modify-write cycles, especially under high concurrency.
Concurrency
Multiple merge operations can be applied concurrently without coordination.
Efficiency
Merge operands are smaller than full values and can be batched together.
Atomicity
Merge operations are atomic and consistent with RocksDB’s guarantees.
Merge Operator Types
RocksDB provides two types of merge operators:AssociativeMergeOperator
For simple associative operations (e.g., numeric addition, string concatenation):MergeOperator
For more complex operations with multiple merge operands:Basic Usage
Configuring a Merge Operator
Using Merge Operations
Implementing AssociativeMergeOperator
String Append Example
Implementing Full MergeOperator
For more complex scenarios, implement the fullMergeOperator interface:
JSON Merge Example
MergeOperator API Reference
MergeOperationInput
MergeOperationOutput
Advanced Features
PartialMerge
Optimize by combining merge operands before full merge:PartialMerge is called during compaction to reduce the number of merge operands, improving read performance.Wide Column Support (FullMergeV3)
For wide-column entities:Merge in Transactions
Merge operations work with transactions:Performance Considerations
1
Keep merge operands small
Smaller operands are more efficient to store and combine.
2
Implement PartialMerge
Reduce the number of operands during compaction for better read performance.
3
Use AllowSingleOperand()
If your merge operator can handle a single operand efficiently, override this method to return
true.4
Handle errors gracefully
Return
false from merge methods if the operation cannot be performed, and log the error.Common Use Cases
- Counters
- Append-Only Logs
- Set Operations
- JSON/Document Updates
Implement atomic increment/decrement operations without explicit locking.
Built-in Merge Operators
RocksDB provides some built-in merge operators:Error Handling
Best Practices
1
Keep operations simple
Merge operators should be deterministic and fast.
2
Test thoroughly
Test with various combinations of Put, Merge, and Delete operations.
3
Document semantics
Clearly document what your merge operator does and its assumptions.
4
Version your operator
If you change merge semantics, use a new operator name to avoid compatibility issues.
5
Handle missing values
Your merge operator must handle the case where there’s no existing value (nullptr).
Next Steps
Basic Operations
Learn fundamental CRUD operations
Transactions
Use merge operators in transactions
Performance Tuning
Optimize merge performance