ドキュメントおよびコレクションを変換するために、ビュー上にMongoDB Search インデックスを作成できます。これにより、コレクションの一部のみをインデックス化したり、互換性のないデータ型やデータモデルをサポートしたりすることが可能になります。
以下の例では、sample_mflix および sample_airbnb のサンプルデータベースを使用します。
注意
曖昧さ回避
このページでは標準ビューについて説明します。オンデマンドのマテリアライズドビューの詳細については、「オンデマンドのマテリアライズドビュー」を参照してください。
ビュー タイプの違いについては「オンデマンドのマテリアライズドビューとの比較」を参照してください。
要件
MongoDB 8.0 以降を使用する必要があります。
MongoDB v8.0以降の場合:
Atlas UIまたは Atlas 管理APIを使用して、ビューにMongoDB Search インデックスを作成します。
ソースコレクションに対してMongoDB Search クエリを実行します。ビュー で作成されたMongoDB Searchインデックスを参照します。これらのクエリでは、 ソースコレクションに現れる元のドキュメントが返されます。
MongoDB v8.1 以降の場合、さらに以下のことが可能です。
ビューでMongoDB Search インデックスを作成および管理するには、
mongoshメソッドとドライバー$listSearchIndexesメソッド、db.collection.createSearchIndex()db.collection.dropSearchIndex()、 、db.collection.updateSearchIndex()、 を使用します。ビューに対してMongoDB Search クエリを実行します。
制限
インデックス名は、ソース コレクションとそのすべてのビューにわたって一意である必要があります。
MongoDB Searchでは、 $$USER_ROLES システム変数や
$rand集計演算子など、動的な結果を生成する演算子を使用した ビュー定義はサポートされていません。MongoDB Search クエリでは、 ソースコレクションに現れる元のドキュメントが返されます。
- 変換されたドキュメントを検索するには、
storedSourceオプションを使用してください。
必要な権限
ビューを作成するには、createCollection の権限を持つロールが必要です。
例
次の例では、ビューの作成方法、ドキュメントの部分インデックス化方法、およびインデックスに対するクエリの実行方法を示します。これらの例では、ソースコレクションまたはビューに対して .aggregate コマンドを実行し、インデックスをクエリします。MongoDB Search は、MongoDB v8.1 以降でのみビューに対する直接のクエリをサポートしています。
ドキュメントをフィルターして、コレクションに部分的にインデックスを付けることができます。次の例では、sample_mflix.movies コレクションにビューを作成し、2000 年 1 月 1 日以降に公開された映画のみを検索できるようにします。
mongosh を使用してクラスターに接続します。
詳細については、 mongosh経由でクラスターに接続する を参照してください。
Atlas で、プロジェクトの [Clusters] ページに移動します。
まだ表示されていない場合は、希望するプロジェクトを含む組織を選択しますナビゲーション バーのOrganizationsメニュー
まだ表示されていない場合は、ナビゲーション バーのProjectsメニューから目的のプロジェクトを選択します。
サイドバーで、 Database見出しの下のClustersをクリックします。
[ Clusters (クラスター) ] ページが表示されます。
In Atlas, go to the Search & Vector Search page for your cluster.
MongoDB 検索するページには、Search & Vector Search オプションまたは Data Explorer から移動できます。
まだ表示されていない場合は、プロジェクトを含む組織をナビゲーション バーの Organizations メニューで選択します。
まだ表示されていない場合は、ナビゲーション バーの Projects メニューからプロジェクトを選択します。
まだ表示されていない場合は、プロジェクトを含む組織をナビゲーション バーの Organizations メニューで選択します。
まだ表示されていない場合は、ナビゲーション バーの Projects メニューからプロジェクトを選択します。
サイドバーで、 Database見出しの下のData Explorerをクリックします。
データベースを展開し、コレクションを選択します。
コレクションのIndexesタブをクリックします。
バナー内の Search and Vector Search リンクをクリックします。
検索とベクトル検索ページが表示されます。
インデックスの設定を開始します。
ページで次の選択を行い、Next をクリックしてください。
Search Type | MongoDB Search のインデックスタイプを選択します。 |
Index Name and Data Source | 以下の情報を指定してください。
|
Configuration Method | ガイドを利用する場合は、Visual Editor を選択します。 |
重要: |fts|インデックスの名前はデフォルトで ``auto embedded_index`` です。複数のインデックスを作成する場合は、インデックス間で一貫した記述的な命名規則を維持することをお勧めします。
releasedAfter2000Index 部分インデックスをクエリします。
[ { "$search": { "index": "releasedAfter2000Index", "text": { "path": "title", "query": "foo" }, "sort": { "released": 1 } } } ]
SCORE: 3.120296001434326 _id: “573a13d2f29313caabd929f8” awards: Object cast: Array (4) countries: Array (1) directors: Array (1) fullplot: "Rising from the ashes of Nirvana, the Foo Fighters became a Grammy-win…" genres: Array (2) imdb: Object languages: Array (1) lastupdated: "2015-08-19 00:00:25.937000000" num_mflix_comments: 0 plot: "Rising from the ashes of Nirvana, the Foo Fighters became a Grammy-win…" poster: "https://m.media-amazon.com/images/M/MV5BMzE4OTczMTgxM15BMl5BanBnXkFtZT…" released: 2011-04-05T00:00:00.000+00:00 runtime: 150 title: "Foo Fighters: Back and Forth" tomatoes: Object type: "movie" year: 2011
MongoDB 配置にmongoshを使用して接続します。
詳細については、 mongosh経由でクラスターに接続する を参照してください。
releasedAfter2000Index 部分インデックスをクエリします。
注意
次の例では、listingsSearchablePrice インデックスに対して .aggregate コマンドを実行し、listings_SearchablePrice という名前のビューを検索します。クラスターが MongoDB v8.0 を実行している場合、ビューのインデックスを使用して、ソースコレクション(例: listingsAndReviews)をクエリする必要があります。ビューを直接クエリするために、MongoDB v8.1 以降にアップグレードしてください。
db.movies_ReleasedAfter2000.aggregate([ { $search: { index: "releasedAfter2000Index", text: { path: "title", query: "foo" }, sort: { released: 1 } } } ])
[ { _id: ObjectId('573a13d2f29313caabd929f8'), plot: "Rising from the ashes of Nirvana, the Foo Fighters became a Grammy-winning sensation on their own. Sixteen years of the band's history comes to life in this documentary, from their demo ...", genres: [ 'Documentary', 'Music' ], runtime: 150, cast: [ 'Shawn Cloninger', 'William Goldsmith', 'Jessy Greene', 'Dave Grohl' ], num_mflix_comments: 0, poster: 'https://m.media-amazon.com/images/M/MV5BMzE4OTczMTgxM15BMl5BanBnXkFtZTcwNTU1NjQxOA@@._V1_SY1000_SX677_AL_.jpg', title: 'Foo Fighters: Back and Forth', fullplot: `Rising from the ashes of Nirvana, the Foo Fighters became a Grammy-winning sensation on their own. Sixteen years of the band's history comes to life in this documentary, from their demo tapes through the creation of their 2011 album, "Wasting Light."`, languages: [ 'English' ], released: ISODate('2011-04-05T00:00:00.000Z'), directors: [ 'James Moll' ], awards: { wins: 1, nominations: 1, text: '1 win & 1 nomination.' }, lastupdated: '2015-08-19 00:00:25.937000000', year: 2011, imdb: { rating: 8.4, votes: 3745, id: 1853563 }, countries: [ 'USA' ], type: 'movie', tomatoes: { viewer: { rating: 4.4, numReviews: 857, meter: 96 }, dvd: ISODate('2011-08-08T00:00:00.000Z'), website: 'http://us.foofightersfilm.com/', production: 'Cinedigm Digital Cinema', lastUpdated: ISODate('2015-09-12T18:42:01.000Z') } } ]
次の例では、新しい totalPriceフィールド(price フィールドと cleaningFee フィールドの合計)に基づいて、sample_airbnb.listingsAndReviewsコレクションでアキュムレーションを検索できます。また、 MongoDB Search は Decimal128 型をサポートしていないため、値を Double に変換します。
mongosh を使用してクラスターに接続します。
詳細については、 mongosh経由でクラスターに接続する を参照してください。
Atlas で、プロジェクトの [Clusters] ページに移動します。
まだ表示されていない場合は、希望するプロジェクトを含む組織を選択しますナビゲーション バーのOrganizationsメニュー
まだ表示されていない場合は、ナビゲーション バーのProjectsメニューから目的のプロジェクトを選択します。
サイドバーで、 Database見出しの下のClustersをクリックします。
[ Clusters (クラスター) ] ページが表示されます。
In Atlas, go to the Search & Vector Search page for your cluster.
MongoDB 検索するページには、Search & Vector Search オプションまたは Data Explorer から移動できます。
まだ表示されていない場合は、プロジェクトを含む組織をナビゲーション バーの Organizations メニューで選択します。
まだ表示されていない場合は、ナビゲーション バーの Projects メニューからプロジェクトを選択します。
まだ表示されていない場合は、プロジェクトを含む組織をナビゲーション バーの Organizations メニューで選択します。
まだ表示されていない場合は、ナビゲーション バーの Projects メニューからプロジェクトを選択します。
サイドバーで、 Database見出しの下のData Explorerをクリックします。
データベースを展開し、コレクションを選択します。
コレクションのIndexesタブをクリックします。
バナー内の Search and Vector Search リンクをクリックします。
検索とベクトル検索ページが表示されます。
Create Search Index をクリックしてインデックス構成を開始します。
ページで次の選択を行い、Next をクリックしてください。
Search Type | MongoDB Search のインデックスタイプを選択します。 |
Index Name and Data Source | 以下の情報を指定してください。
|
Configuration Method | 生のインデックス定義を編集するには JSON Editor を選択します。 |
totalPriceIndex インデックスにクエリを実行します。
[ { "$search": { "index": "totalPriceIndex", "range": { "path": "totalPrice", "lte": 300 }, "returnStoredSource": true } } ]
SCORE: 1 _id: "10006546" totalPrice: 115 SCORE: 1 _id: "1001265" totalPrice: 215 SCORE: 1 _id: "10021707" totalPrice: 40 SCORE: 1 _id: "1003530" totalPrice: 270 SCORE: 1 _id: "10038496" totalPrice: 269 SCORE: 1 _id: "10051164" totalPrice: 250 SCORE: 1 _id: "10057447" totalPrice: 50 SCORE: 1 _id: "10057826" totalPrice: 205 SCORE: 1 _id: "10059244" totalPrice: 43 SCORE: 1 _id: "10066928" totalPrice: 140
Connect to your MongoDB deployment using mongosh.
詳細については、 mongosh経由でクラスターに接続する を参照してください。
totalPriceIndex インデックスにクエリを実行します。
注意
次の例では、listingsSearchablePrice インデックスに対して .aggregate コマンドを実行し、listings_SearchablePrice という名前のビューを検索します。クラスターが MongoDB v8.0 を実行している場合、ビューのインデックスを使用して、ソースコレクション(例: listingsAndReviews)をクエリする必要があります。ビューを直接クエリするために、MongoDB v8.1 以降にアップグレードしてください。
db.listingsAndReviews_totalPrice.aggregate([ { $search: { index: "totalPriceIndex", range: { path: "totalPrice", lte: 300 }, returnStoredSource: true } } ])
[ { _id: '10006546', totalPrice: 115 }, { _id: '1001265', totalPrice: 215 }, { _id: '10021707', totalPrice: 40 }, { _id: '1003530', totalPrice: 270 }, { _id: '10038496', totalPrice: 269 }, { _id: '10051164', totalPrice: 250 }, { _id: '10057447', totalPrice: 50 }, { _id: '10057826', totalPrice: 205 }, { _id: '10059244', totalPrice: 43 }, { _id: '10066928', totalPrice: 140 }, { _id: '10082422', totalPrice: 60 }, { _id: '10083468', totalPrice: 40 }, { _id: '10084023', totalPrice: 231 }, { _id: '10091713', totalPrice: 231 }, { _id: '10092679', totalPrice: 58 }, { _id: '10096773', totalPrice: 205 }, { _id: '10112159', totalPrice: 90 }, { _id: '10117617', totalPrice: 55 }, { _id: '10120414', totalPrice: 150 }, { _id: '10133554', totalPrice: 121 } ]
命名パターンに一致するフィールドをインデックス化するには、インデックス化するフィールドがサブドキュメントにネストされるよう、ビューを使用してデータを変換します。これによりサブドキュメントパスに動的マッピングを使用できるようになり、インデックスの定義を変更することなく接尾辞が _type のすべてのフィールドを自動的に検索できます。
次の listings_SearchableTypes という名前の View は、sample_airbnb.listingsAndReviews コレクションの _type で終わるフィールド名のみと一致します。具体的には、$set ステージでは、フィールド名に _type という用語が付いたフィルタリングされたフィールドを含む、searchable_types という名前の新しいフィールド名が付きます。$arrayToObject には、フィルター入力(ドキュメント全体)と条件(_type の正規表現一致)が含まれています。
mongosh を使用してクラスターに接続します。
詳細については、 mongosh経由でクラスターに接続する を参照してください。
listings_SearchableTypes という名前のビューを作成します。
1 db.createView( 2 "listings_SearchableTypes", 3 "listingsAndReviews", 4 [ 5 { 6 "$set": { 7 "searchable_types": { 8 "$arrayToObject": { 9 "$filter": { 10 "input": { "$objectToArray": "$$ROOT" }, 11 "cond": { 12 "$regexMatch": { 13 "input": "$$this.k", 14 "regex": /_type$/ 15 } 16 } 17 } 18 } 19 } 20 } 21 } 22 ] 23 )
Atlas で、プロジェクトの [Clusters] ページに移動します。
まだ表示されていない場合は、希望するプロジェクトを含む組織を選択しますナビゲーション バーのOrganizationsメニュー
まだ表示されていない場合は、ナビゲーション バーのProjectsメニューから目的のプロジェクトを選択します。
サイドバーで、 Database見出しの下のClustersをクリックします。
[ Clusters (クラスター) ] ページが表示されます。
In Atlas, go to the Search & Vector Search page for your cluster.
MongoDB 検索するページには、Search & Vector Search オプションまたは Data Explorer から移動できます。
まだ表示されていない場合は、プロジェクトを含む組織をナビゲーション バーの Organizations メニューで選択します。
まだ表示されていない場合は、ナビゲーション バーの Projects メニューからプロジェクトを選択します。
まだ表示されていない場合は、プロジェクトを含む組織をナビゲーション バーの Organizations メニューで選択します。
まだ表示されていない場合は、ナビゲーション バーの Projects メニューからプロジェクトを選択します。
サイドバーで、 Database見出しの下のData Explorerをクリックします。
データベースを展開し、コレクションを選択します。
コレクションのIndexesタブをクリックします。
バナー内の Search and Vector Search リンクをクリックします。
検索とベクトル検索ページが表示されます。
Create Search Index をクリックしてインデックス構成を開始します。
ページで次の選択を行い、Next をクリックしてください。
Search Type | MongoDB Search のインデックスタイプを選択します。 |
Index Name and Data Source | 以下の情報を指定してください。
|
Configuration Method | 生のインデックス定義を編集するには JSON Editor を選択します。 |
インデックスの定義を編集します。
以下のインデックス定義をコピーして貼り付け、 UI のデフォルトのインデックス定義を置き換えます。
{ "analyzer": "lucene.standard", "searchAnalyzer": "lucene.standard", "mappings": { "dynamic": false, "fields": { "searchable_types": [ { "dynamic": { "typeSet": "tokenTypeSet" }, "type": "document" } ] } }, "typeSets": [ { "name": "tokenTypeSet", "types": [ { "type": "token" } ] } ] }
ビューにクエリを実行します。
次のクエリでは、private room で house の listings_SearchableTypes という名前のビューを検索します。このクエリを実行するには、クエリをコピーして貼り付け、Search をクリックします。
[ { "$search": { "index": "listingsSearchableTypes", "compound": { "should": [ { "text": { "path": "searchable_types.property_type", "query": "House" } }, { "text": { "path": "searchable_types.room_type", "query": "Private room" } } ] } } } ]
SCORE: 2.0530142784118652 _id: "10051164" name: "Catete's Colonial Big Hause Room B", searchable_types: Object property_type: 'House', room_type: 'Private room', bed_type: 'Real Bed' SCORE: 2.0530142784118652 _id: "1016739" name: 'Private Room (2) in Guest House at Coogee Beach', searchable_types: Object property_type: 'House', room_type: 'Private room', bed_type: 'Real Bed' SCORE: 2.0530142784118652 _id: "10324377" name: 'Suíte em local tranquilo e seguro', searchable_types: Object property_type: 'House', room_type: 'Private room', bed_type: 'Real Bed' SCORE: 2.0530142784118652 _id: "1073607" name: 'Bright Inner West Terrace Value+', searchable_types: Object property_type: 'House', room_type: 'Private room', bed_type: 'Real Bed' SCORE: 2.0530142784118652 _id: "1077686" name: 'BALAT', searchable_types: Object property_type: 'House', room_type: 'Private room', bed_type: 'Real Bed' SCORE: 2.0530142784118652 _id: "10990260" name: 'The Executive Posh Room', searchable_types: Object property_type: 'House', room_type: 'Private room', bed_type: 'Real Bed' SCORE: 2.0530142784118652 _id: "10992286" name: 'Holoholo Inn: Rain Forest (Priv-2)', searchable_types: Object property_type: 'House', room_type: 'Private room', bed_type: 'Real Bed' SCORE: 2.0530142784118652 _id: "11396243" name: 'Beautiful Ensuite Room -Easy access to city', searchable_types: Object property_type: 'House', room_type: 'Private room', bed_type: 'Real Bed' SCORE: 2.0530142784118652 _id: "1145567" name: 'ROOM + ENSUITE INNER CITY MOD HOUSE', searchable_types: Object property_type: 'House', room_type: 'Private room', bed_type: 'Real Bed' SCORE: 2.0530142784118652 _id: "11464859" name: 'The Sassy Lilac Megan Love Room', searchable_types: Object property_type: 'House', room_type: 'Private room', bed_type: 'Real Bed'
MongoDB 配置にmongoshを使用して接続します。
詳細については、 mongosh経由でクラスターに接続する を参照してください。
ビューでMongoDB Searchインデックスを作成します。
次の listingsSearchableTypes という名前の View のインデックス定義では、typeSet を構成し、searchable_types ドキュメントのすべてのフィールドを string 型として自動的にインデックス化します。このパターンに一致する新規フィールドを追加すると、MongoDB Search はこれらのフィールドも自動的にインデックス化します。
db.listings_SearchableTypes.createSearchIndex( "listingsSearchableTypes", { "analyzer": "lucene.standard", "searchAnalyzer": "lucene.standard", "mappings": { "dynamic": false, "fields": { "searchable_types": [ { "type": "document", "dynamic": { "typeSet": "tokenTypeSet" } } ] } }, "typeSets": [ { "name": "tokenTypeSet", "types": [ { "type": "token" } ] } ] } )
totalPriceIndex インデックスにクエリを実行します。
次のクエリでは、private room で house の listings_SearchableTypes という名前のビューを検索します。
db.listings_SearchableTypes.aggregate([ { "$search": { "index": "listingsSearchableTypes", "compound": { "should": [ { "equals": { "path": "searchable_types.property_type", "value": "House" } }, { "equals": { "path": "searchable_types.room_type", "value": "Private room" } } ] } } }, { "$limit": 10 }, { "$project": { "_id": 0, "searchable_types": 1, "name": 1 } } ])
[ { name: "Catete's Colonial Big Hause Room B", searchable_types: { property_type: 'House', room_type: 'Private room', bed_type: 'Real Bed' } }, { name: 'Private Room (2) in Guest House at Coogee Beach', searchable_types: { property_type: 'House', room_type: 'Private room', bed_type: 'Real Bed' } }, { name: 'Suíte em local tranquilo e seguro', searchable_types: { property_type: 'House', room_type: 'Private room', bed_type: 'Real Bed' } }, { name: 'Bright Inner West Terrace Value+', searchable_types: { property_type: 'House', room_type: 'Private room', bed_type: 'Real Bed' } }, { name: 'BALAT', searchable_types: { property_type: 'House', room_type: 'Private room', bed_type: 'Real Bed' } }, { name: 'The Executive Posh Room', searchable_types: { property_type: 'House', room_type: 'Private room', bed_type: 'Real Bed' } }, { name: 'Holoholo Inn: Rain Forest (Priv-2)', searchable_types: { property_type: 'House', room_type: 'Private room', bed_type: 'Real Bed' } }, { name: 'Beautiful Ensuite Room -Easy access to city', searchable_types: { property_type: 'House', room_type: 'Private room', bed_type: 'Real Bed' } }, { name: 'ROOM + ENSUITE INNER CITY MOD HOUSE', searchable_types: { property_type: 'House', room_type: 'Private room', bed_type: 'Real Bed' } }, { name: 'The Sassy Lilac Megan Love Room', searchable_types: { property_type: 'House', room_type: 'Private room', bed_type: 'Real Bed' } } ]
ブール値、ObjectId、UUID などのサポートされていないフィールド型に対してファセット化を行うには、その値を string 型に変換することをお勧めします。
次の例では、sample_airbnb.listingsAndReviews 名前空間にビューを作成し、boolean 型のhost.host_is_superhost フィールドとobjectID 型の_id フィールドをファセット化できるようにします。
mongosh を使用してクラスターに接続します。
詳細については、 mongosh経由でクラスターに接続する を参照してください。
Atlas で、プロジェクトの [Clusters] ページに移動します。
まだ表示されていない場合は、希望するプロジェクトを含む組織を選択しますナビゲーション バーのOrganizationsメニュー
まだ表示されていない場合は、ナビゲーション バーのProjectsメニューから目的のプロジェクトを選択します。
サイドバーで、 Database見出しの下のClustersをクリックします。
[ Clusters (クラスター) ] ページが表示されます。
In Atlas, go to the Search & Vector Search page for your cluster.
MongoDB 検索するページには、Search & Vector Search オプションまたは Data Explorer から移動できます。
まだ表示されていない場合は、プロジェクトを含む組織をナビゲーション バーの Organizations メニューで選択します。
まだ表示されていない場合は、ナビゲーション バーの Projects メニューからプロジェクトを選択します。
まだ表示されていない場合は、プロジェクトを含む組織をナビゲーション バーの Organizations メニューで選択します。
まだ表示されていない場合は、ナビゲーション バーの Projects メニューからプロジェクトを選択します。
サイドバーで、 Database見出しの下のData Explorerをクリックします。
データベースを展開し、コレクションを選択します。
コレクションのIndexesタブをクリックします。
バナー内の Search and Vector Search リンクをクリックします。
検索とベクトル検索ページが表示されます。
Create Search Index をクリックしてインデックス構成を開始します。
ページで次の選択を行い、Next をクリックしてください。
Search Type | MongoDB Search のインデックスタイプを選択します。 |
Index Name and Data Source | 以下の情報を指定してください。
|
Configuration Method | 生のインデックス定義を編集するには JSON Editor を選択します。 |
listingsAndReviews ソースコレクションをクエリします。
次のクエリは、summary フィールドでocean view をlistings_SearchableTypes インデックスから検索します。このクエリは、個別の _id と host.host_is_superhost ごとに属するプロパティ数を取得します。このクエリを実行するには、クエリをコピーして貼り付け、Search をクリックします。
[{ "$searchMeta": { "index": "listingsSearchableTypes", "facet":{ "operator": { "text": { "path": "summary", "query": "ocean view" } }, "facets": { "idFacet" : { "type" : "string", "path" : "idString", "numBuckets" : 10, }, "hostFacet": { "type" : "string", "path" : "superHostString" } } } } }]
count: Object lowerBound: 510 facet: Object idFacet: Object buckets: Array (10) 0: Object _id: "10082422" count: 1 1: Object _id: "10166986" count: 1 2: Object _id: "10266175" count: 1 3: Object _id: "10267144" count: 1 4: Object _id: "10317142" count: 1 5: Object _id: "10359729" count: 1 6: Object _id: "10392282" count: 1 7: Object _id: "10548991" count: 1 8: Object _id: "1067052" count: 1 9: Object _id: "1069531" count: 1 hostFacet: Object buckets: Array (2) 0: Object _id: "false" count: 370 1: Object _id: "true" count: 140
MongoDB 配置にmongoshを使用して接続します。
詳細については、 mongosh経由でクラスターに接続する を参照してください。
listings_SearchableTypes ビューを作成します。
次のビューには、次の 2 つのフィールドが含まれています。
idStringstring型に変換した後の_idフィールドの値を含みます。superHostStringstring型に変換した後のhost.host_is_superhostフィールドの値を含みます。
db.createView( "listings_SearchableTypes", "listingsAndReviews", [ { "$addFields": { "idString": { "$toString": "$_id" }, "superHostString": { "$toString": "$host.host_is_superhost" } } } ] )
ビューでMongoDB Searchインデックスを作成します。
次のインデックス定義では、idString フィールドと superHostString フィールドが token 型としてインデックス化され、これらのフィールドでファセットがサポートされます。
db.listings_SearchableTypes.createSearchIndex( "listingsSearchableTypes", { "mappings": { "dynamic": true, "fields": { "idString": { "type": "token" }, "superHostString": { "type": "token" } } } } )
listingsSearchableTypes 部分インデックスをクエリします。
次のクエリは、summary フィールドの ocean view をlistings_SearchableTypes インデックスで検索します。このクエリは、個別の _id と host.host_is_superhost ごとに属するプロパティ数を取得します。
db.listings_SearchableTypes.aggregate([{ "$searchMeta": { "index": "listingsSearchableTypes", "facet":{ "operator": { "text": { "path": "summary", "query": "ocean view" } }, "facets": { "idFacet" : { "type" : "string", "path" : "idString", "numBuckets" : 10, }, "hostFacet": { "type" : "string", "path" : "superHostString" } } } } }])
[ { count: { lowerBound: Long('510') }, facet: { idFacet: { buckets: [ { _id: '10082422', count: Long('1') }, { _id: '10166986', count: Long('1') }, { _id: '10266175', count: Long('1') }, { _id: '10267144', count: Long('1') }, { _id: '10317142', count: Long('1') }, { _id: '10359729', count: Long('1') }, { _id: '10392282', count: Long('1') }, { _id: '10548991', count: Long('1') }, { _id: '1067052', count: Long('1') }, { _id: '1069531', count: Long('1') } ] }, hostFacet: { buckets: [ { _id: 'false', count: Long('370') }, { _id: 'true', count: Long('140') } ] } } } ]
Decimal128 タイプのフィールドで検索するには、値を double タイプに変換することをお勧めします。
以下の例では、sample_airbnb.listingsAndReviews名前空間にビューを作成し、totalPriceという名前のフィールドを追加します。このフィールドには、priceフィールドとcleaning_feeフィールドの値をdoubleに変換した後の合計が含まれます。
mongosh を使用してクラスターに接続します。
詳細については、 mongosh経由でクラスターに接続する を参照してください。
listings_SearchablePrice という名前のビューを作成します。
次のビューには、price とcleaning-fee フィールドの値の合計を含む totalPrice という名前のフィールドが含まれています。これらのフィールドの値を追加する前に、次のコードは price とcleaning-fee フィールドの値をdouble 型に変換します。
1 db.createView( 2 "listings_SearchablePrice", 3 "listingsAndReviews", 4 [ 5 { 6 "$addFields": { 7 "totalPrice": { 8 "$add": [ 9 { 10 "$ifNull": [{ "$toDouble": "$price" }, 0] 11 }, 12 { 13 "$ifNull": [{ "$toDouble": "$cleaning_fee" }, 0] 14 } 15 ] 16 } 17 } 18 } 19 ] 20 )
Atlas で、プロジェクトの [Clusters] ページに移動します。
まだ表示されていない場合は、希望するプロジェクトを含む組織を選択しますナビゲーション バーのOrganizationsメニュー
まだ表示されていない場合は、ナビゲーション バーのProjectsメニューから目的のプロジェクトを選択します。
サイドバーで、 Database見出しの下のClustersをクリックします。
[ Clusters (クラスター) ] ページが表示されます。
In Atlas, go to the Search & Vector Search page for your cluster.
MongoDB 検索するページには、Search & Vector Search オプションまたは Data Explorer から移動できます。
まだ表示されていない場合は、プロジェクトを含む組織をナビゲーション バーの Organizations メニューで選択します。
まだ表示されていない場合は、ナビゲーション バーの Projects メニューからプロジェクトを選択します。
まだ表示されていない場合は、プロジェクトを含む組織をナビゲーション バーの Organizations メニューで選択します。
まだ表示されていない場合は、ナビゲーション バーの Projects メニューからプロジェクトを選択します。
サイドバーで、 Database見出しの下のData Explorerをクリックします。
データベースを展開し、コレクションを選択します。
コレクションのIndexesタブをクリックします。
バナー内の Search and Vector Search リンクをクリックします。
検索とベクトル検索ページが表示されます。
Create Search Index をクリックしてインデックス構成を開始します。
ページで次の選択を行い、Next をクリックしてください。
Search Type | MongoDB Search のインデックスタイプを選択します。 |
Index Name and Data Source | 以下の情報を指定してください。
|
Configuration Method | 生のインデックス定義を編集するには JSON Editor を選択します。 |
ソースコレクションをクエリします。
次のクエリは、インデックス名listingsSearchablePrice に対して、価格が 100 以上 200 以下(両端を含む)のプロパティを検索します。このクエリを実行するには、クエリをコピーして貼り付け、Search をクリックします。
[ { "$search": { "index": "listingsSearchablePrice", "range": { "path": "totalPrice", "gte": 100, "lte": 200 } } } ]
SCORE: 1 _id: "10006546" access: "We are always available to help guests. The house is fully available t…" accommodates: 8 address: Object price: 80.00 SCORE: 1 _id: "10066928" access: "Le logement sera disponible en entier pour votre séjour." accommodates: 6 address: Object price: 140.00 SCORE: 1 _id: "10120414" access: "You can access to the rooftop where you have a beautiful view of Empir…" accommodates: 3 address: Object price: 150.00 SCORE: 1 _id: "10133554" access: "We have bathroom,wc,İnternet in rooms and under rooms we have cafe bar…" accommodates: 3 address: Object price: 121.00 SCORE: 1 _id: "10186755" access: "" accommodates: 2 address: Object price: 185.00 SCORE: 1 _id: "10213499" access: "Guests have access to backyard saltwater pool" accommodates: 2 address: Object price: 117.00 SCORE: 1 _id: "1022200" access: "" accommodates: 6 address: Object price: 135.00 SCORE: 1 _id: "10228731" access: "O quarto é privativo, com acesso a todas as acomodações do apartamento…" accommodates: 1 address: Object price: 149.00 SCORE: 1 _id: "10359729" access: "" accommodates: 4 address: Object price: 105.00 SCORE: 1 _id: "1036027" access: "" accommodates: 8 address: Object price: 100.00
MongoDB 配置にmongoshを使用して接続します。
詳細については、 mongosh経由でクラスターに接続する を参照してください。
listings_SearchablePrice ビューを作成します。
次のビューには、price とcleaning-fee フィールドの値の合計を含む totalPrice という名前のフィールドが含まれています。これらのフィールドの値を追加する前に、次のコードは price とcleaning-fee フィールドの値をdouble 型に変換します。
db.createView( "listings_SearchablePrice", "listingsAndReviews", [ { "$addFields": { "totalPrice": { "$add": [ { "$ifNull": [{ "$toDouble": "$price" }, 0] }, { "$ifNull": [{ "$toDouble": "$cleaning_fee" }, 0] } ] } } } ] )
listingsSearchablePrice インデックスをクエリします。
次のクエリは、インデックス名listingsSearchablePrice に対して、価格が 100 以上 200 以下(両端を含む)のプロパティを検索します。
db.listingsAndReviews.aggregate([ { "$search": { "index": "listingsSearchablePrice", "range": { "path": "totalPrice", "gte": 100, "lte": 200 } } }, { "$project": { "_id": 0, "totalPrice": 1, "price": 1, "cleaning_fee": 1 } } ])
[ { price: Decimal128('80.00'), cleaning_fee: Decimal128('35.00') }, { price: Decimal128('140.00') }, { price: Decimal128('150.00') }, { price: Decimal128('121.00') }, { price: Decimal128('185.00') }, { price: Decimal128('117.00'), cleaning_fee: Decimal128('0.00') }, { price: Decimal128('135.00') }, { price: Decimal128('149.00'), cleaning_fee: Decimal128('30.00') }, { price: Decimal128('105.00') }, { price: Decimal128('100.00') }, { price: Decimal128('138.00') }, { price: Decimal128('100.00'), cleaning_fee: Decimal128('80.00') }, { price: Decimal128('112.00'), cleaning_fee: Decimal128('0.00') }, { price: Decimal128('80.00'), cleaning_fee: Decimal128('30.00') }, { price: Decimal128('129.00'), cleaning_fee: Decimal128('60.00') }, { price: Decimal128('112.00') }, { price: Decimal128('100.00'), cleaning_fee: Decimal128('100.00') }, { price: Decimal128('85.00'), cleaning_fee: Decimal128('15.00') }, { price: Decimal128('85.00'), cleaning_fee: Decimal128('40.00') }, { price: Decimal128('135.00'), cleaning_fee: Decimal128('50.00') } ] Type "it" for more
ビューを編集する
次の例では、2000 年より前の映画の movies_ReleasedAfter2000 MongoDB ビューを更新します。
db.runCommand( { collMod: "movies_ReleasedAfter2000", viewOn: "movies", "pipeline": [ { $match: { $expr: { $lt: [ "$released", ISODate("2000-01-01T00") ] } } } ] } )
このコマンドを実行すると、MongoDB Search はビュー定義の変更を自動的に検出し、ダウンタイムを発生させることなく再インデックス作成を実行します。
ビューのパイプラインを返します
次の例では、movies_ReleasedAfter2000 ビューのパイプラインを返します。
db.getCollectionInfos({ name: "movies_ReleasedAfter2000" })[0].options.pipeline
[ { '$match': { '$expr': { '$gt': [ '$released', ISODate('2000-01-01T00:00:00.000Z') ] } } } ]
パフォーマンスに関する考慮事項
非常に複雑なビュー変換では、インデックスの作成とクエリ時間が増加する可能性があります。これは、インデックス作成(最初の同期と 定常状態のレプリケーション)中にoplogエントリをフィルタリングして変換するとき、およびクエリ時に返されたドキュメントにそれらの変換を適用するときに、mongodはビュー定義を読み取る必要があるためです。
Atlas で余計なレプリケーション負荷を回避するために、 マテリアライズドビューの作成を検討してください。ビュー変換によるクエリレイテンシを回避するために、ソースコレクションを直接クエリすることもできます。
トラブルシューティング
インデックスの変更 FAILED
インデックスは次のシナリオで FAILED ステータスに変更されます。
MongoDB Search と互換性のないビューにインデックスを作成する。
MongoDB Search の互換性要件を満たさない方法でビューを編集する。
ビューのソース コレクションを削除または変更します。
たとえば、1 つのビューが別のビュー上に作成され、親ビューのソースを別のコレクションに変更した場合です。
注意
この制限は、ビューが他のビューの子である場合にも適用されます。たとえば、すべての子が由来するソース コレクションを変更または削除することはできません。
インデックスの変更 STALE
インデックスは次のシナリオで STALE ステータスに変更されます。
警告
ビューで定義された集計パイプラインがコレクション内のドキュメントと互換性がない場合、検索レプリケーションは失敗します。たとえば、$toDouble 式が配列を含むドキュメント フィールドに対して操作されると、レプリケーションは失敗します。ビューがコレクション内のすべてのドキュメントでエラーなく動作することを確認してください。
インデックスが
READYのときにビュー定義によって集計が失敗した場合、インデックスはSTALEになります。ドキュメントを解決するかビュー定義を変更して失敗しないようにすると、インデックスはREADYに戻ります。STALEの場合でも、インデックスは引き続きクエリ可能です。インデックスがoplogから削除されると、インデックスの再構築がトリガーされます。インデックスが
BUILDINGの時にビュー定義によって集計パイプラインに障害が発生した場合、インデックス構築はそのドキュメントが修正されるまで停止します。ドキュメントを解決するか、ビュー定義を変更すると、インデックスはREADYに戻り、失敗しなくなります。
Atlas UI で「インデックス ステータスの詳細」ページを表示して、インデックス ステータスを確認できます。
Error: $search is only valid as the first stage in a pipeline
このエラーは、8.1 より前のバージョンのMongoDBを使用してビューをクエリすると表示されます。
8.0 より前のバージョンのMongoDBを使用している場合は、ビューを直接クエリするために 8.1+ にアップグレードすることをお勧めします。ソースコレクションをクエリするには、 8.0 にアップグレードします。
MongoDB 8.0 を使用する場合は、 ソースコレクションに対してビューインデックスをクエリする必要があります。例、ビューではなくコレクションで
.aggregate()を実行します。
インデックス プロセス
ビューでMongoDB Searchインデックスを作成すると、mongot プロセスは通常のコレクションでMongoDB Searchインデックスを作成する場合と同じタスクを実行します。mongot プロセス:
コレクションのインデックス定義 のルールに基づいてMongoDB Search インデックスを作成します。
MongoDB Search インデックスを定義したコレクションについて、ドキュメントとインデックスの現在の状態に関する 変更ストリーム をモニターします。
MongoDB Search クエリを処理し、一致するドキュメントのドキュメントID とその他の検索メタデータを
mongodに返します。その後、ドキュメント全体が検索され、その結果がクライアントに返されます。
ビューでMongoDB検索インデックスを作成すると、ステップ 1 と 2 中にビュー定義が適用され、変換されたドキュメントは検索インデックス定義に基づいてインデックス化され、ディスクに保存されます。
詳細
ビューの詳細については、「ビュー」を参照してください。
ビューにMongoDB ベクトル検索インデックスを作成するには、 MongoDB ベクトル検索でビューを使用する を参照してください。