Atlas Search インデックスの作成
Atlas Search インデックスは、簡単に検索可能な形式でデータを分類するデータ構造であり、タームとタームを含むドキュメントの間をマッピングします。Atlas Search インデックスを使用すると、特定の識別子を使用してドキュメントをすばやく検索できます。Atlas Search を使用して Atlas クラスター内のデータをクエリするには、Atlas Search インデックスを構成する必要があります。
Atlas Search インデックスは、単一または複数のフィールドで作成できます。データのソートやフィルタリングによく使用するフィールドはインデックスを作成して、クエリ時に関連データを含むドキュメントをすばやく取得できるようにすることをお勧めします。
Atlas クラスター上の全コレクション(時系列コレクションを除く)を対象に Atlas Search インデックスを作成するには、Atlas UI、API、Atlas CLI、Terraform を使用します。
重要
前提条件
Atlas Search インデックスを作成するには、次の Atlas クラスターが必要です。
MongoDB バージョン
4.2
以上がインストールされた任意のクラスター階層Atlas Search インデックスの作成対象のコレクション
必要なアクセス権
次の表は、指定された Atlas Search アクションに対して各ユーザーロールがサポートするアクセスモードを示しています。
ロール | Atlas Search アクション | Atlas UI | Atlas CLI | Atlas API [1] |
---|---|---|---|---|
Atlas Search アナライザーとインデックスを表示します。 | ✓ | ✓ | ||
Atlas Search アナライザとインデックスを作成および管理するために。 | ✓ | ✓ | ✓ | |
Atlas 検索インデックスを作成、表示、更新、および削除するために操作を行います。 | ✓ | ✓ | ✓ |
[1] | 各ロールは、Atlas 管理 API 内のAtlas Search API エンドポイントのサブセットまたはフルセットを呼び出す権限を付与します。各ロールがアクセスを許可する API エンドポイントの説明については、Atlas 検索アクション列を参照してください。 |
インデックスを作成するデータベースには、少なくとも readWriteAnyDatabase
ロールまたは readWrite
アクセス権が必要です。詳しくは、「組み込みロール」または「特定の特権」を参照してください。
インデックスの制限
インデックス作成数の上限は以下のとおりです。
M0
クラスターで 3 件。M2
クラスターで 5 件M5
クラスターで 10 件Flex クラスターで 10 インデックス。
単一の
M10+
クラスターには、2,500 以下の検索インデックスを作成することを推奨します。Compass から Atlas Searchインデックスを作成するには、
M10+
MongoDB 以上を実行中 Atlas7.0 クラスターが必要です。
インデックスのサイズを見積もる
コレクションのサブセットにインデックスを作成することで、インデックスのサイズを見積もることができます。
データのサンプルを取得し、サンプル データを使用して新しいコレクションを作成します。
サンプル データを使用してコレクションに検索インデックスを作成します。
注意
サンプル データのインデックス定義は、完全なコレクションに作成するインデックス定義と同じである必要があります。
データの合計サイズに基づいて、サンプル データ インデックスのサイズをスケーリングします。
estimated-index-size = ( subset-data-index-size / subset-data-size ) x total-collection-data-size
例
この例では、 sample_mflix.movies
名前空間を使用します。 最初に$sample
を実行して、 movies
コレクションから10ドキュメントをランダムに選択し、 $sample
出力ドキュメントを含むsample_data
という名前の新しいコレクションを作成します。
db.movies.aggregate([ { $sample: { size: 10 } }, { $out: "sample_data" } ])
[ { _id: ObjectId('573a13bbf29313caabd53f9c'), plot: "Three years ago, in real-life, Hama Ali, a charismatic actor from Iraq famous locally for his performance as Iraq's version of Superman, met Ayca on a film-set. He and Ayca, a fiery actress...", genres: [ 'Drama', 'Romance', 'War' ], runtime: 93, cast: [ 'Ayèa Damgaci', 'Hama Ali Kahn', 'Cengiz Bozkurt', 'Nesrin Cavadzade' ], num_mflix_comments: 1, poster: 'https://m.media-amazon.com/images/M/MV5BMjA1OTI1MjI4OV5BMl5BanBnXkFtZTgwODk1MTA2MDE@._V1_SY1000_SX677_AL_.jpg', title: 'Gitmek: My Marlon and Brando', fullplot: "Three years ago, in real-life, Hama Ali, a charismatic actor from Iraq famous locally for his performance as Iraq's version of Superman, met Ayca on a film-set. He and Ayca, a fiery actress from Turkey, had a passionate love affair before returning to their respective homes. From his Kurdish village, Hama Ali sends Ayca video love letters which he has filmed on his handycam. She watches them from her sofa in Istanbul, with her cat for company. The video love letters capture the hellish violence engulfing Iraq, the goats and uncles populating his rural area, and also his tender affection towards her. Feeling suffocated by her own city and angered by the indifference towards the war that surrounds her, Ayca decides to make the journey eastwards to Iraq to be reunited with her lover. GITMEK, a dramatic feature film, is based on the true story of Ayca's departure from Istanbul and her extraordinary journey to the Iraqi border. At a time when many people were fleeing from East to West in search of safety, Ayca makes the opposite journey, in search of love. She is helped by immigrant artists who live in the slums of Istanbul and the mothers of long distance truck drivers who she meets at various border towns. The journey takes her through breathtaking landscapes, strange encounters and terrifying times.", languages: [ 'English', 'Kurdish', 'Turkish' ], released: ISODate('2008-11-14T00:00:00.000Z'), directors: [ 'Huseyin Karabey' ], writers: [ 'Ayèa Damgaci', 'Huseyin Karabey' ], awards: { wins: 12, nominations: 4, text: '12 wins & 4 nominations.' }, lastupdated: '2015-07-04 00:20:59.083000000', year: 2008, imdb: { rating: 6.6, votes: 628, id: 920460 }, countries: [ 'Turkey' ], type: 'movie', tomatoes: { viewer: { rating: 3.7, numReviews: 181, meter: 79 }, lastUpdated: ISODate('2015-07-16T18:10:38.000Z') } }, { _id: ObjectId('573a139af29313caabcefb6a'), plot: '48 hours of intersecting lives and crimes in Los Angeles.', genres: [ 'Comedy', 'Crime', 'Drama' ], runtime: 104, rated: 'R', cast: [ 'Danny Aiello', 'Greg Cruttwell', 'Jeff Daniels', 'Teri Hatcher' ], num_mflix_comments: 1, poster: 'https://m.media-amazon.com/images/M/MV5BZDI0ZmFmYTgtMTQ5OS00MTVmLTgwNWYtNzIyY2Y5NjYxNzgyXkEyXkFqcGdeQXVyNzc5MjA3OA@@._V1_SY1000_SX677_AL_.jpg', title: '2 Days in the Valley', fullplot: 'John Herzfeld deftly welds together a multitude of subplots-- a loser hitman and a cool assassin involved in an insurance scam; a washed-up director, turned suicidal, if only he had someone to care for his beloved dog; a snooty art dealer, wracked by kidney stones, cared for by his devoted assistant; a grungy deranged vice cop, now partnered with a fresh-faced rookie; and two beautiful and jealous women entangled in their deadly scheme--into a spoof of the crime thriller genre.', languages: [ 'English', 'Vietnamese' ], released: ISODate('1996-09-27T00:00:00.000Z'), directors: [ 'John Herzfeld' ], writers: [ 'John Herzfeld' ], awards: { wins: 0, nominations: 1, text: '1 nomination.' }, lastupdated: '2015-09-11 00:42:22.520000000', year: 1996, imdb: { rating: 6.5, votes: 15019, id: 115438 }, countries: [ 'USA' ], type: 'movie', tomatoes: { viewer: { rating: 3, numReviews: 14630, meter: 55 }, dvd: ISODate('2001-08-07T00:00:00.000Z'), critic: { rating: 6, numReviews: 53, meter: 60 }, lastUpdated: ISODate('2015-08-19T18:25:36.000Z'), consensus: 'A labyrinthine thriller with a host of memorable characters, 2 Days in the Valley is an uneven but intriguing thriller/black comedy.', rotten: 21, production: 'HBO Video', fresh: 32 } }, { _id: ObjectId('573a13bdf29313caabd5943e'), fullplot: "When Emily Parris exposes a secret society of teenage girls who have slipped out of the world of social media and into another world they've discovered in the woods at night. When she accuses the girls of committing sexually deviant activities, Emily sends the small American town into a atmosphere of hysteria and the national media spotlight. The mystery deepens when each of the accused girls upholds a vow of silence.", imdb: { rating: 6.2, votes: 861, id: 1015471 }, year: 2014, plot: "When a teenage girl says she's the victim of a secret network called The Sisterhood of Night, a quiet suburban town becomes the backdrop for a modern-day Salem witch trial.", genres: [ 'Drama', 'Mystery', 'Thriller' ], rated: 'PG-13', metacritic: 60, title: 'The Sisterhood of Night', lastupdated: '2015-09-10 17:22:16.113000000', languages: [ 'English' ], writers: [ 'Marilyn Fu (screenplay)', 'Steven Millhauser (short story)' ], type: 'movie', tomatoes: { website: 'http://www.thesisterhoodofnight-movie.com/', viewer: { rating: 3.6, numReviews: 382, meter: 65 }, dvd: ISODate('2015-06-09T00:00:00.000Z'), critic: { rating: 6.6, numReviews: 19, meter: 79 }, boxOffice: '$5.3k', rotten: 4, production: 'Cine Mosaic', lastUpdated: ISODate('2015-09-13T17:24:37.000Z'), fresh: 15 }, poster: 'https://m.media-amazon.com/images/M/MV5BODg3MjE0MDM4N15BMl5BanBnXkFtZTgwOTY0MjE5NDE@._V1_SY1000_SX677_AL_.jpg', num_mflix_comments: 1, released: ISODate('2014-10-18T00:00:00.000Z'), awards: { wins: 2, nominations: 3, text: '2 wins & 3 nominations.' }, countries: [ 'USA' ], cast: [ 'Georgie Henley', 'Kara Hayward', 'Willa Cuthrell', 'Olivia DeJonge' ], directors: [ 'Caryn Waechter' ], runtime: 104 }, { _id: ObjectId('573a13c4f29313caabd6d7bf'), plot: 'A film producer struggles with suicidal despair.', genres: [ 'Drama' ], runtime: 110, metacritic: 76, cast: [ 'Louis-Do de Lencquesaing', 'Chiara Caselli', 'Alice de Lencquesaing', 'Alice Gautier' ], num_mflix_comments: 0, poster: 'https://m.media-amazon.com/images/M/MV5BMTUxODczODA2NV5BMl5BanBnXkFtZTcwNzExMjQ1Mw@@._V1_SY1000_SX677_AL_.jpg', title: 'Father of My Children', fullplot: "In the first half, Gregoire, a movie producer of great charm, owner of Moon Films, plays with his younger daughters, talks with his wife and his eldest daughter, and keeps his studio going while one project hemorrhages money and creditors circle. In the second half, Sylvia, his Italian wife, tries to hold the family together as she looks fully into Moon Films' troubles. She meets with a banker, a temperamental Swede, Russian TV magnates, a film lab exec, and Moon's lawyer. Clèmence, the oldest daughter, goes on her own search. Debt can crush; how does a family pick up the pieces?", languages: [ 'French' ], released: ISODate('2009-12-16T00:00:00.000Z'), directors: [ 'Mia Hansen-Lève' ], writers: [ 'Mia Hansen-Lève (screenplay)' ], awards: { wins: 2, nominations: 3, text: '2 wins & 3 nominations.' }, lastupdated: '2015-09-02 00:01:22.897000000', year: 2009, imdb: { rating: 6.7, votes: 1820, id: 1356928 }, countries: [ 'France', 'Germany', 'Belgium' ], type: 'movie', tomatoes: { website: 'http://www.filmsdulosange.fr/fr/fr_peredemesenfants.html', viewer: { rating: 3.3, numReviews: 1232, meter: 60 }, dvd: ISODate('2010-06-21T00:00:00.000Z'), critic: { rating: 7.4, numReviews: 55, meter: 91 }, lastUpdated: ISODate('2015-09-11T18:38:12.000Z'), consensus: 'A tragedy gracefully lifted by tender empathy and moments of joy, Father of My Children is a quiet triumph for writer-director Mia Hansen-Love.', rotten: 5, production: 'IFC Films', fresh: 50 } }, { _id: ObjectId('573a13a5f29313caabd15cc1'), plot: 'After a 13-year imprisonment in Hong Kong, a kickboxer challenges the current champion in order to restore his honor.', genres: [ 'Drama', 'Romance', 'Sport' ], runtime: 105, cast: [ 'Andy Lau', 'Takako Tokiwa', 'Inthira Charoenpura', 'Apichaya Thanatthanapong' ], title: 'Ah Fu', lastupdated: '2015-09-14 12:56:13.823000000', languages: [ 'Cantonese' ], released: ISODate('2000-11-21T00:00:00.000Z'), directors: [ 'Daniel Lee' ], writers: [ 'Chi-Sing Cheung', 'Daniel Lee' ], awards: { wins: 1, nominations: 3, text: '1 win & 3 nominations.' }, year: 2000, imdb: { rating: 6.6, votes: 350, id: 277558 }, countries: [ 'Hong Kong' ], type: 'movie', tomatoes: { viewer: { rating: 3.3, numReviews: 644, meter: 57 }, lastUpdated: ISODate('2015-04-25T18:41:33.000Z') }, num_mflix_comments: 0 }, { _id: ObjectId('573a13bef29313caabd5ce2b'), plot: 'Johann Sebastian Bach llega con su familia a Leipzig para ocupar el puesto de cantor en la Escuela de Santo Tomès...', genres: [ 'Musical' ], runtime: 102, metacritic: 70, cast: [ 'Christian Atanasiu', 'Fèodor Atkine', 'George-Christoph Biller', 'Christian Brembeck' ], title: 'The Silence Before Bach', lastupdated: '2015-05-25 00:50:52.210000000', languages: [ 'Spanish', 'German', 'Catalan' ], released: ISODate('2007-12-21T00:00:00.000Z'), directors: [ 'Pere Portabella' ], writers: [ 'Xavier Albertè', 'Pere Portabella', 'Carles Santos' ], awards: { wins: 3, nominations: 3, text: '3 wins & 3 nominations.' }, year: 2007, imdb: { rating: 6.8, votes: 329, id: 1079450 }, countries: [ 'Spain' ], type: 'movie', tomatoes: { website: 'http://www.pereportabella.com/eng/fla/die/home_eng.html', viewer: { rating: 3.5, numReviews: 391, meter: 64 }, critic: { rating: 6.6, numReviews: 16, meter: 81 }, lastUpdated: ISODate('2015-08-11T19:15:49.000Z'), rotten: 3, production: 'Film Forum', fresh: 13 }, num_mflix_comments: 0 }, { _id: ObjectId('573a13ccf29313caabd83260'), plot: 'A woman subject to mental, physical, and sexual abuse on a remote island seeks a way out.', genres: [ 'Crime', 'Drama', 'Horror' ], runtime: 115, cast: [ 'Yeong-hie Seo', 'Seong-won Ji', 'Min-ho Hwang', 'Min Je' ], num_mflix_comments: 0, poster: 'https://m.media-amazon.com/images/M/MV5BMjAyNDEwMDgzMl5BMl5BanBnXkFtZTcwNzMyMTYwNQ@@._V1_SY1000_SX677_AL_.jpg', title: 'Bedevilled', fullplot: "Hae-won is a beautiful single woman in her thirties who works at a bank in the Seoul city. She leads a busy life until she becomes a witness to an attempted murder case, and at the same time, things get complicated at work. When things get out of hand she is forced to take a vacation so she heads for 'Moodo', a small undeveloped island, where she had once visited to see her grandparents. And where she had befriended a girl named Bok-nam who stills writes to Hae-won asking her to visit despite the fact that Hae-won never bothered to reply. Upon arriving at the island, Hae-won is shocked to see everyone treating Bok-nam like a slave. As practically the only young woman on the island, she is a plaything for all the men and a free laborer for the women. Sick of all the inhumane treatment, Bok-nam had tried to escape the island several times in the past but had failed each time. She begs Hae-won to help her escape the place, but Hae-won remains indifferent not wanting to be involved in complicated situations. When Bok-nam realizes that her own daughter will follow her footsteps, she tries to escape the island with her daughter.", languages: [ 'Korean' ], released: ISODate('2010-09-02T00:00:00.000Z'), directors: [ 'Cheol-soo Jang' ], writers: [ 'Kwang-young Choi' ], awards: { wins: 10, nominations: 5, text: '10 wins & 5 nominations.' }, lastupdated: '2015-09-01 01:18:02.960000000', year: 2010, imdb: { rating: 7.3, votes: 7983, id: 1646959 }, countries: [ 'South Korea' ], type: 'movie' }, { _id: ObjectId('573a13c7f29313caabd746fe'), plot: 'A Californian family inherits a castle in Romania. This is especially exciting to the son, who is obsessed with monsters. And he is not disappointed.', genres: [ 'Comedy', 'Family' ], runtime: 83, rated: 'TV-G', cast: [ 'Victoria Justice', 'Chase Ellison', 'Anna Galvin', 'Matt Winston' ], num_mflix_comments: 0, poster: 'https://m.media-amazon.com/images/M/MV5BMjU1MmJlMTctY2FiMC00MmU1LWI5NmYtMDc5OWM0NjEzMmI2XkEyXkFqcGdeQXVyNDgyODgxNjE@._V1_SY1000_SX677_AL_.jpg', title: 'The Boy Who Cried Werewolf', fullplot: 'A Californian family inherits a castle in Romania. This is especially exciting to the son, who is obsessed with monsters. And he is not disappointed.', languages: [ 'English' ], released: ISODate('2010-10-22T00:00:00.000Z'), directors: [ 'Eric Bross' ], writers: [ 'Art Edler Brown', 'Douglas Sloan' ], awards: { wins: 1, nominations: 2, text: '1 win & 2 nominations.' }, lastupdated: '2015-08-20 00:01:59.673000000', year: 2010, imdb: { rating: 6.3, votes: 1582, id: 1451423 }, countries: [ 'USA', 'Canada' ], type: 'movie', tomatoes: { viewer: { rating: 3.7, numReviews: 762, meter: 66 }, lastUpdated: ISODate('2015-09-12T17:30:20.000Z') } }, { _id: ObjectId('573a13b4f29313caabd3f473'), genres: [ 'Documentary' ], runtime: 85, title: 'Zero Degrees of Separation', countries: [ 'Canada' ], lastupdated: '2015-08-09 00:30:38.977000000', languages: [ 'Arabic', 'English', 'Hebrew' ], released: ISODate('2005-06-22T00:00:00.000Z'), directors: [ 'Elle Flanders' ], writers: [ 'Elle Flanders' ], awards: { wins: 1, nominations: 0, text: '1 win.' }, year: 2005, imdb: { rating: 6.6, votes: 90, id: 454990 }, type: 'movie', tomatoes: { viewer: { rating: 3.5, numReviews: 5, meter: 100 }, fresh: 1, critic: { numReviews: 2 }, rotten: 1, lastUpdated: ISODate('2015-01-04T23:25:58.000Z') }, num_mflix_comments: 0 }, { _id: ObjectId('573a13bff29313caabd5f070'), plot: 'This hilarious genre-bending comedy follows Gary Brewer, along with girlfriend Holly Brewer (no relation), and best friend Trevor Morehouse as Gary quests to reign supreme at the 2006 Rock, Paper, Scissors World Championships.', genres: [ 'Comedy' ], runtime: 85, cast: [ 'Tim Doiron', 'April Mullen', 'Ryan Tilley', 'Peter Pasyk' ], num_mflix_comments: 0, poster: 'https://m.media-amazon.com/images/M/MV5BMTI5MzIwMjA2Ml5BMl5BanBnXkFtZTcwOTcyOTA4MQ@@._V1_SY1000_SX677_AL_.jpg', title: 'Rock, Paper, Scissors: The Way of the Tosser', fullplot: 'This hilarious genre-bending comedy follows Gary Brewer, along with girlfriend Holly Brewer (no relation), and best friend Trevor Morehouse as Gary quests to reign supreme at the 2006 Rock, Paper, Scissors World Championships.', languages: [ 'English' ], released: ISODate('2007-07-06T00:00:00.000Z'), directors: [ 'Tim Doiron', 'April Mullen' ], writers: [ 'Tim Doiron (creator)', 'April Mullen (creator)', 'Tim Doiron' ], awards: { wins: 2, nominations: 0, text: '2 wins.' }, lastupdated: '2015-08-12 00:01:33.813000000', year: 2007, imdb: { rating: 6.2, votes: 316, id: 1121964 }, countries: [ 'Canada' ], type: 'movie' } ]
次に、 $out
を使用してsample_data
コレクションに追加した$sample
の出力データ用に、 title
フィールドのみにインデックスを作成します。
{ "mappings": { "dynamic": false, "fields": { "title": { "type": "string" } } } }
10ドキュメントを含むsample_data
コレクションのtitle
フィールドのインデックスのサイズは4.34です KB. sample_data
コレクションのサイズは14.19です KB. movies
コレクションの合計サイズは32です。 54 MB、これは32540 KB です。 次の計算を使用して、 movies
コレクション全体のインデックス サイズを見積もります。
4.34 KB / 14.19 KB = 0.30584918957012 KB (per document) 0.30584918957012 KB x 32540 KB = 9952.3326286117048 KB 9265.466 KB x 0.001 MB = 9.952332628611705 MB
movies
コレクション内のtitle
フィールドの推定サイズ インデックス サイズは9.95です MB。 ただし、 movies
コレクションのインデックス サイズは、サンプリングされていないドキュメントのタイトルの長さによって異なる場合があります。
Atlas Search インデックスの作成
Atlas Search インデックスを作成するには、Atlas UI または MongoDB Compass を使用します。また、mongosh
、Atlas CLI、API のいずれかを使用するか、任意の言語でサポート対象の MongoDB ドライバーを使用してプログラム的にも作成できます。
注意
Atlas Search インデックスは、コレクションの一部ではなく、コレクション全体に適用する必要があります。
➤ [言語の選択]ドロップダウン メニューを使用して、このセクション内の例の言語を設定します。
Atlas Search インデックスを作成するには
POST
リクエストを送信します。
POST
リクエストを search/indexes
エンドポイントに送信します。
curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest \ --header "Accept: application/json" \ --header "Content-Type: application/json" \ --include \ --request POST "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes" \ --data ' { "collectionName": "string", "database": "string", "name": "string", "type": "search", "definition": { "analyzer": "lucene.<analyzer>", "analyzers": [ { "charFilters": [ ... ], "name": "string", "tokenFilters": [ ... ], "tokenizer": { ... } } ], "mappings": { "dynamic": true | false, "fields": { "property1": {}, ... } }, "searchAnalyzer": "lucene.<analyzer>", "storedSource": { "include | exclude": [...] }, "synonyms": [ { "analyzer": "lucene.<analyzer>", "name": "string", "source": { "collection": "string" } } ] } }'
このエンドポイントの構文とパラメータについて詳しくは、「作成」を参照してください。
Atlas Search は、Atlas CLI を使用して作成したローカル Atlas 配置で使用することもできます。 詳細については、「 Atlas 配置のローカル配置の作成 」を参照してください。
クラウド配置用 Atlas Search インデックスの作成
Atlas CLI を使用してクラスターの検索インデックスを作成するには、次のコマンドを実行します。
atlas clusters search indexes create [indexName] [options]
コマンド構文とパラメーターの詳細については、Atlas CLI ドキュメントの「atlas clusters search indexes create」を参照してください。
ローカル デプロイ用 Atlas Search インデックスの作成
Atlas CLI を使用して指定したデプロイの検索インデックスを作成するには、次のコマンドを実行します。
atlas deployments search indexes create [indexName] [options]
コマンド構文とパラメーターの詳細については、Atlas CLI ドキュメントの「atlas deployments search indexes create」を参照してください。
例
次の例は、 atlas clusters
またはatlas deployments
コマンドを使用して、構成ファイルを使用して非対話型モードで Atlas Search インデックスを作成する方法を示しています。
$search
クエリの場合、デフォルトの search
タイプのインデックスを作成します。
手順
Atlas UI から Atlas Search インデックスを作成するには、以下の手順を行います。
Atlas Atlasで、プロジェクトの {0 ページにGoします。GoClusters
まだ表示されていない場合は、希望するプロジェクトを含む組織を選択しますナビゲーション バーのOrganizationsメニュー
まだ表示されていない場合は、ナビゲーション バーのProjectsメニューから目的のプロジェクトを選択します。
まだ表示されていない場合は、サイドバーの [Clusters] をクリックします。
[ Clusters (クラスター) ] ページが表示されます。
インデックスの設定を開始します。
ページで次の選択を行い、Next をクリックしてください。
Search Type | Atlas Search のインデックスタイプを選択します。 |
Index Name and Data Source | 以下の情報を指定してください。
|
Configuration Method | For a guided experience, select Visual Editor. To edit the raw index definition, select JSON Editor. |
Index Configurations セクションでデフォルトの Atlas Search インデックス構成設定を確認します。
デフォルトのインデックス定義を使用することも、カスタムのインデックス定義を指定することもできます。
デフォルトのインデックス定義は、ドキュメント内のフィールドを動的にマッピングしたもので、どのコレクションでも機能します。
カスタムのインデックス定義は静的マッピングです。インデックス、アナライザ、データ型にフィールドを指定します。
フィールド名 | 説明 | 必要性 |
---|---|---|
Index Analyzer | 任意 | |
Query Analyzer | 任意 | |
Dynamic Mapping | フィールドの動的マッピングまたは静的マッピングを指定します。動的マッピングを無効にするには、
| 必須 |
フィールド名 | 説明 | 必要性 |
---|---|---|
| 任意 | |
| 任意 | |
| フィールドの動的マッピングまたは静的マッピングを指定します。動的マッピングを無効にするには、 | 必須 |
これらのインデックス定義設定について詳しくは、「Atlas Search インデックス構文の確認」を参照してください。
デフォルト設定に問題がなければ、先に進みます。Atlas Search インデックスを再定義する場合は、次の手順に進みます。
Atlas Search インデックスを微調整して、追加設定を構成します。
以下の設定のいずれかを変更するには [Refine Your Index] をクリックします。
フィールド名説明必要性Field Mappings
Index Configurations セクションの Dynamic Mapping が無効になっている場合は必須です。
独自のフィールド マッピングを定義することは、上級ユーザーのみにおすすめします。
インデックスを作成するフィールドを指定します。フィールドを追加するには、次の操作を行う必要があります。
Add FieldをクリックするとAdd Field Mappingウィンドウが開きます。
フィールドに関する次の情報を指定します。
Field name - インデックスを作成するフィールドの名前。
Data Type Configuration - フィールドのデータ型。サポートされているデータ型とそのオプションについて詳しくは、「データ型」を参照してください。
Enable Dynamic Mapping - ドキュメントおよび埋め込みドキュメント型のフィールドに使用する静的または動的マッピング。動的マッピングを無効にすると、フィールドのデータは自動的にインデックス化されません。
[Add] をクリックしてフィールドを追加します。
オプションで、Actions 列のフィールドの省略記号(...)アイコンをクリックして、次の操作を実行できます。
[Edit] をクリックしてフィールドの設定を変更します。
[Add Data Type] をクリックして、フィールドに追加のデータ型を設定します。
[Delete] をクリックして、インデックスからフィールドを削除します。
Atlas Search インデックス定義では、任意の順序でフィールドを定義できます。
mappings.fields
JSON 設定に対応します。条件付き
Stored Source Fields
Atlas Search に保存するフィールドを指定します。次のいずれかを選択できます。
None -(デフォルト)選択すると、Atlas Search はフィールドをストアしません。
All - 選択すると、Atlas Search はドキュメント内のすべてのフィールドをストアします。
Specified - 選択すると、Atlas Search は
_id
と指定したフィールドをストアします。フィールドを指定するには、次の手順を実行します。Field Name 列のドロップダウンから、Atlas Search に保存するフィールドを選択します。
[Add] をクリックして、保存するフィールドのリストにフィールドを追加します。
[Add Field] をクリックして、リストに追加するフィールドごとに手順 a と b を繰り返します。
(任意)次のいずれかをクリックします。
Edit 別のフィールドを選択します。
Delete 保存するフィールドのリストからフィールドを削除します。
All Except Specified - 選択すると、Atlas Search は特定のフィールドを Atlas Search のストレージから除外します。
Field Name 列のドロップダウンから、除外するフィールドを選択します。
[Add] をクリックして、除外するフィールドのリストにフィールドを追加します。
[Add Field] をクリックして、リストから除外するフィールドごとに手順 a と b を繰り返します。
(任意)次のいずれかをクリックします。
Edit 別のフィールドを選択します。
Delete 除外するフィールドのリストからフィールドを削除します。
フィールドの保存の詳細については、「Atlas Search インデックスに保存されたソース フィールドの定義」を参照してください。
storedSource
JSON 設定に対応します。任意
Synonyms Mappings
インデックスで使用するシノニム マッピングを指定します。詳しくは、「Atlas Searchインデックスでのシノニム マッピングの定義」を参照してください。
シノニム マッピングを追加するには、シノニムごとに次の設定を指定する必要があります。
Synonym mapping name - クエリ時に参照するシノニム マッピングを識別するラベル。ユニークな値を指定する必要があります。空の文字列値を指定することはできません。
Synonym source collection - Atlas Search インデックスと同じデータベース内の MongoDB コレクションを識別するラベル。このコレクションのドキュメントでは、シノニムソースコレクションのドキュメントで説明されている形式を使用しています。空のコレクションを追加したり、サンプルコレクションをロードしたりすることもできます。
Analyzer - このシノニムマッピングで使用するアナライザを識別するラベル。
シノニム(同意語)マッピング を使用して、同じアナライザで分析されたフィールドのみをクエリできます。 デフォルトでは、Atlas Search は標準アナライザ(
"lucene.standard"
)を使用します。以下を除く任意の Atlas Search アナライザを指定できます。
synonyms
JSON 設定に対応します。任意。
Index Partitions
フィールドオブジェクトが 2.1 00 億を超える場合に使用するパーティションの数。
numPartitions
JSON 設定に対応します。重要
numPartitions
オプションはプレビュー機能として利用できます。任意。
[Save Changes] をクリックします。
次のいずれかの設定をインデックスに追加します。
フィールド名説明必要性mappings.fields
mappings.dynamic
がfalse
の場合は必須です。独自のフィールド マッピングを定義することは、上級ユーザーのみにおすすめします。
インデックスを作成するフィールドを指定します。詳しくは「フィールドマッピングの定義」を参照してください。
Atlas Search インデックス定義では、任意の順序でフィールドを定義できます。
条件付き
storedSource
Atlas Search にストアするドキュメント内のフィールドを指定します。値は次のいずれかになります。
true
: すべてのフィールドを保存false
、フィールドを保存しない場合ストレージから
include
またはexclude
にフィールドを指定するオブジェクト
省略した場合、デフォルトは
false
になります。storedSource
次のいずれかのバージョンを実行している Atlas クラスターでのみ使用できます。MongoDB 5.0.6+
MongoDB 6.0+
MongoDB 7.0+
サポートされているすべてのデータ型のフィールドを Atlas Search に保存できます。 構文とフィールドの詳細については、「 Atlas Search インデックスに保存されているソース フィールドの定義 」を参照してください。
任意
synonyms
インデックスで使用するシノニム マッピングを指定します。詳しくは、「Atlas Searchインデックスでのシノニム マッピングの定義」を参照してください。
シノニム(同意語)マッピング を使用して、同じアナライザで分析されたフィールドのみをクエリできます。 デフォルトでは、Atlas Search は標準アナライザ(
"lucene.standard"
)を使用します。任意
numPartitions
フィールドオブジェクトが 2.1 00 億を超える場合に使用するパーティションの数。
重要
numPartitions
オプションはプレビュー機能として利用できます。任意。
これらのインデックス定義設定について詳しくは、「Atlas Search インデックス構文の確認」を参照してください。
[Next] をクリックします。
任意。Visual Editor を使用すると、インデックス定義の下書きを保存または削除できます。
注意
Visual Editor を使用しており、インデックス定義に静的マッピングが含まれている場合は、インデックス定義をドラフトとして保存できます。デフォルトのインデックス定義を下書きとして保存することはできません。下書きとして保存できるのは、カスタムのインデックス定義のみです。
[Cancel] をクリックします。
[Save Draft] または [Delete Draft] をクリックします。
重要
保留中のインデックス ドラフトがある場合は、インデックスを新規作成できません。
インデックス ドラフトを使用したインデックスの作成方法について詳しくは、「Atlas Search インデックス ドラフトの再開または削除」を参照してください。
実際に見て学びたい方に
このビデオ チュートリアルでは、複雑度がさまざまに異なる Atlas Search インデックスの作成方法を紹介します。
所要時間: 15 分
mongosh
を通じて Atlas Search インデックスを作成するには以下の手順を行います。
mongosh
を使用して接続します。
詳しくは、「 mongosh
経由で接続 」を参照してください。
Atlas Search インデックスの作成。
db.collection.createSearchIndex()
メソッドを使用します。
このコマンドの構文は、次のとおりです。インデックス名を省略すると、Atlas Search はインデックスに default
という名前を付けます。詳しくは「Atlas Search インデックス構文の確認」を参照してください。
db.<collection>.createSearchIndex( "<index-name>", { /* search index definition */ } )
例
example-index
という名前のインデックスを作成し、movies
コレクションのフィールドに動的にインデックスするには、次のコマンドを実行します。
db.movies.createSearchIndex( "example-index", { mappings: { dynamic: true } } )
example-index
MongoDB Compass の Atlas クラスターに接続します。
Compass を開き、Atlas クラスターに接続します。接続の詳細な手順については、「Compass 経由での接続」を参照してください。
C ドライバーを使用して Atlas Search インデックスを作成するには、アプリケーションで検索インデックスを定義し、mongoc_collection_command_simple()
メソッドを呼び出します。
注意
Atlas Search インデックス マネジメントのメソッドは非同期で実行されます。ドライバー メソッドは、正常に実行されたことを確認する前に戻ることができます。検索インデックスの現在のステータスを判別するには、$listSearchIndexes
パイプライン ステージで集計操作を実行します。
次のコード例を ファイルにコピーします。
次のサンプルアプリケーションでは、createSearchIndexes
コマンドを指定して、コレクション内のフィールドに動的にインデックスを付ける検索インデックスを定義します。次に、アプリケーションはコマンドと検索インデックス情報を BSON に変換し、この情報を mongoc_collection_command_simple()
メソッドに渡して検索インデックスを作成します。詳しくは「Atlas Search インデックス構文の確認」を参照してください。
int main (void) { mongoc_client_t *client = NULL; mongoc_collection_t *collection = NULL; mongoc_database_t *database = NULL; bson_error_t error; bson_t cmd = BSON_INITIALIZER; bool ok = true; mongoc_init(); // Connect to your Atlas deployment client = mongoc_client_new("<connectionString>"); if (!client) { fprintf(stderr, "Failed to create a MongoDB client.\n"); ok = false; goto cleanup; } // Access your database and collection database = mongoc_client_get_database(client, "<databaseName>"); collection = mongoc_database_get_collection(database, "<collectionName>"); // Specify the command and the new index const char *cmd_str = BSON_STR({ "createSearchIndexes" : "<collectionName>", "indexes" : [ { "definition" : {"mappings" : {"dynamic" : true}}, "name" : "<indexName>" } ] }); // Convert your command to BSON if (!bson_init_from_json(&cmd, cmd_str, -1, &error)) { fprintf(stderr, "Failed to parse command: %s\n", error.message); ok = false; goto cleanup; } // Create the Atlas search index by running the command if (!mongoc_collection_command_simple (collection, &cmd, NULL, NULL, &error)) { fprintf(stderr, "Failed to run createSearchIndexes: %s\n", error.message); ok = false; goto cleanup; } printf ("Index created!\n"); cleanup: mongoc_collection_destroy (collection); mongoc_client_destroy (client); mongoc_database_destroy (database); bson_destroy (&cmd); mongoc_cleanup (); return ok ? EXIT_SUCCESS : EXIT_FAILURE; }
一度に複数の Atlas Search インデックスを作成することもできます。次の例では、作成する各検索インデックスを indexes
配列内のドキュメントとして定義します。次に、コマンドと検索インデックス情報を BSON に変換し、mongoc_collection_command_simple()
メソッドを呼び出して検索インデックスを作成します。
int main (void) { mongoc_client_t *client = NULL; mongoc_collection_t *collection = NULL; mongoc_database_t *database = NULL; bson_error_t error; bson_t cmd = BSON_INITIALIZER; bool ok = true; mongoc_init(); // Connect to your Atlas deployment client = mongoc_client_new("<connectionString>"); if (!client) { fprintf(stderr, "Failed to create a MongoDB client.\n"); ok = false; goto cleanup; } // Access your database and collection database = mongoc_client_get_database(client, "<databaseName>"); collection = mongoc_database_get_collection(database, "<collectionName>"); // Specify the command and the new indexes const char *cmd_str = BSON_STR({ "createSearchIndexes" : "<collectionName>", "indexes" : [{ // Add your search index definition fields here "name" : "<firstIndexName>" }, { // Add your search index definition fields here "name" : "<secondIndexName>" }] }); // Convert your command to BSON if (!bson_init_from_json(&cmd, cmd_str, -1, &error)) { fprintf(stderr, "Failed to parse command: %s\n", error.message); ok = false; goto cleanup; } // Create the Atlas search indexes by running the command if (!mongoc_collection_command_simple (collection, &cmd, NULL, NULL, &error)) { fprintf(stderr, "Failed to run createSearchIndexes: %s\n", error.message); ok = false; goto cleanup; } printf ("Indexes created!\n"); cleanup: mongoc_collection_destroy (collection); mongoc_client_destroy (client); mongoc_database_destroy (database); bson_destroy (&cmd); mongoc_cleanup (); return ok ? EXIT_SUCCESS : EXIT_FAILURE; }
次の値を指定して、ファイルを保存します。
Atlas 接続文字列。詳しくは、「ドライバーによる接続」を参照してください。
インデックスを作成するデータベースとコレクション。
インデックスの名前。インデックス名を省略すると、Atlas Search はインデックスに
default
という名前を付けます。
検索インデックスの定義。詳しくは「Atlas Search インデックス構文の確認」を参照してください。
C++ ドライバーを使用して Atlas Search インデックスを作成するには、アプリケーションで検索インデックスを定義し、create_one()
メソッドを呼び出します。
注意
Atlas Search インデックスマネジメントのメソッドは非同期で実行されます。ドライバーメソッドは、正常に実行されたことを確認する前に戻ることができます。検索インデックスの現在の状態を確認するには、検索インデックスビューのインスタンスで list()
メソッドを呼び出します。
次のコード例を ファイルにコピーします。
次のサンプルアプリケーションでは、検索インデックスの名前と定義を search_index_model()
メソッドに渡して、コレクション内のフィールドに動的にインデックスを付けます。次に、アプリケーションは検索インデックスの仕様を create_one()
メソッドに渡して検索インデックスを作成します。詳しくは「Atlas Search インデックス構文の確認」を参照してください。
using bsoncxx::builder::basic::kvp; using bsoncxx::builder::basic::make_document; using namespace mongocxx; int main() { try { // Connect to your Atlas deployment mongocxx::instance instance{}; mongocxx::uri uri("<connectionString>"); mongocxx::client client(uri); // Access your database and collection auto db = client["<databaseName>"]; auto collection = db["<collectionName>"]; // Create an index model with your index name and definition auto siv = collection.search_indexes(); auto name = "<indexName>"; auto definition = make_document(kvp("mappings", make_document(kvp("dynamic", true)))); auto model = search_index_model(name, definition.view()); // Create the search index siv.create_one(model); std::cout << "Index created!" << std::endl; } catch (const std::exception& e) { std::cout<< "Exception: " << e.what() << std::endl; } return 0; }
一度に複数の Atlas Search インデックスを作成することもできます。作成する検索インデックスごとに、検索インデックスの仕様を search_index_model()
メソッドに渡します。次に、各検索インデックスをベクトルに追加し、そのベクトルを create_many()
メソッドに渡して検索インデックスを作成します。
using bsoncxx::builder::basic::kvp; using bsoncxx::builder::basic::make_document; using namespace mongocxx; int main() { try { // Connect to your Atlas deployment mongocxx::instance instance{}; mongocxx::uri uri("<connectionString>"); mongocxx::client client(uri); // Access your database and collection auto db = client["<databaseName>"]; auto collection = db["<collectionName>"]; // Create index models and add them to a vector auto siv = collection.search_indexes(); std::vector<search_index_model> models; auto name1 = "<firstIndexName>"; auto definition1 = make_document(/* Add search index definition fields here */); auto model1 = search_index_model(name1, definition1.view()); models.push_back(model1); auto name2 = "<secondIndexName>"; auto definition2 = make_document(/* Add search index definition fields here */); auto model2 = search_index_model(name2, definition2.view()); models.push_back(model2); // Create the search indexes siv.create_many(models); std::cout << "Indexes created!" << std::endl; } catch (const std::exception& e) { std::cout<< "Exception: " << e.what() << std::endl; } return 0; }
次の値を指定して、ファイルを保存します。
Atlas 接続文字列。詳しくは、「ドライバーによる接続」を参照してください。
インデックスを作成するデータベースとコレクション。
インデックスの名前。インデックス名を省略すると、Atlas Search はインデックスに
default
という名前を付けます。
検索インデックスの定義。詳しくは「Atlas Search インデックス構文の確認」を参照してください。
インデックスを 1 つ作成する
.NET/C# ドライバーを使用して MongoDB Atlas Search 検索インデックスを作成するには、次の手順を行います。
インデックスを定義する
BsonDocument
を構築します。BsonDocument
をCreateOne()
またはCreateOneAsync()
メソッドに渡します。
次のサンプル アプリケーションでは、コレクション内のフィールドに動的にインデックスを付ける検索インデックスを定義し、CreateOne()
メソッドを実行してインデックスを作成します。詳しくは、「Atlas Search インデックス構文の確認」を参照してください。
Program.cs
ファイルの内容を、インデックスを定義する BsonDocument
に置き換えます。
以下の例のプレースホルダー値を置き換えます。
値 | 説明 |
---|---|
| Atlas 接続文字列。詳しくは、「ドライバーによる接続」を参照してください。 |
| インデックスを作成するデータベース。 |
| インデックスを作成するコレクション。 |
| インデックスの名前。インデックス名を省略すると、Atlas Search はインデックスに |
using MongoDB.Bson; using MongoDB.Driver; // connect to your Atlas deployment var uri = "<connection-string>"; var client = new MongoClient(uri); var db = client.GetDatabase("<databaseName>"); var collection = db.GetCollection<BsonDocument>("<collectionName>"); // define your Atlas Search index var index = new BsonDocument { { "mappings", new BsonDocument { { "dynamic", true } } } }; var result = collection.SearchIndexes.CreateOne(index, "<indexName>"); Console.WriteLine(result);
複数のインデックスの作成
複数の Atlas Search インデックスを一括で作成する方法
検索インデックスの定義を含む
IEnumerable<CreateSearchIndexModel>
インスタンスを構築します。CreateMany()
またはCreateManyAsync()
メソッドにコレクションを渡します。
次の例は、CreateMany()
メソッドを使用して複数のインデックスを作成する方法を示しています。
Program.cs
ファイルの内容を、インデックスを定義する BsonDocument
に置き換えます。
以下の例のプレースホルダー値を置き換えます。
値 | 説明 |
---|---|
| Atlas 接続文字列。詳しくは、「ドライバーによる接続」を参照してください。 |
| インデックスを作成するデータベース。 |
| インデックスを作成するコレクション。 |
| 最初のインデックスの名前。 |
| 最後のインデックスの名前。 |
using MongoDB.Bson; using MongoDB.Driver; // connect to your Atlas deployment var uri = "<connection-string>"; var client = new MongoClient(uri); var db = client.GetDatabase("<databaseName>"); var collection = db.GetCollection<BsonDocument>("<collectionName>"); // define your Atlas Search indexes var indexes = new List<CreateSearchIndexModel> { new CreateSearchIndexModel( "<first-index-name>", new BsonDocument { // search index definition fields } ), ... new CreateSearchIndexModel( "<last-index-name>", new BsonDocument { // search index definition fields } ) }; var result = collection.SearchIndexes.CreateMany(indexes);
Java ドライバーを使用して Atlas Search インデックスを作成するには、検索インデックスを定義するドキュメントを作成し、そのドキュメントを createSearchIndex()
または createSearchIndexes()
メソッドに渡します。詳しくは「ドライバーのドキュメント」を参照してください。
注意
Atlas Search インデックス マネジメントのメソッドは非同期で実行されます。ドライバー メソッドは、正常に実行されたことを確認する前に戻ることができます。インデックスの現在のステータスを確認するには、listSearchIndexes()
メソッドを呼び出します。
次のコード例を ファイルにコピーします。
次のサンプルアプリケーションでは、コレクション内のフィールドに動的インデックスを付ける検索インデックスを定義し、createSearchIndex()
メソッドを実行してインデックスを作成します。詳しくは「Atlas Search インデックス構文の確認」を参照してください。
import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; public class CreateIndex { public static void main(String[] args) { // connect to your Atlas cluster String uri = "<connection-string>"; try (MongoClient mongoClient = MongoClients.create(uri)) { // set namespace MongoDatabase database = mongoClient.getDatabase("<databaseName>"); MongoCollection<Document> collection = database.getCollection("<collectionName>"); Document index = new Document("mappings", new Document("dynamic", true)); collection.createSearchIndex("<index-name>", index); } } }
次のサンプルアプリケーションを使用して、一度に複数の Atlas Search インデックスを作成できます。そのためには、作成する検索インデックスごとにドキュメントを作成し、そのドキュメントを配列として createSearchIndexes()
メソッドに渡します。
import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.SearchIndexModel; import org.bson.Document; import java.util.Arrays; public class CreateIndex { public static void main(String[] args) { // connect to your Atlas cluster String uri = "<connection-string>"; try (MongoClient mongoClient = MongoClients.create(uri)) { // set namespace MongoDatabase database = mongoClient.getDatabase("<databaseName>"); MongoCollection<Document> collection = database.getCollection("<collectionName>"); SearchIndexModel indexOne = new SearchIndexModel("<first-index-name>", new Document( // search index definition fields )); SearchIndexModel indexTwo = new SearchIndexModel("<second-index-name>", new Document( // search index definition fields )); collection.createSearchIndexes(Arrays.asList(indexOne, indexTwo)); } } }
次の値を指定して、ファイルを保存します。
Atlas 接続文字列。詳しくは、「ドライバーによる接続」を参照してください。
インデックスを作成するデータベースとコレクション。
インデックスの名前。インデックス名を省略すると、Atlas Search はインデックスに
default
という名前を付けます。
検索インデックスを定義するフィールド。詳しくは「Atlas Search インデックス構文の確認」を参照してください。
インデックスを 1 つ作成する
ノード ドライバーを使用して Atlas Search インデックスを作成する方法
アプリケーションから検索インデックスを定義します。
createSearchIndex
またはcreateSearchIndexes
ヘルパー メソッドを実行します。
次の create-index.js
という名前のサンプル アプリケーションでは、コレクション内のフィールドに動的にインデックスを付けるための検索インデックスを定義し、createSearchIndex
コマンドを実行してインデックスを作成します。詳しくは「Atlas Search インデックス構文の確認」を参照してください。
検索インデックスを定義します。
以下の例のプレースホルダー値を置き換えます。
値 | 説明 |
---|---|
| Atlas 接続文字列。詳しくは、「ドライバーによる接続」を参照してください。 |
| インデックスを作成するデータベース。 |
| インデックスを作成するコレクション。 |
| インデックスの名前。 インデックス名を省略すると、Atlas Search はインデックスに |
import { MongoClient } from "mongodb"; // connect to your Atlas deployment const uri = "<connection-string>"; const client = new MongoClient(uri); async function run() { try { const database = client.db("<databaseName>"); const collection = database.collection("<collectionName>"); // define your Atlas Search index const index = { name: "<index-name>", definition: { /* search index definition fields */ "mappings": { "dynamic": true } } } // run the helper method const result = await collection.createSearchIndex(index); console.log(result); } finally { await client.close(); } } run().catch(console.dir);
複数のインデックスの作成
複数の Atlas Search インデックスを一括で作成する方法
アプリケーションで、検索インデックスの配列を定義します。
配列を
createSearchIndexes
コマンドに渡します。
以下の例は、createSearchIndexes
コマンドを使用して複数のインデックスを作成する方法を示しています。
検索インデックスを定義します。
以下の例のプレースホルダー値を置き換えます。
値 | 説明 |
---|---|
| Atlas 接続文字列。詳しくは、「ドライバーによる接続」を参照してください。 |
| インデックスを作成するデータベース。 |
| インデックスを作成するコレクション。 |
| 最初のインデックスの名前。 |
| 最後のインデックスの名前。 |
import { MongoClient } from "mongodb"; // connect to your Atlas deployment const uri = "<connection-string>"; const client = new MongoClient(uri); async function run() { try { const database = client.db("<databaseName>"); const collection = database.collection("<collectionName>"); // define an array of Atlas Search indexes const indexes = [ { name: "<first-index-name>", definition: { /* search index definition fields */ } }, ... { name: "<last-index-name>", definition: { /* search index definition fields */ } } ] // run the helper method const result = await collection.createSearchIndexes(indexes); console.log(result); } finally { await client.close(); } } run().catch(console.dir);
Python ドライバーを使用して Atlas Search インデックスを作成するには、アプリケーションから検索インデックスを定義し、create_search_index()
メソッドを呼び出します。
注意
Atlas Search インデックス マネジメントのメソッドは非同期で実行されます。ドライバー メソッドは、正常に実行されたことを確認する前に戻ることができます。検索インデックスの現在のステータスを確認するには、コレクションで list_search_indexes()
メソッドを呼び出します。
例
次のコード例を ファイルにコピーします。
次のサンプル アプリケーションでは、コレクション内のフィールドに動的にインデックスを付ける検索インデックスを定義します。次に、アプリケーションはコレクションの create_search_index()
メソッドを呼び出して検索インデックスを作成します。詳しくは「Atlas Search インデックス構文の確認」を参照してください。
from pymongo.mongo_client import MongoClient from pymongo.operations import SearchIndexModel def create_index(): # Connect to your Atlas deployment uri = "<connectionString>" client = MongoClient(uri) # Access your database and collection database = client["<databaseName>"] collection = database["<collectionName>"] # Create your index model, then create the search index search_index_model = SearchIndexModel( definition={ "mappings": { "dynamic": True }, }, name="<indexName>", ) result = collection.create_search_index(model=search_index_model) print(result)
一度に複数の Atlas Search インデックスを作成することもできます。アプリケーションで、検索インデックスの配列を定義します。そして、その配列を create_search_indexes()
メソッドのパラメーターとして渡します。
from pymongo.mongo_client import MongoClient from pymongo.operations import SearchIndexModel def create_indexes(): # Connect to your Atlas deployment uri = "<connectionString>" client = MongoClient(uri) # Access your database and collection database = client["<databaseName>"] collection = database["<collectionName>"] # Create your index models and add them to an array first_model = SearchIndexModel( definition={ # Add search index definition fields here }, name="<firstIndexName>", ) second_model = SearchIndexModel( definition={ # Add search index definition fields here }, name="<secondIndexName>", ) idx_models = [first_model, second_model] # Create the search indexes result = collection.create_search_indexes(models=idx_models) print(result)
次の値を指定して、ファイルを保存します。
Atlas 接続文字列。詳しくは、「ドライバーによる接続」を参照してください。
インデックスを作成するデータベースとコレクション。
インデックスの名前。インデックス名を省略すると、Atlas Search はインデックスに
default
という名前を付けます。
検索インデックスの定義。詳しくは「Atlas Search インデックス構文の確認」を参照してください。
アトラス検索インデックスを作成すると、アトラス検索ページにはAtlas Search インデックスに関する情報が表示されます。Status 列には、クラスターのプライマリノードにおけるインデックスの現在の状態が表示されます。詳細については、「インデックスステータスの確認」を参照してください。
警告
Atlas Search インデックスが既に存在するコレクションをシャーディングする場合、コレクションがシャードに表示され始めるときにクエリのダウンタイムが短時間発生することがあります。また、シャードを Atlas Search インデックスなどのシャーディングされたコレクションに追加する場合、追加されたシャードで最初の同期プロセスが完了するまで、そのコレクションに対する検索クエリは失敗します。詳しくは、「最初の同期プロセス」を参照してください。