Overview
RocksDB provides two interfaces for merge operations:- AssociativeMergeOperator: For simple, associative operations (e.g., numeric addition, string concatenation)
- MergeOperator: For complex, non-associative operations with full control over merge semantics
AssociativeMergeOperator
Interface
Merge Method
const Slice&
Key associated with the merge operation.
const Slice*
Current value, or nullptr if the key doesn’t exist.
const Slice&
Merge operand to apply.
std::string*
Output parameter for the merge result.
Logger*
Logger for error messages.
bool
Returns true on success, false on error.
Example: Counter Merge Operator
MergeOperator
FullMergeV3
MergeOperationInputV3
const Slice&
User key, including user-defined timestamp if applicable.
ExistingValue
Base value: no value, plain value, or wide-column value.
const OperandList&
List of merge operands to apply.
MergeOperationOutputV3
NewValue
Result: new plain value, new wide-column value, or existing operand.
OpFailureScope
Scope of failure: kDefault, kTryMerge, or kMustMerge.
PartialMerge
const Slice&
First operand.
const Slice&
Second operand.
std::string*
Output parameter for combined operand.
bool
Returns true if operands were combined, false if combination is not possible.
PartialMergeMulti
Example: String Append Merge Operator
Example: Complex JSON Merge
Advanced Features
ShouldMerge
const std::vector<Slice>&
Merge operands in reversed order (most recent first).
bool
Returns true to trigger merge immediately.
AllowSingleOperand
bool
Returns true to enable single-operand partial merge.
Failure Scopes
OpFailureScope
OpFailureScope
Flush and compaction fail, putting the DB in read-only mode.
OpFailureScope
Get and iteration fail, but flush/compaction can proceed by copying operands.
Performance Considerations
When to Use Merge
Good for:- Counters and statistics
- Append-only data structures
- Associative operations (sum, max, min)
- High-frequency updates to the same key
- Non-associative operations requiring all history
- Operations needing full value for every update
- Simple Put operations
Partial Merge Benefits
Implementing PartialMerge can significantly improve performance by:- Reducing full merge invocations
- Merging operands during compaction
- Reducing memory usage during Get
Memory Usage
Merge operands are stored until compaction or Get:- Many small operands can accumulate
- Use ShouldMerge to limit operand stack size
- Consider partial merge to reduce stack growth