任何人都可以解釋的區別:搜索在蒙戈DB使用正則表達式的貓鼬與文本
db.collection.find({ $text: { $search: "dog cat" } })
和
Product.find({ "drug": { "$regex": "cols", "$options": "i" } })
我們什麼時候應該去哪個?
任何人都可以解釋的區別:搜索在蒙戈DB使用正則表達式的貓鼬與文本
db.collection.find({ $text: { $search: "dog cat" } })
和
Product.find({ "drug": { "$regex": "cols", "$options": "i" } })
我們什麼時候應該去哪個?
Provides regular expression capabilities for pattern matching strings in queries. MongoDB uses Perl compatible regular expressions (i.e. 「PCRE」) version 8.36 with UTF-8 support.
performs a text search on the content of the fields indexed with a text index .
對於數據
{ "_id" : 100, "sku" : "abc123", "description" : "Single line description." }
{ "_id" : 101, "sku" : "abc789", "description" : "First line\nSecond line" }
{ "_id" : 102, "sku" : "xyz456", "description" : "Many spaces before line" }
{ "_id" : 103, "sku" : "xyz789", "description" : "Multiple\nline description" }
要搜索字段sku
其是單〜應變G值,可以使用$regex
db.products.find({ sku: { $regex: /^ABC/i } })
而到搜索欄description
這是文本內容的值,可以使用$text
,當然,我們應該description
建立全文索引首先。
db.products.find({ $text: { $search: "coffee" } })
爲什麼不僅正則表達式?
regular expressions
有其先天限制,因爲他們沒有任何制止的功能,並在平凡的方式無法處理方便的搜索查詢,如「action -superhero」
。這裏是一個link來比較它們。
好吧,正則表達式和文本搜索($ text)都可以幫助您非常有效地在文本中進行搜索。兩者都有各自的優點和缺點,但有兩個明顯的區別
regex
正則表達式不帶指數的優勢,除非你是在字符串的開頭使用^
運營商搜索。
正則表達式允許您搜索部分文本。因此。*和其他許多模式。
正則表達式不支持停止詞或噪音詞。
$text
MongoDB中的文本索引真快,應該是首選。但是,MongoDB不實現全功能文本索引。一個主要缺點是,它不支持部分匹配。例如如果你正在尋找貓,它會搜索只貓和貓,但不是山貓或caterpiller。
Bottom line is if you are looking to implement feature like RDBMS
like
operator, '$text' will not help you (at least in current implementations of MongoDB, but in future it may change).
嗨,我試圖使用這樣的東西: db.products.find({$ text:{$ search:{$ regex:「test」,$ options:「i」}}},{score: {$ meta:「textScore」}})。sort({score:{$ meta:「textScore」}}) 它引發錯誤 錯誤:錯誤:{ 「$ err」:「Can not canonicalize查詢:BadValue $搜索需要一個字符串「, 」code「:17287 } 有沒有什麼辦法可以同時使用?我是mongo的新手。請幫忙 –
感謝您的解釋。但我還有一個疑問。我使用$文本並使用$分數投影根據相關性對結果進行排序。但我需要像使用正則表達式一樣使用匹配的部分字符串的功能。有什麼方法可以同時使用它們嗎? –
你可以在帶有文本索引的字段上使用正則表達式。然而,如果你正在尋找兩全其美的方法,遺憾的是它尚未得到支持。讓我們希望好。 – Saleem