文本search空白转义

我使用nodeJs Mongoose来执行文本search;

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

我在模式中的每个字段上创build一个文本索引。

当我尝试执行文本search时,我开发了这个代码:

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

不幸的是,当我在术语search中使用空格时,它将会获取集合内部的所有文档,这些文档与词语search中的每个字段匹配。

我认为文本索引具有标记符空白符;

我需要知道如何逃避空白,以search每一个领域的整个术语search,而不分裂。

我尝试用\\replace空格,但没有任何更改。

可以请别人帮我吗?

MongoDB允许对string内容进行文本search查询,支持不区分大小写,分隔符,停用词和词干。 您searchstring中的字词默认为“或”。 从文档中, $searchstring是…

MongoDBparsing并用来查询文本索引的string。 除非被指定为短语,否则MongoDB会执行术语的逻辑ORsearch。

因此,如果$searchstring中至less有一个词匹配,那么MongoDB将返回该文档,并使用所有术语(其中一个词是由空格分隔的string)进行MongoDBsearch。

你可以通过指定一个短语来改变这个行为,你可以通过在引号中包含多个词来做到这一点。 在你的问题中,我你想search一个确切的词组: a search term所以只要把这个短语在转义string引号。

这里有些例子:

  • 鉴于这些文件:

     { "_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" } }) 

因此,总而言之,通过将您的search字词放在转义string引号中而不是"a search term"使用"\"a search term\"" "a search term" ”来避免空格。

Interesting Posts