How to use HSCAN command in Redis?
Asked Answered
U

2

13

I want to use Redis's HSCAN command in my assignment but I have no idea how it works. Redis's official page (http://redis.io/commands/hscan) for this command gives me blank page.

I am getting continuous input data and saving them instantaneously in multiple hashes in Redis and I would like to iterate through all of them at later point of time.

I'm using following command to save my data

HMSET myhash ordertype "neworder" order_ts "1234" act_type "order_ack" ack_ts "1240"
HMSET myhash2 ordertype "neworder" order_ts "2234" act_type "order_ack" ack_ts "2240"

Can anyone give me some examples of how to use HSCAN?

In my case I would like to get following output
1) myhash
2) myhash2
3) myhash3
.
.
.
.

Unparalleled answered 11/11, 2013 at 15:54 Comment(0)
E
17

Commands

Start a full hash scan with:

HSCAN myhash 0

Start a hash scan with fields matching a pattern with:

HSCAN myhash 0 MATCH order_*

Start a hash scan with fields matching a pattern and forcing the scan command to do more scanning with:

HSCAN myhash 0 MATCH order_* COUNT 1000

Note

Don't forget that MATCH can return little to no element for each iteration, as explained in the documentation:

It is important to note that the MATCH filter is applied after elements are retrieved from the collection, just before returning data to the client. This means that if the pattern matches very little elements inside the collection, SCAN will likely return no elements in most iterations.

And that's why you can use COUNT to force more scanning for each iteration.

[Update] As Didier Spezia specified, you'll need Redis 2.8+ to use the *SCAN commands.

Ezekiel answered 12/11, 2013 at 10:44 Comment(3)
And please note you need Redis 2.8 to get scanning capabilities. Stable Redis is still 2.6.Narcissus
I think he is confused. what he want is the hash keys as output while HSCAN will scan the values of scan.Parasitic
Is it possible to use match in a complex data type/Object?Maulmain
E
12

As mentioned by you. you need to get the output of hash keys

myhash
myhash2
myhash3

HSCAN is not for this purpose. HSCAN is to scan the fields of a particular HASH. so you can scan the fields of myhash or myhash2. But if you want to find the keys on the basis of patterns you have two options.

Create a SET with the HASH keys

SADD hashkeys "myhash" "myhash1" "myhash2"

SMEMBERS hashkeys
    1) "myhash"
    2) "myhash2"
    3) "myhash1"

If you are using 2.8 I would recommend you use sscan instead of smembers

sscan hashkeys 0 match my*

USE ONLY SCAN COMMAND

scan 0 MATCH myhash* count 1000 

USE key matching (NOT RECOMMENDED AS it will block the redis server)

keys myhash*

So long story cut sort to fetch the keys you can use SMEMBERS, SSCAN or KEYS. Ofcourse best is SSCAN if you are using redis 2.8

Esophagitis answered 20/11, 2013 at 0:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.