nodejs + mongodb實現模糊查詢與全文搜索


 

mongodb中的查詢條件

 

 

 

關鍵字 說明
$or 或關系
$nor 或關系取反
$gt 大於
$gte 大於等於
$lt 小於
$lte 小於等於
$ne 不等於
$in 在多個值范圍內
$nin 不在多個值范圍內
$all 匹配數組中多個值
$regex 正則,用於模糊查詢
$size 匹配數組大小
$maxDistance 范圍查詢,距離(基於LBS)
$mod 取模運算
$near 鄰域查詢,查詢附近的位置(基於LBS)
$exists 字段是否存在
$elemMatch 匹配內數組內的元素
$within 范圍查詢(基於LBS)
$box 范圍查詢,矩形范圍
$center 范圍查詢,圓形范圍
$centerSphere 范圍查詢,球形范圍
$slice 查詢字段集合中的元素(比如從第幾個之后,第N到第M個元素)

 

mongodb中的查詢語句

db.movies.find({'name':/未來/})
db.collection.find( { field: { $regex: 'acme.*corp', $options: 'i' } } );

官方舉例是通過 '/.../' 和$regex,這兩種都可以查詢到結果。

現在我想實現查詢標題關鍵字匹配到對應文章。

如下:

1.查詢title字段中包含某個字符串的集合:

 Article.find({"title":{$regex: /searchValue/,$options:'i'}}, (err, data) => { // {"title": /searchValue/} $options:'i' 表示忽略大小寫
        if(err) { console.log(err) return res.status(500).json({ result: 1, error_info: err.message }) } console.log(data) let length = data.length return res.status(200).json({ result: 0, count: length, searchArticle: data }) })
searchValue是前端傳過來的查詢關鍵詞。

這么寫好像沒有問題,跟官方實例一樣,但是查詢不到結果。

請注意,MongoDB的的模糊查詢是通過正則表達式實現的,對應mongodb中,可以直接使用 ‘/../’ 斜杠。
但是在nodejs中,必須要使用RegExp,來構建正則表達式對象。

router.post('/like_article_search', (req,res) => { let searchValue = req.body.value console.log(searchValue) var str=".*"+searchValue+".*$" var reg = new RegExp(str)
 Article.find({"title":{$regex:reg,$options: 'i'}}, (err, data) => { // $options:'i' 表示忽略大小寫
        if(err) { console.log(err) return res.status(500).json({ result: 1, error_info: err.message }) } console.log(data) let length = data.length return res.status(200).json({ result: 0, count: length, searchArticle: data }) }) })

 

這樣就可以匹配到查詢結果。

2.查詢以某個字母開頭的集合

mongodb語法:

db.UserInfo.find({userName :/^A/})

nodejs中寫法:

router.post('/like_article_search', (req,res) => { let searchValue = req.body.value console.log(searchValue) var str="^.*"+searchValue+".*$" var reg = new RegExp(str)
 Article.find({"title":{$regex:reg,$options: 'i'}}, (err, data) => { // {"title": /searchValue/} $options:'i' 表示忽略大小寫
        if(err) { console.log(err) return res.status(500).json({ result: 1, error_info: err.message }) } console.log(data) let length = data.length return res.status(200).json({ result: 0, count: length, searchArticle: data }) }) })

3.多條件模糊查詢

使用$or 語法。

多字段匹配,title、categroy、lable中包含查詢關鍵詞的都進行匹配

//模糊查詢
router.post('/like_article_search', (req,res) => { let searchValue = req.body.value // console.log(searchValue)
    // var str=".*"+searchValue+".*$"
    // var reg = new RegExp(str)
    var reg = new RegExp(searchValue); var _filter = { //多字段匹配  $or: [ {'title': {$regex: reg}}, {'categroy': {$regex: reg}}, {'lable': {$regex: reg}}, ] } Article.find(_filter, (err, data) => { // {"title": /searchValue/} $options:'i' 表示忽略大小寫
        if(err) { console.log(err) return res.status(500).json({ result: 1, error_info: err.message }) } console.log(data) let length = data.length return res.status(200).json({ result: 0, count: length, searchArticle: data }) }) })

這樣就可以實現。還可以通過某個字段對搜索結果進行降序或升序排列。

 4.全文搜索

 

上述正則表達是在效率上等同在該字段上進行全部掃描(除了在該字段上建立索引並使用^符號進行查找,該操作是會走索引的),當需要正則搜索的文檔到了一定的量級,模糊是查詢的效率還是會很低的。

 

全文搜索就是在需要搜索的字段上加上一個文本索引,注意:一個集合只能支持建立一個全文索引,但該索引可以包含多個字段做聯合索引。

Mongo的 $text 和 $search 相關的內容,這是Mongo內置的全文檢索,支持多種語言,支持詞語權重,在最新的Mongodb 3.2 enterprise版本中,已經增加了對中文文本的搜索。

數據庫結構

 

 

 創建索引

MongoDB提供文本索引以支持對字符串內容的文本搜索查詢。text索引可以包括其值為字符串或字符串元素數組的任何字段。 要執行文本搜索查詢,必須text在集合上有 索引。集合只能有一個 文本搜索索引,但該索引可以涵蓋多個字段。

 

articleSchema.index({title: 'text', content: 'text', categroy: 'text'})

查詢

使用$text查詢運算符對具有文本索引的集合執行文本搜索。 $text將使用空格和大多數標點符號作為分隔符來標記搜索字符串,並OR在搜索字符串中執行所有此類標記的邏輯

router.post('/like_article_search', (req,res) => {
    let searchValue = req.body.value
    
    //正則匹配 
    var reg = new RegExp(searchValue);
    
    Article.find({$text:{$search: reg}},{score: {$meta: "textScore"}})
    .sort({score:{$meta: "textScore"}}) 
    .exec((err, data) => { 
        if(err) {
            console.log(err)
            return res.status(500).json({
                result: 1,
                error_info: err.message
            })
        }
        console.log(data)
        let length = data.length
        return res.status(200).json({
            result: 0,
            count: length,
            searchArticle: data
        })
    })
})

默認情況下,mongodb將以未排序的順序返回結果。如果要按照相關性得分的順序進行排序,需要明確的指出對字段進行映射和排序:$meta: textScore

 推薦文章:https://blog.csdn.net/wukongbajieheti/article/details/99715743


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM