Redis(4)-實現聯集、交集和差集

Redis的Sets datatype(集合資料類型)和c#的HashSet很類似,

而且也是只使用key的Dictionary精簡版。

Sets存放資料都是未排序的字串,並且不允許重複資料,例如新增多筆相同資料,

但集合永遠只會有單一資料,這也表示,新增任何資料我們都可以不用先判斷是否存在集合後再新增,

且每一個Sets最大總數超過40億(對真實世界絕對足夠)。而我對Sets比較感興趣的是,

你可以針對存在的集合,快速進行union(聯集)、intersections(交集)和differences(差集)操作,

可應用在如及時統計網站在線總人數..等。

下圖為Set的所有方法,但我這裡只簡單示範CRUD和union、intersections和differences。

StackExchangeRedisHelper _StackExchangeRedisHelper = new StackExchangeRedisHelper();
            RedisKey key1 = "setRico";
            RedisKey key2 = "setSherry";
            using (conn = _StackExchangeRedisHelper.SafeConn)
            {
                IDatabase _IDatabase = conn.GetDatabase();
                
                //insert
                for (int i = 1; i <= 10; i++)
                    _IDatabase.SetAdd(key1, i);
                var members = _IDatabase.SetMembers(key1);//select 該集合所有成員
                Console.WriteLine(string.Join(",", members));

                //delete
                _IDatabase.SetRemove(key1, 3);
                Console.WriteLine(_IDatabase.SetContains(key1, 3)); //判斷 3 是否存在該集合
            
                members = _IDatabase.SetMembers(key1);

                _IDatabase.SetAdd(key2, "SherryAndRico".Select(x => (RedisValue)x.ToString()).ToArray());

                var values = _IDatabase.SetCombine(SetOperation.Union, key1, key2);//key1 和 key2 兩個集合聯集
                Console.WriteLine("UNION:" + string.Join(",", values));

                values = _IDatabase.SetCombine(SetOperation.Difference, key1, key2);//key1 和 key2 兩個集合差集
                Console.WriteLine("EXCEPT:" + string.Join(",", values));

                values = _IDatabase.SetCombine(SetOperation.Intersect, key1, key2);//key1 和 key2 兩個集合交集
                Console.WriteLine("INTERSECT:" + string.Join(",", values));

                //Add apple to 
                _IDatabase.SetAdd(key2, "Ricoisme");
                //select by pattern
                var patternMatchValues = _IDatabase.SetScan(key2, "Ri*");
                Console.WriteLine(string.Join(",", patternMatchValues));

                patternMatchValues = _IDatabase.SetScan(key2, "*me");
                Console.WriteLine(string.Join(",", patternMatchValues));

                //從集合取隨機資料並刪除
                var randomVal = _IDatabase.SetPop(key1);            
                Console.WriteLine(randomVal);
                Console.WriteLine(_IDatabase.SetContains(key1, randomVal)); //是否存在該集合
            }

結果

也可使用Redis Desktop Manager 查看並管理Redis資料庫

 

參考

Data types

Redis Desktop Manager Documentation

Redis for .NET Developers – Redis Sets Datatype