使用文字搜尋

使用 Cloud Firestore 中的文字搜尋功能,在集合中搜尋特定字串。

事前準備

開始使用 Text Search 前,請先完成下列步驟:

  1. 確認您有權存取現有的 MongoDB 相容作業資料庫,或建立資料庫並連線。

  2. 確認您有文字索引,或建立文字索引。

Text Search 會在篩選器中使用 $text 運算子。在 $search 引數中指定查詢字串。

執行下列指令,執行一般文字搜尋:

  # Find search
  db.cities.find({ $text: { $search: "french bread" } })

  # Aggregation search
  db.cities.aggregate([
    { $match: { $text: { $search: "french bread" } } }
  ]);

如果索引已分區,您可以在搜尋中加入「and」等式篩選器,並在其中加入分區,依據分區篩選。舉例來說,如果您有 city 分區,可以按照下列方式篩選 Text Search:

db.myCollection.find( { $and: [
  { $text: { $search: "french bread" } },
  { "city": "Paris" }
] } )

您也可以根據分區篩選匯總。例如:

db.myCollection.aggregate([
 { $match: { $text: { $search: "french bread" } } },
 { "city": "Paris" }
] );

分區值必須是字串。您的分區篩選器必須使用「and」與 Text Search 連結。

設定文字搜尋語言

您可以使用 $language 引數設定文字搜尋語言。例如:

  db.cities.find({ $text: { $search: "french bread", $language: "en"} })

如未設定語言,搜尋會使用文字索引的語言。

搜尋完全相符的字詞

如要搜尋完全相符的字詞,請將字詞設為以雙引號括住的一連串字詞。例如:

  # Find search
  db.cities.find({ $text: { $search: "\"best french bread\"" } })

  # Aggregation search
  db.cities.aggregate([
    { $match: { $text: { $search: "\"best french bread\"" } } },
  ]);

搜尋字詞組合

如要讓 Text Search 更精確,請指定一連串字詞。舉例來說,下列搜尋會傳回符合 best AND french AND ("bread" OR "is") 組合的文件:

  # Find search
  db.cities.find({ $text: { $search: "\"best\" \"french\" bread is" } })

  # Aggregation search
  db.cities.aggregate([
    { $match: { $text: { $search: "\"best\" \"french\" bread is" } } },
  ]);

排除字詞

如要從文字搜尋中排除某個字詞,請在該字詞前加上連字號 (-):

  # Find search
  db.cities.find({ $text: { $search: "best bread -french"} })

  # Aggregation search
  db.cities.aggregate([
    { $match: { $text: { $search: "best bread -french" } } },
  ]);

計算關聯性分數

使用 {$meta: "textScore"} 運算式,計算 Text Search 比對出的文件關聯性分數。如要依分數遞減排序結果,請在排序運算式中使用 $meta。請參考下列範例,其中 SCORE_FIELD 是用來儲存分數值的欄位名稱:

  # Find search
  db.cities
    .find({ $text: { $search: "best french bread" } })
    .sort({ SCORE_FIELD: { $meta: "textScore" } })

  # Aggregation search
  db.cities.aggregate([
    { $match: { $text: { $search: "best french bread" } } },
    { $sort: { "SCORE_FIELD": { $meta: "textScore"} } },
  ]);

您也可以在投影運算式中使用文字分數。例如:

  # Find search
  db.cities
    .find({ $text: { $search: "best french bread" } })
    .project({ score: { $meta: "textScore" } })

  # Aggregation search
  db.cities.aggregate([
    { $match: { $text: { $search: "best french bread" } } },
    { $project: { "scoreField": { $meta: "textScore"} } },
  ]);

為提高文字搜尋結果的關聯性,$text 運算子會根據指定語言擴充搜尋字串,納入符合內容感知同義詞、詞幹形式、拼寫校正字詞、變音符號變化等條件的結果。

限制

  • $near 運算子和 $text 運算子無法在同一個文字搜尋中使用。
  • 每次 find 或 aggregation 搜尋只能使用一個 $text 運算子。
  • 在匯總中,含有 $text 的 $match 階段必須是第一個管道階段。
  • $text 只能在 $and 和 $or 中建立巢狀結構。
  • 如果 $text 位於 $or 內,非搜尋分離式可能會使用現有的排序索引來最佳化搜尋。如果其他析取式未建立索引,搜尋就會依賴集合掃描。
  • $text 無法與提示搭配使用。
  • 使用文字搜尋的查詢無法依 $natural 排序。