# CMS.MERGE

> Replace a Count-min sketch with the sum, optionally weighted, of other sketches.

URL: https://docs.hotkv.com/commands/cms-merge/

```
CMS.MERGE destination numkeys source [source ...] [WEIGHTS weight [weight ...]]
```

- Group: Count-min sketch
- Complexity: O(n * width * depth), n being the sources
- HotKV Cloud: all plans
- On-Premise: no license needed

`CMS.MERGE` sets the Count-min sketch at `destination` to the sum of the
`numkeys` source sketches, counter by counter. With `WEIGHTS`, each source is
multiplied by its weight first. Use it to combine sketches kept per server,
per shard or per time window.

The destination must already exist, and every sketch must have the same width
and depth (create them with the same arguments). The destination's previous
counts are replaced, not added to; list it among the sources to add to it.

## Options

| Option | Effect |
| --- | --- |
| `WEIGHTS weight ...` | One integer weight per source, in order (default 1 each). Weights may be negative, as long as no counter ends below 0. |

## Return value

| Case | RESP2 | RESP3 |
| --- | --- | --- |
| Merged | Simple string `OK` | Simple string `OK` |

Error replies:

- `CMS: key does not exist` if the destination or a source is missing.
- `CMS: width/depth is not equal`
- `CMS: invalid numkeys` and `CMS: Number of keys must be positive`
- `CMS: wrong number of keys` and `CMS: wrong number of keys/weights`
- `CMS: invalid weight value`
- `CMS: MERGE overflow` when a counter would go below 0 or past 4294967295 (the destination is left unchanged).
- `WRONGTYPE` if a key holds another type.

## Examples

```
127.0.0.1:6379> CMS.INITBYDIM day1 2000 5
OK
127.0.0.1:6379> CMS.INITBYDIM day2 2000 5
OK
127.0.0.1:6379> CMS.INITBYDIM week 2000 5
OK
127.0.0.1:6379> CMS.INCRBY day1 /home 10
1) (integer) 10
127.0.0.1:6379> CMS.INCRBY day2 /home 4
1) (integer) 4
127.0.0.1:6379> CMS.MERGE week 2 day1 day2
OK
127.0.0.1:6379> CMS.QUERY week /home
1) (integer) 14
127.0.0.1:6379> CMS.MERGE week 2 day1 day2 WEIGHTS 1 2
OK
127.0.0.1:6379> CMS.QUERY week /home
1) (integer) 18
```

## Compatibility

Same as `CMS.MERGE` in RedisBloom, including the requirement that the
destination exists.

## See also

[CMS.INITBYDIM](https://docs.hotkv.com/commands/cms-initbydim/index.md), [CMS.QUERY](https://docs.hotkv.com/commands/cms-query/index.md), [CMS.INFO](https://docs.hotkv.com/commands/cms-info/index.md)