clarkk
clarkk

Reputation: 27689

redis - fetch all hashes by pattern/prefix

I have a hash pattern websocket:socket:*

$redis->hMSet('websocket:socket:1', ['block' => 9866]);
$redis->hMSet('websocket:socket:2', ['block' => 854]);
$redis->hMSet('websocket:socket:3', ['block' => 854]);

How can I fetch all hashes that matches pattern websocket:socket:* ??

Or what is the best way (performange wise) to keep track of a list of items?

Upvotes: 1

Views: 751

Answers (2)

Charles Thayer
Charles Thayer

Reputation: 402

Update: Newer versions of redis let you scan by "type hash" and use "match foo*" so you can now scan 0 type hash match websocket:socket:* to answer the original question.

Here I have several pieces of data for my go-crawler so I can keys go-crawler* and one of these is a has (stats) so I can see that with scan 0 type hash match go-crawler:*. Once I have that I can hgetall go-crawler:request:site:statsorhkeys go-crawler:request:site:stats`, though I don't know of a way to filter those keys by "match".

Here's a redis-cli example

127.0.0.1:6379> scan 0 type hash
1) "0"
2) 1) "go-crawler:request:site:stats"
127.0.0.1:6379> scan 0 type hash match "go-crawler:*"
1) "0"
2) 1) "go-crawler:request:site:stats"
127.0.0.1:6379> hset thayer one 1
(integer) 1
127.0.0.1:6379> scan 0 type hash match "go-crawler:*"
1) "0"
2) 1) "go-crawler:request:site:stats"
127.0.0.1:6379> scan 0 type hash
1) "0"
2) 1) "thayer"
   2) "go-crawler:request:site:stats"
127.0.0.1:6379> 
:::: graphite 01:30:52 (main) 0 crawl-mo; redis-cli
127.0.0.1:6379> keys go-crawler*
1) "go-crawler:link:queue"
2) "go-crawler:request:site:stats"
3) "go-crawler:task:queue"
127.0.0.1:6379> hgetall thayer
1) "one"
2) "1"

Upvotes: 0

Itamar Haber
Itamar Haber

Reputation: 49942

Redis does not provide search-by-value out of the box. You'll have to implement some kind of indexing yourself.

Read more about indexing in Redis at Secondary indexing with Redis (or use RediSearch).

Upvotes: 3

Related Questions