2017-10-01 25 views
1

我使用nodeJs Mongoose来执行文本搜索;文本搜索空白转义

var mongoose = require('mongoose'); 
var config = require('../config'); 
var mongoosePaginate = require('mongoose-paginate'); 
var poiSchema = mongoose.Schema({ 
    city:String, 
    cap:String, 
    country:String, 
    address: String, 
    description: String, 
    latitude: Number, 
    longitude: Number, 
    title: String, 
    url: String, 
    images:Array, 
    freeText:String, 
    owner:String, 
}); 
poiSchema.index({'$**': 'text'}); 

poiSchema.plugin(mongoosePaginate); 
mongoose.Promise = global.Promise; 
mongoose.connect(config.database); 
module.exports = mongoose.model('Poi', poiSchema); 

正如你可以在这里看到

poiSchema.index({'$**': 'text'}); 

我创建我的架构内各个领域的文本索引。

当我尝试执行文本搜索,我开发这个代码:

var term = "a search term"; 

var query = {'$text':{'$search': term}}; 
Poi.paginate(query, {}, function(err, pois) { 
    if(!pois){ 
     pois = { 
      docs:[], 
      total:0 
     }; 
    } 
    res.json({search:pois.docs,total:pois.total}); 
}); 

不幸的是,当我使用的空白项里面搜索,它会读取每一个单场比赛中短期集合里面的所有文件搜索按空白分隔。

我想象文本索引有作为标记化器空白;

我需要知道如何逃避空白,以搜索具有整个术语搜索而不分裂它的每个领域。

我试图用\\替换空格,但没有任何更改。

可以请别人帮我吗?

回答

2

MongoDB允许对字符串内容进行文本搜索查询,支持不区分大小写,分隔符,停用词和词干。搜索字符串中的术语默认为OR。从文档中,$search字符串是...

MongoDB解析并用于查询文本索引的字符串。除非指定为短语,否则MongoDB会对术语执行逻辑OR搜索。

所以,如果你$search字符串中的至少一个词语匹配,那么MongoDB的返回文档和MongoDB搜索使用所有项(其中一个术语是由空格分隔字符串)。

您可以通过指定一个短语来更改此行为,您可以通过将多个词语用引号引起来进行更改。在你的问题中,我认为你想要搜索的确切短语:a search term所以只需将该短语包含在转义字符串引号中。

下面是一些例子:

  • 鉴于这些文件:

    { "_id" : ..., "name" : "search" } 
    { "_id" : ..., "name" : "term" } 
    { "_id" : ..., "name" : "a search term" } 
    
  • 下面的查询将返回...

    // returns the third document because that is the only 
    // document which contains the phrase: 'a search term' 
    db.collection.find({ $text: { $search: "\"a search term\"" } }) 
    
    // returns all three documents because each document contains 
    // at least one of the 3 terms in this search string 
    db.collection.find({ $text: { $search: "a search term" } }) 
    

因此,简言之你可以通过封闭空间“逃避空白”在转义字符串引号中输入搜索字词...而不是"a search term"使用"\"a search term\""