文本搜索空格转义

Text search whitespace escape

我正在使用 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});
});

不幸的是,当我在术语搜索中使用空格时,它会获取集合中与术语搜索中的每个字段相匹配的所有文档,并用空格分割。

我想文本索引有作为分词器的空白;

我需要知道如何转义空格,以便在不拆分的情况下搜索具有整个搜索词的每个字段。

我尝试用 \ 替换空格,但没有任何变化。

有人可以帮助我吗?

MongoDB 允许对字符串内容进行文本搜索查询,支持不区分大小写、定界符、停用词和词干提取。默认情况下,搜索字符串中的字词是或运算的。在文档中,$search 字符串是 ...

A string of terms that MongoDB parses and uses to query the text index. MongoDB performs a logical OR search of the terms unless specified as a phrase.

因此,如果您的 $search 字符串中至少有一个字词匹配,则 MongoDB return 将使用 allMongoDB 搜索该文档和 MongoDB =37=] 术语(其中术语是由空格分隔的字符串)。

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

这里有一些例子:

  • 鉴于这些文件:

    { "_id" : ..., "name" : "search" }
    { "_id" : ..., "name" : "term" }
    { "_id" : ..., "name" : "a search term" }
    
  • 以下查询将return ...

    // 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" } })
    

因此,总而言之,您 "escape whitespace" 通过将搜索词组括在转义字符串引号中...而不是 "a search term" 使用 "\"a search term\"".