Fastest way to check key exists in redis - php
Asked Answered
L

3

7

Is there any other faster way than EXISTS, to check if a key exists in redis or not?

My problem is, I have over 1 million records in redis and I need to do a key_exists check. This should happen within 10ms.

Any Ideas around this?

Leuco answered 19/12, 2016 at 12:55 Comment(1)
EXISTS has a time complexity of O(1), that's the best that you can get.Albertinealbertite
R
9

Using the EXISTS command is the fastest way, this should be extremely quick. If you feel that it's too slow its probably the latency between your server and the redis server and nothing to do with the command itself.

Rozanneroze answered 19/12, 2016 at 12:57 Comment(0)
M
0

To reduce the time you need to keep indexes of your keys using some pattern logical to your application. This means instead of having to do exists on the all the keys you can do a sismember or zscore on your index set/zset. So for example you have keys related to users, messages and leaderboards etc you keep sets called keys:users , keys:messages etc. I have a library just open sourced to help manage your key names and make this stuff a bit easier https://github.com/imikemiller/Pkeys

Menthol answered 30/7, 2017 at 20:27 Comment(0)
F
0

The time complexity of the exists is O(1), so it's the fastest possible algorithm.

Your problem is from somewhere else, But you can check the real execution time of the exists using the SLOWLOG command to make sure.

Fries answered 6/6, 2020 at 4:34 Comment(2)
The Redis documentation indicates that EXISTS is an O(N) operation based on the size of the keyspace it is searching. If the keyspace is very large, it could still be a slow operation.Trout
@Trout Nope. The N in O(N) refers to the number of input keys. So if you enter the three keys, You will have O(3). But the main operation of deleting a key is O(1). From Documentation: Time complexity: O(N) where N is the number of keys to check. So Still, it's O(1) and the fastest possible way.Fries

© 2022 - 2024 — McMap. All rights reserved.