当前位置: 动力学知识库 > 问答 > 编程问答 >

nosql - Unique value in redis list/set

问题描述:

I am new to redis and trying to learn it.


I want to make list of existing products but I want implementation in such way that I should not able to add duplicate entry in list of products.


My product list should not contain duplicate product name.


but I am not able to implement such scenario, my list is accepting duplicate entry also.


Can anyone help me to show how to add unique value in list?

网友答案:

Instead of using a list, use a set. Sets are containers for unique objects. Each object can only appear once in a set. Take a look at the set-related commands here: http://redis.io/commands/#set.

And an example using redis-cli (we attempt to add "Product One" twice, but it only appears once in the list of products):

$ redis-cli
127.0.0.1:6379> sadd products "Product One"
(integer) 1
127.0.0.1:6379> sadd products "Product Two"
(integer) 1
127.0.0.1:6379> sadd products "Product Three"
(integer) 1
127.0.0.1:6379> sadd products "Product One"
(integer) 0
127.0.0.1:6379> smembers products
1) "Product Three"
2) "Product One"
3) "Product Two"
127.0.0.1:6379>
网友答案:

In case you need to maintain the order and the uniqueness you can use a sorted set

127.0.0.1:6379> zadd products 1 "Product One"
(integer) 1
127.0.0.1:6379> zadd products 2 "Product Two"
(integer) 1
127.0.0.1:6379> zadd products 3 "Product Tree"
(integer) 1
127.0.0.1:6379> zadd products 4 "Product Four"
(integer) 1
127.0.0.1:6379> zrange products 0 -1
1) "Product One"
2) "Product Two"
3) "Product Tree"
4) "Product Four"
分享给朋友:
您可能感兴趣的文章:
随机阅读: