To perform text search, MongoDB uses a text index and the $text
operator.
插入用例數(shù)據(jù)
> db.stores.insert(
... [
... { _id: 1, name: "Java Hut", description: "Coffee and cakes" },
... { _id: 2, name: "Burger Buns", description: "Gourmet hamburgers" },
... { _id: 3, name: "Coffee Shop", description: "Just coffee" },
... { _id: 4, name: "Clothes Clothes Clothes", description: "Discount clothing" },
... { _id: 5, name: "Java Shopping", description: "Indonesian goods" }
... ]
... )
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 5,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
文字索引
MongoDB provides text indexes to support text search queries on string content. text
indexes can include any field whose value is a string or an array of string elements.
To perform text search queries, you must have a text
index on your collection. A collection can only have one text search index, but that index can cover multiple fields.
For example you can run the following in a mongo
shell to allow text search over the name
and description
fields:
> db.stores.createIndex( { name: "text", description: "text" } )
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
>
$text運算符
使用$text
查詢運算符對具有文本索引的集合執(zhí)行文本搜索产阱。
$text
將使用空格和大多數(shù)標點符號作為分隔符來OR
標記搜索字符串向叉,并對搜索字符串中的所有此類標記執(zhí)行邏輯運算。
例如,您可以使用以下查詢從列表“ coffee”,“ shop”和“ java”中查找包含任何術語的所有商店:
db.stores.find( { $text: { $search: "java coffee shop" } } )
精確匹配
您還可以通過將它們括在雙引號中來搜索確切的短語
以下將查找包含“coffee shop”的所有文檔:
db.stores.find( { $text: { $search: "\"coffee shop\"" } } )
排除單詞
要排除一個單詞,可以在前面加上一個“ -”字符。例如衡招,要查找所有包含“ java”或“ shop”但不包含“ coffee”的商店,請使用以下命令:
> db.stores.find( { $text: { $search: "java shop -coffee" } } )
{ "_id" : 5, "name" : "Java Shopping", "description" : "Indonesian goods" }
排序
默認情況下每强,MongoDB將以未排序的順序返回結果始腾。但是,文本搜索查詢將為每個文檔計算相關性分數(shù)空执,以指定文檔與查詢的匹配程度浪箭。
要按相關性得分的順序對結果進行排序,必須顯式投影該字段并對其進行排序:$meta
textScore
field
> db.stores.find(
... { $text: { $search: "java coffee shop" } },
... { score: { $meta: "textScore" } }
... ).sort( { score: { $meta: "textScore" } } )
{ "_id" : 3, "name" : "Coffee Shop", "description" : "Just coffee", "score" : 2.25 }
{ "_id" : 1, "name" : "Java Hut", "description" : "Coffee and cakes", "score" : 1.5 }
{ "_id" : 5, "name" : "Java Shopping", "description" : "Indonesian goods", "score" : 1.5 }
>