总和使用Redis集合遍历求和不可思议的计算精确度(redis遍历集合并计算)

Working with large datasets requires bith power and accuracy, and computing their aggregate and summative values is an essential prerequisite for data analytics. Redis is a popular open-source, in-memory data structure store that has been around for more than a decade, and is used for tasks like caching, session handling and more. Redis Sets are a collection type offered by Redis that allow us to store non-repeating string, character and integers. In this tutorial, we will explore how to use Redis Sets to calculate sum of values.

In order to calculate the sum of values, the first step is to get all the values into a Redis Set. This can be done with the SADD (add) command. It takes a key followed by all the values, like so:

SADD my_values 1 2 3 4 5

The command will return the total number of values added to the set. The next step is to use the SMEMBERS (members) command to retrieve all the elements in the set. This command has the signature SMEMBERS .

SMEMBERS my_values

The command will return all the values in the set:

1
2
3
4
5

Now that all the values are in a Redis Set, we can use the SCARD (cardinal) command to get the count of elements in the set. SCARD returns the number of elements in the set.

Now, we can use the SINTERSTORE (intersection store) command to add all the elements in the set. SINTERSTORE takes two keys and stores all the common elements in the key provided, like so:

SINTERSTORE my_sum my_values my_sum

This command takes two sets and stores the sum of all elements in the key1. We can then use the SINTER (intersection) command to retrieve all the elements in the key.

SINTER my_sum

This will return the sum of all the elements in the set, 15 in this case!

We can then use the SDIFFSTORE (difference store) command to subtract an element from the set. Agn, it takes two keys and subtracts all the elements in key2 from the elements in key1. For example,

SDIFFSTORE my_sum my_values 5

This command will subtract 5 from all the elements in the set and store the reduced values in the key1. Agn, we can use the SINTER command to retrieve all the elements in the set which should now be 10.

Using Redis Set and these built-in commands, we can easily calculate summative values for large datasets. The accuracy and precision of the calculation is amazing since it is able to perform the operation on the fly, without having to write any code. There are a lot of other possible operations that can be performed on Redis Sets, so do check out the documentation to learn more.


数据运维技术 » 总和使用Redis集合遍历求和不可思议的计算精确度(redis遍历集合并计算)