Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js & redis / zadd objects to a set

Tags:

node.js

redis

I have the following code:

var db = require("redis");
var dbclient1 = db.createClient();

dbclient1.zadd("myprivateset", 3, {"guid":"abab-baba", "data-persistent":"xxxx", "size":"20"})
dbclient1.zadd("myprivateset", 2, {"guid":"abab-baba3", "data-persistent":"xxxx", "size":"20"})
dbclient1.zrangebyscore("myprivateset", 1, 4)
dbclient1.hgetall("myprivateset", function(err, rep){
 console.log(rep);
});

I wish to store my objects (in JSON format) in a sorted set, which determine by the score (3 & 2 in our case).

For some reason, when I print this table (rep), I get undefined.

What I do wrong?

like image 358
MIDE11 Avatar asked Jun 09 '15 07:06

MIDE11


People also ask

What is NodeJS used for?

Node. js is primarily used for non-blocking, event-driven servers, due to its single-threaded nature. It's used for traditional web sites and back-end API services, but was designed with real-time, push-based architectures in mind.

Is NodeJS better than Python?

Node is better for web applications and website development whereas Python is best suitable for back-end applications, numerical computations and machine learning. Nodejs utilize JavaScript interpreter whereas Python uses CPython as an interpreter.

Is NodeJS frontend or backend?

A common misconception among developers is that Node. js is a backend framework and is only used for building servers. This isn't true: Node. js can be used both on the frontend and the backend.

Is NodeJS a programming language?

Is Node JS a Language? No. Node JS is not a programming language, but it allows developers to use JavaScript, which is a programming language that allows users to build web applications. This tool is mostly used by programmers who use JavaScript to write Server-Side scripts.

What is node Node JS?

Node.js is an open source server environment. Node.js allows you to run JavaScript on the server. Our "Show Node.js" tool makes it easy to learn Node.js, it shows both the code and the result. res.end('Hello World!');

Are there any open source libraries for Node JS?

There are thousands of open-source libraries for Node.js, most of them hosted on the npm website. The Node.js developer community has two main mailing lists and the IRC channel #node.js on freenode.

What is the latest version of Node JS?

In February 2016, Node.js 0.10.42 is released and in May 2022 Node.js version is Node.js 18.2.0 is also released. [44] In 2019, the JS Foundation and Node.js Foundation merged to form the OpenJS Foundation .

How do I start developing with Node JS?

Download the Node.js source code or a pre-built installer for your platform, and start developing today.


3 Answers

Issue 1 -- sorted set keys

Try stringifying the JSON you are using as the keys of your sorted set. For example,

dbclient1.zadd("myprivateset", 3, {"guid":"abab-baba", "data-persistent":"xxxx", "size":"20"}) 

needs to be:

dbclient1.zadd("myprivateset", 3, JSON.stringify({"guid":"abab-baba", "data-persistent":"xxxx", "size":"20"})) 

Without stringifying the keys, every zadd will use the key [object Object] overwriting each time. That is, you'll only ever have one item in your sorted set that is unidentifiable (other than by [object Object]).

Issue 2 -- fetching data

Also, hgetall is not the redis command to use for retrieving data in a redis sorted set. You'll want to focus on sorted set specific commands. A list of redis commands are listed here: http://redis.io/commands

like image 126
cpentra1 Avatar answered Oct 14 '22 12:10

cpentra1


My two cents, building on comments by @leonid-beschastny and @cpentra1. I recommend using redis.multi(). It allows for several calls in a batch, and as you can see in the example, as soon as the three elements are added to the ordered set, we can perform a zrangebyscore in the same multi batch and get the expected results. Instructions can be created dynamically. The replies array when multi.exec() is invoked returns the results for each of the multi operations, in order.

var db = require("redis");
var dbclient1 = db.createClient();
var multi = dbclient1.multi();

// We use JSON.stringify() as suggested by @cpentra1 
multi.zadd("myprivateset", 3, JSON.stringify({"guid":"abab-baba", "data-persistent":"xxxx", "size":"20"}));
multi.zadd("myprivateset", 2, JSON.stringify({"guid":"abab-baba3", "data-persistent":"xxxx", "size":"20"}));
multi.zadd("myprivateset", 2, JSON.stringify({"guid":"abab-dafa3", "data-persistent":"yyyy", "size":"21"}));
multi.zrangebyscore("myprivateset", 1, 4);
multi.zcard("myprivateset"); // The total number of elements in the set
multi.exec(function(err, replies) {
    console.log(replies)
    // Will output something like:
    // [ 1,
    //   1,
    //   1,
    //   [ '{"guid":"abab-baba3","data-persistent":"xxxx","size":"20"}',
    //     '{"guid":"abab-dafa3","data-persistent":"yyyy","size":"21"}',
    //     '{"guid":"abab-baba","data-persistent":"xxxx","size":"20"}' ],
    //   3 ]
});

Note: if you run the same example twice, instead of 1s in the first three elements of the replies array, you'll get 0s as the same member with the same score cannot be added twice.

like image 31
Óscar Palacios Avatar answered Oct 14 '22 13:10

Óscar Palacios


Seems like with Redis 6.2 the format has changed to and object with score and value attributes or an array of those, like this:

async function sortedSet() {
  let client;
  try {
    client = createClient();

    client.on("error", (err) => console.log("Redis Client Error", err));

    await client.connect();
    console.log("connected");

    await client.zAdd("user:0:followers", [{score: "1", value: "John"}, {score: "2", value: "Other John"}]);
    console.log("sorted set added");

  } finally {
    await client.quit();
  }
}

sortedSet("duto_guerra", "with hashes");

In case you are wondering, I figured this out by reading the source code for node-redis ZADD

like image 38
John Alexis Guerra Gómez Avatar answered Oct 14 '22 12:10

John Alexis Guerra Gómez