MongoDB 7.0.5+を実行中クラスターでは、MongoDB Search を使用して、参照点の後、または 前 で $search クエリ結果を連続して取得します。$search searchAfter または searchBefore オプションを使用して結果を順番に走査し、アプリケーション内で「次のページ」と「前のページ」関数を構築します。
使用法
ページ分割された結果を検索するには、次の手順を実行します。
クエリを実行したいフィールドにインデックスを作成します。
参照点を返す
$searchクエリを実行します。 詳細については、「 参照点の取得 」を参照してください。後続の
$searchクエリで参照点を使用して、結果内に次または前のドキュメント セットを検索します。To learn more about retrieving results to build a "Next Page" function, see Search After a Specific Point of Reference.
「前のページ」関数を構築するための結果の検索の詳細については、「特定の参照点の前の検索 」を参照してください。
To jump to a page in your results, combine
$skipand$limitwith$searchsearchAfterorsearchBeforeoptions. For example, to jump to results from Page 3 to Page 5, with 10 results per page, do the following:ページ3の最後の結果の参照点を持つ
searchAfterを使用して結果を取得します(結果30 )。ページ5の結果を返します(結果41 - 50 )。
Here, using
$skipwith thesearchAfteroption optimizes the query to skip only 1 page of results (10 documents). By comparison, if you use$skipwithout the$searchsearchAfteroption, the query skips 4 pages of results (40 documents). To learn more, see Jump from Page 2 to Page 5 Using searchAfter and $skip.
Considerations
複数のドキュメントが同じ値を持つフィールドでソートすると、同点となります。Mongo DBは、結び付けられたクエリ結果の順序を保証しません。
searchAfterとsearchBeforeを使用すると、重複や不整合が発生する可能性があります。関連性スコアの同点を減らすために、次の原則を応用します。関連性スコアの同点を防ぐために、クエリを一意のフィールドで並べ替えます。例については、 「スコアと一意のフィールドによる並べ替え」を参照してください。
非 一意のフィールドで主にソートする場合は、タイブレークとして機能するために一意のフィールドに セカンダリ ソート句を追加 します。
クエリ間でドキュメントを更新または削除すると、結果順序の不整合が発生する可能性があります。決定的な検索する動作をサポートするには、次の原則を適用します。
クエリ結果を
_idなどの不変フィールドで並べ替えます。MongoDB Search は、最初のクエリと後続のクエリの間にコレクションに加えた更新を反映します。変更可能なフィールド(例:updated_time)でソートし、最初のクエリと2番目のクエリの間でコレクションを更新すると、MongoDB Search では同じドキュメントの順序が異なる場合があります。専用の検索ノードを配置し、
searchScore、結果をソートする場合は、以下を考慮してください。By default, MongoDB Search scores documents using the
bm25similarity algorithm, which calculates term frequency in relation to the entire corpus of documents on the MongoDB Search node. Because each MongoDB Search node replicates from the changestream independently, this corpus might vary across MongoDB Search nodes. As a result, the same query can return differentbm25scores when routed to different MongoDB Search nodes. Subsequent queries are more likely to be routed to different MongoDB Search nodes if your deployment uses dedicated MongoDB Search nodes, or your read preference is set tosecondaryornearest.以降のクエリでコンシステントなスコアが得られるようにするには、フィールドを MongoDB Search のstringまたはautocomplete型としてインデックス化するときに
similarity.typeプロパティをstableTflあるいはbooleanに設定します。これにより、text、phrase、queryString、autocomplete 演算子は、インデックス付きフィールドのクエリの関連性スコアを計算するためにstableTflまたはboolean類似度アルゴリズムを使用するようになります。これらのアルゴリズムは、すべての MongoDB Search ノードで一貫してスコアを計算します。詳細については、「スコアの詳細」を参照してください。
To count search results during pagination, use the count option in your initial
$searchquery or in a separate$searchMetaquery. This method is more efficient than using the$countstage after your$searchstage.count オプションは検索条件に一致するドキュメントの合計数を返すため、ページ分割された結果を生成している場合は、後のクエリで
countオプションを使用する必要がありません。$searchメインの クエリとは別にカウントするには、$searchMetaオプションを指定したcountステージを使用します。検索結果をカウントすると、パフォーマンスに影響する可能性があります。count オプションは必要な場合にのみ使用してください。例、最初のページの検索結果を取得する場合などです。
参照点の取得
To retrieve query results at a certain point, you must provide the point of reference in your $search query. You can retrieve the reference point by using the $meta keyword searchSequenceToken in the $project stage after your $search stage.
構文
1 [{ 2 "$search": { 3 "index": "<index-name>", 4 "<operator-name>"|"<collector-name>": { 5 <operator-specification>|<collector-specification> 6 }, 7 "sort": { 8 "score": { 9 "$meta": "searchScore" 10 } 11 }, 12 ... 13 }, 14 { 15 "$project": { 16 "paginationToken" : { "$meta" : "searchSequenceToken" } 17 }, 18 ... 19 }]
出力
searchSequenceTokenは、結果内の各ドキュメントに対して base 64でエンコードされたトークンを生成します。 トークンの長さは、クエリのソートオプションで指定されたフィールドの数に応じて増加します。 トークンはデータベースのスナップショットには関連付けられていません。
クエリで sort オプションを指定しない限り、結果内のドキュメントはデフォルトの順序でソートされます。結果の並べ替えの詳細については、「 MongoDB検索結果の並べ替え 」を参照してください。
特定の参照点の後の検索
参照点を検索するには、 searchSequenceTokenによって生成されたトークンでsearchAfterオプションを使用して、 $searchクエリで参照点を指定する必要があります。 searchSequenceTokenによって生成されたトークンは、 searchSequenceTokenがトークンを生成した$searchクエリを再実行した場合にのみ使用できます。 トークンを使用する後続の$searchクエリのセマンティクス(検索フィールドと値)は、 searchSequenceTokenがトークンを生成したクエリと同一である必要があります。
You can use the searchAfter option to build a "Next Page" function in your application. For a demonstration of this, see the example on this page.
searchAfter 構文
1 [{ 2 "$search": { 3 "index": "<index-name>", 4 "<operator-name>"|"<collector-name>": { 5 <operator-specification>|<collector-specification> 6 }, 7 "searchAfter": "<base64-encoded-token>", 8 "sort": { 9 "score": { 10 "$meta": "searchScore" 11 } 12 }, 13 ... 14 }, 15 "$project": { 16 "paginationToken" : { "$meta" : "searchSequenceToken" } 17 }, 18 ... 19 }]
出力
MongoDB Search returns the documents in the results after the specified token. MongoDB Search returns the generated tokens for the documents in the results because you specified the searchSequenceToken in the $project stage after the $search stage (as shown in line 11). These tokens can be used as a reference point for another query with the same semantics.
クエリで sort オプションを指定しない限り、結果内のドキュメントはデフォルトの順序でソートされます。結果の並べ替えの詳細については、「 MongoDB検索結果の並べ替え 」を参照してください。
特定の参照点の前の検索
参照点の前を検索するには、 searchSequenceTokenによって生成されたトークンでsearchBeforeオプションを使用して、 $searchクエリで参照点を指定する必要があります。 searchSequenceTokenによって生成されたトークンは、 searchSequenceTokenがトークンを生成した$searchクエリを再実行した場合にのみ使用できます。 トークンを使用する後続の$searchクエリのセマンティクス(検索フィールドと値)は、 searchSequenceTokenがトークンを生成したクエリと同一である必要があります。
searchBefore オプションを使用して、アプリケーションで「前のページ」機能を構築できます。これを行うには、以下を組み合わせます。
これを証明するために、このページのsearchBeforeクエリ例を参照してください。
searchBefore 構文
1 [{ 2 "$search": { 3 "index": "<index-name>", 4 "<operator-name>"|"<collector-name>": { 5 <operator-specification>|<collector-specification> 6 }, 7 "searchBefore": "<base64-encoded-token>", 8 "sort": { 9 "score": { 10 "$meta": "searchScore" 11 } 12 }, 13 ... 14 }, 15 "$project": { 16 "paginationToken" : { "$meta" : "searchSequenceToken" } 17 }, 18 ... 19 }]
searchBefore 出力
MongoDB Search returns documents in the results preceding the specified token in reverse order. MongoDB Search also returns the generated tokens for the documents in the results because you specified the searchSequenceToken in the $project stage after the $search stage (as shown in line 11). These tokens can be used as a reference point for another query with the same semantics.
例
The following examples use the db.collection.aggregate() method to run $search queries against the sample_mflix database. The first example query demonstrates how to retrieve a point of reference, which you use in the subsequent example queries to retrieve additional results for pages after or before the reference point.
To run these example queries in mongosh:
Load the sample_mflix.movies collection
動的マッピングを使用して
pagination-tutorialインデックスを作成します。インデックスの作成方法については、「MongoDB Search インデックスの管理」を参照してください。Connect to your cluster using
mongoshand switch to thesample_mflixdatabase
注意
デフォルトでは 、 MongoDB Search は結果内のドキュメントを、ドキュメントの関連性スコアでソートします。結果内の複数のドキュメントのスコアが同じである場合、 MongoDB Search は任意の順序付けられた結果を返します。特定の順序でドキュメントを返すには、クエリで一意のフィールドreleased を指定して結果をソートします。