我正在使用 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 返回该文档,MongoDB 将使用所有 术语进行搜索(其中一个术语是一个字符串,由空格)。
您可以通过指定短语来更改此行为,方法是将多个术语括在引号中。在您的问题中,我认为您想搜索确切的短语:一个搜索词
,因此只需将该短语括在转义字符串引号中即可。
这里有一些例子:
鉴于这些文档:
{ "_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\""
.
关于node.js - 文本搜索空格转义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46510708/