2017-10-01 27 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\""