node.jsmapreducecouchdbrecommendation-enginenano

recommendation engine with apache couch-db and nano: filter a view for a specific user


I'm building a recommendation system for a webshop. The shopping history is saved in a couch-db database. I'm creating a view through map-reduce that emits for each user and product, the quantity of that product bought. The reduce parts consists in taking the sum.

// map 
const onCheckout = (doc) => {
  const { username, items } = doc;

  // once a checkout is done (i.e. history db is populated)
  // map every items bought
  items.map((item) => emit([username, item.name], item.quantity));
};

I can then fetch my recommendation service and grab the view.

router.get("/recommendation/user", jwt, (req, res) => {
  const { username } = req.auth;
  history
    .view("on-checkout__user", "items_bought", {
      group: true,
    })
    .then((body) => {
      console.log(body.rows);
      res.status(200).json({ content: body.rows });
    })
    .catch((err) => res.send(err));
});

This gives me the following results view

The first key is the username, then the product. The value is the total quantity of that product bought by the user. However, I would like the filter that view only for a specific user (the one that makes the request with a JWT in the headers, e.g. only for the user called "potiron"). I know I can pass a key in the parameters of the view function, I tried with {key: "potiron"} but it does not work. Is there any other way ?


Solution

  • Your key is not a string, it's an array. You'd want to do something like: startkey=["potiron"]&endkey=["potiron",{}]

    Reference