Home > Blockchain >  Redis sortedset get top 100 or N scores with values in descending order error
Redis sortedset get top 100 or N scores with values in descending order error

Time:12-13

I have nodejs(typescript) with https://www.npmjs.com/package/redis package and redis version is redis_version:4.0.14. I am trying to get the top 100 scores with values from a sorted set. It runs ok for ascending order but when I set REV: true for descending it throws an syntax error exception. Descending order is what I need for the leaderboard. Is there something that I am doing wrong?

redisClient.zRangeWithScores('lb:global', 0, 99)

This gives => [{"value":"user:2","score":10}, {"value":"user:4","score":20}....{"value":"user:1","score":100}]

The above command works fine but the command below for descending order does not

redisClient.zRangeWithScores('lb:global', 0, 99, { REV: true })

This gives => [ErrorReply: ERR syntax error]

CodePudding user response:

You're using Redis 4.x. Node Redis doesn't support that version—see the supported Redis versions in the README.

That said, sometimes it works because many of the commands haven't changed. GET, for example, is pretty basic and hasn't changed much. ZRANGE, however, has changed.

Your code would generate the following Redis command:

ZRANGE lb:global 0 99 REV WITHSCORES

According to the documentation for the ZRANGE command, REV was added in Redis 6.2:

Starting with Redis version 6.2.0: Added the REV, BYSCORE, BYLEX and LIMIT options.

Your install of Redis 4.0 doesn't know what to do with REV and so you get a Syntax Error.

The correct solution would be to upgrade to a newer version of Redis. Of course, that's not always practical. So, I offer a workaround.

You can use .sendCommand to call the deprecated ZREVRANGE command directly. It just takes an array of strings with the bits and bobs of the command you want to send:

await redisClient.sendCommand(['ZREVRANGE', 'lb:global', '0', '99'])

Note that any numeric values will need to be turned to strings for this to work.

Hope this helps and I hope you are able to upgrade your Redis version. But if not, needs must when the devil drives.

  • Related