2014-03-31 67 views
0

如何为couchdb视图优化此SQL查询?为couchdb视图优化SQL查询

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

CouchDB的数据库包含的文件,这样的结构:

_id 
user  
userFollowed 

这是因为用户可以遵循另一个,反之亦然,我的范围是让用户A随后该用户把它转化的所有追随者,例如:

甲如下乙

乙如下甲

在这个例子中,我需要得到B,两个用户都是追随者,这是稳定的......我知道解释和理解很复杂,但我会尝试使用node.js和摇篮来做的事情。

视图地图:

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

Node.js的代码:

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); 
    } 
});  

所以在代码首先我检查,如果A或B的值corrispondes给其他用户,然后用检查另一个循环,如果有关系把追随者列表

所有这些代码的作品,但我不认为这是正确的程序,也许我错了什么:(你能帮助我Ase?

回答

1

更容易在视图功能,同时发射的用户:

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

比你可以调用视图,并会得到一个简单的列表:

http://localhost:5984/db/_design/app/_view/followers?include_docs=true