2014-03-31 113 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