i have a nodejs/react
app and i know how to store data in objects in redis
(hmset),
but the issue is i want to get all the hashes with its values stored in redis db, rather than getting one by one as below function,
-
is there any redis built in function to do this?
-
if not what are the options available for me to execute this functionality?
redisClient.hgetall(category, (err, object) => {
if(err) {
console.error(err);
} else {
console.log(object);
}
});
2
Answers
Based on your response, I’ll assume that there are more than just
category
entries in your redis. That being the assumption, here’s a solution that is moderately common and that I’ve used before:Use a separate SET to track the keys that contain category records. Since SETs deduplicate already, you don’t need to worry about duplicate entries
Somewhere else in your code, when you want to pull all of your categories if the number of records balloons, you should really use SSCAN to iterate through the entries of a SET instead of popping SMEMBERS on a very large entry.
Now I used async/await syntax here, because I didn’t lookup the old async library signature for doing chunked callback-based async requests, but that should be pretty easy if you’re still in a callback system. Keep in mind the number of promises you may be generating and probably chunk this request somehow.
When/if you delete a category entry by calling DEL on a key, you’ll also call SREM on the same key within the tracking set
Something else to think about is doing the writing operations (set, delete) within a MULTI block, though that’s not a hard requirement.
If you are able to use RediSearch, it was created to solve this very problem. You just need to create an index to make your Hashes searchable:
FT.CREATE category:index ON HASH PREFIX 1 category: SCHEMA field TAG another_field NUMERIC a_third_field TEXT
And then you can search it:
FT.SEARCH category:index '@field:{ javascript | typescript } @another_field:[23 42] @a_third_field:patterns
If you want everything—which is sounds like you do—you can search for that too:
FT.SEARCH category:index '*'