【问题标题】:mongoDB - Text Search in multiple fields using node.jsmongoDB - 使用 node.js 在多个字段中进行文本搜索
【发布时间】:2015-12-13 06:27:57
【问题描述】:

我正在尝试使用 Node.JS 连接到 MongoDB 数据库(全部托管在 heroku 上,因此使用 MongoLab 插件)来执行文本搜索。我想在我的文档中搜索变量关键字的某些字段(字符串或字符串数​​组,但我可以将它们更改为所有需要的字符串)。

希望下面的代码可以在“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)) });
    } 
}

【问题讨论】:

    标签: node.js mongodb heroku


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-16
      • 2014-11-19
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      相关资源
      最近更新 更多