Lalith
Lalith

Reputation: 20534

Redis keys as a regex?

I have to create a redis database with keys as regex patterns(URL pattern: May be I should say just URL path). So when a URL comes in to my application I need to see which pattern it fits in and get the key. Does redis already provide any easier way to do the pattern matching?

  Any thoughts to improve the logic is appreciated.

Regards, Lalith

Upvotes: 2

Views: 21352

Answers (4)

droid192
droid192

Reputation: 2232

Quick and production ready examply with redis-py client:

r = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True)
keys: List[str] = [k for k in r.scan_iter(match="norgx:but:blob:*", count=1000)]

now you have a list of all keys of interest and perform the regex on them (which are not supported by the SCAN command. The count reduces ping/pong overhead on big databases and is the scanned batch size before matching.

Upvotes: 1

robertomarin
robertomarin

Reputation: 1282

You could maintain two structures:

1 - First a list with all your keys. I mean, all your url-regex to match your urls. This should be updated every time you create another url-regex. Also you could have this in memory inside your application, so from time to time you read this list to update the items.

2 - Second the url-regex keys. This is the keys you where referring to, so here you put your values, whatever they are.

I don't think using keys is a good idea. It's not for production usage, at least not with business logic making use of it.

From the doc keys:

Warning: consider KEYS as a command that should only be used in production environments with extreme care. It may ruin performance when it is executed against large databases. This command is intended for debugging and special operations, such as changing your keyspace layout. Don't use KEYS in your regular application code. If you're looking for a way to find keys in a subset of your keyspace, consider using SCAN or sets.

Upvotes: 1

shahmanthan9
shahmanthan9

Reputation: 523

redis-cli keys "user:*" | grep "user:[0-9]\+$" | xargs redis-cli DEL

This is taken from Here

Upvotes: 3

alphazero
alphazero

Reputation: 27224

antirez has his lua-scripting branch up. Give it a try ;)

Upvotes: 2

Related Questions