Question

How to optimize this SQL query for a couchdb view ?

SELECT * FROM db WHERE user = '$userid' OR userFollowed = '$userid'

The couchdb database contains this structure of documents:

_id
user    
userFollowed

This because a user can follows another and viceversa and my scope is to get all followers of user A that this user which follows it turn, for example:

A follows B

B follows A

In this example I need to get B, enstabilishing that both users are followers... I know it's complex to explain and understand but I'll try with the things I'm doing with node.js and cradle.

The view map:

function (doc) { 
    emit(doc.user, doc.userFollowed) 
}

The node.js code:

db.view("followers/getFollowers", function(err, resp) {
  if (!err) {
     var followers = [];

     resp.forEach(function(key, value, id) {
        var bothFollow = false;

        if (key == userID) {
           if (followers.indexOf(value) == -1) {                  
              resp.forEach(function(key, value, id) {
                 if (value == userID)
                    bothFollow = true;
              });

              if (bothFollow)
                 followers.push(value);
           }
         } else if (value == userID) {
           if (followers.indexOf(key) == -1) {
              resp.forEach(function(key, value, id) {
                 if (key == userID)
                    bothFollow = true;
              });

              if (bothFollow)
                 followers.push(key);
           }
        }
     });

     console.log(followers);
  }
});    

So in the code first I check if the A or B values corrispondes to the other user, then check with another loop if there is a relationship putting the follower in the list

All this code works but I don't think that's the correct procedure and maybe I'm wrong anything :( can you help me please ?

Was it helpful?

Solution

It is easier to emit both users in the view function:

function (doc) { 
    emit(doc.user, null); 
    emit(doc.userFollowed, null); 
} 

Than you can just call the view and will get a plain list:

http://localhost:5984/db/_design/app/_view/followers?include_docs=true
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top