2015-12-12 61 views
1

我試圖使用Node.JS連接到MongoDB數據庫(所有託管在heroku,因此使用MongoLab插件)來執行文本搜索。我想爲可變關鍵字搜索我的文檔的某些字段(字符串或字符串數​​組,但是我可以將它們更改爲所有需要的字符串)。mongoDB - 使用node.js在多個字段中搜索文本

下面的代碼希望做的是搜索關鍵字變量的'title'字段或'ingredients'字段,然後返回這些結果。 我懷疑ensureIndex行(嘗試ensureIndexcreateIndex),因爲刪除它們並不會改變程序的功能。

任何幫助,將不勝感激!

app.get('/searchtitle', function(request, response) { 
    response.header("Access-Control-Allow-Origin", "*"); 
    response.header("Access-Control-Allow-Headers", "X-Requested-With"); 
    response.set('Content-Type', 'application/json'); 

    var type = request.query.type; 
    var keyword = request.query.keyword; 

    if (type == 'title') { 
     db.collection('Test_Recipes').ensureIndex({ title: "text" }); 
     db.collection('Test_Recipes').find({ 
     $text: {$search: keyword } 
     }).toArray(function(err, results){ 
     response.send(JSON.stringify(results)) }); 
    } 
    else { 
     console.log("in else case: type is " 
       + type + " and keyword is " +keyword); 
     db.collection('Test_Recipes').ensureIndex({ingredients :"text"}); 
     db.collection('Test_Recipes').find({ 
     ingredients: {$elemMatch: keyword } }) 
     .toArray(function(err, results){ 
     response.send(JSON.stringify(results)) }); 
    } 
} 

回答

0

Indexes,在任何數據庫,需要創建一次,第一次創建collection時。創建索引是一項代價高昂的操作,也是一項blocking操作。

由於mongoDB 3.0有方法createIndex()ensureIndex()沒有什麼區別,而它們中的應使用的收集,創建索引只有一次,在服務器端,創建集當且僅當被修改需要。

索引既titleingredients領域,你需要在收集創建index爲:

db.collection.createIndex({"ingredients":"text","title":"text"}) 

這將確保這兩個字段是indexed,當文檔被插入。

我半信半疑的ensureIndex線(都嘗試ensureIndex和 上的createIndex),因爲刪除它們不會改變程序的功能 。任何幫助,將不勝感激!

這是因爲,createIndex()操作的行爲如何。 如果再次在同一個字段上創建索引,則只有第一次調用此方法成功,其他調用將被忽略。

然後只是查詢,如下將在titleingredients字段中查詢keyword

var type = request.query.type; 
var keyword = request.query.keyword; 
db.collection('Test_Recipes').find({ 
$text: {$search: keyword } 
}).toArray(function(err, results){ 
response.send(JSON.stringify(results)) 
});