Docs Menu

Atlas Search インデックスの作成

Atlas Search インデックスは、簡単に検索可能な形式でデータを分類するデータ構造であり、タームとタームを含むドキュメントの間をマッピングします。Atlas Search インデックスを使用すると、特定の識別子を使用してドキュメントをすばやく検索できます。Atlas Search を使用して Atlas クラスター内のデータをクエリするには、Atlas Search インデックスを構成する必要があります。

Atlas Search インデックスは、単一または複数のフィールドで作成できます。データのソートやフィルタリングによく使用するフィールドはインデックスを作成して、クエリ時に関連データを含むドキュメントをすばやく取得できるようにすることをお勧めします。

Atlas クラスター上の全コレクション(時系列コレクションを除く)を対象に Atlas Search インデックスを作成するには、Atlas UI、APIAtlas CLITerraform を使用します。

重要

$out 集計ステージを使用して Atlas Search インデックスを持つコレクションを変更する場合は、その Atlas Search インデックスを削除して再作成する必要があります。可能であれば、$out の代わりに $merge を使用することを検討してください。

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 クラスターが必要です。

コレクションのサブセットにインデックスを作成することで、インデックスのサイズを見積もることができます。

  1. データのサンプルを取得し、サンプル データを使用して新しいコレクションを作成します。

  2. サンプル データを使用してコレクションに検索インデックスを作成します。

    注意

    サンプル データのインデックス定義は、完全なコレクションに作成するインデックス定義と同じである必要があります。

  3. データの合計サイズに基づいて、サンプル データ インデックスのサイズをスケーリングします。

    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 UI または MongoDB Compass を使用します。また、mongosh、Atlas CLI、API のいずれかを使用するか、任意の言語でサポート対象の MongoDB ドライバーを使用してプログラム的にも作成できます。

注意

Atlas Search インデックスは、コレクションの一部ではなく、コレクション全体に適用する必要があります。


➤ [言語の選択]ドロップダウン メニューを使用して、このセクション内の例の言語を設定します。


Atlas Search インデックスを作成するには

1

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"
}
}
]
}
}'

このエンドポイントの構文とパラメータについて詳しくは、「作成」を参照してください。

2

注意

Atlas ではコレクションが存在しない場合はインデックスを作成しませんが、その場合も 200 ステータスを返します。

Atlas Search は、Atlas CLI を使用して作成したローカル Atlas 配置で使用することもできます。 詳細については、「 Atlas 配置のローカル配置の作成 」を参照してください。

Atlas CLI を使用してクラスターの検索インデックスを作成するには、次のコマンドを実行します。

atlas clusters search indexes create [indexName] [options]

コマンド構文とパラメーターの詳細については、Atlas CLI ドキュメントの「atlas clusters search indexes create」を参照してください。

Atlas CLI を使用して指定したデプロイの検索インデックスを作成するには、次のコマンドを実行します。

atlas deployments search indexes create [indexName] [options]

コマンド構文とパラメーターの詳細については、Atlas CLI ドキュメントの「atlas deployments search indexes create」を参照してください。

次の例は、 atlas clustersまたはatlas deploymentsコマンドを使用して、構成ファイルを使用して非対話型モードで Atlas Search インデックスを作成する方法を示しています。

1
{
"collectionName": "movies",
"database": "sample_mflix",
"definition": {
"mappings": {
"dynamic": true
},
},
"name": "searchIndex"
}
2
  1. 次のいずれかのコマンドを実行します。

    クラウド配置

    atlas clusters search indexes create --file indexDef.json

    ローカル配置:

    atlas deployments search indexes create --file indexDef.json
  2. 配置を指定し、Enter キーを押します。

$search クエリの場合、デフォルトの search タイプのインデックスを作成します。

Atlas UI から Atlas Search インデックスを作成するには、以下の手順を行います。

1
  1. まだ表示されていない場合は、希望するプロジェクトを含む組織を選択しますナビゲーション バーのOrganizationsメニュー

  2. まだ表示されていない場合は、ナビゲーション バーのProjectsメニューから目的のプロジェクトを選択します。

  3. まだ表示されていない場合は、サイドバーの [Clusters] をクリックします。

    [ Clusters (クラスター) ] ページが表示されます。

2

GoAtlas Searchページには、サイドバー、Data Explorer 、またはクラスターの詳細ページから できます。

  1. サイドバーで、 Services見出しの下のAtlas Searchをクリックします。

    注意

    クラスターがない場合は、Create clusterをクリックしてクラスターを作成してください。詳細については、「 クラスターの作成 」を参照してください。

  2. [ Select data sourceドロップダウンからクラスターを選択し、[ Go to Atlas Search ] をクリックします。

    Atlas Searchページが表示されます。

  1. クラスターの [Browse Collections] ボタンをクリックします。

  2. データベースを展開し、コレクションを選択します。

  3. コレクションのSearch Indexesタブをクリックします。

    Atlas Searchページが表示されます。

  1. クラスタの名前をクリックします。

  2. [Atlas Search] タブをクリックします。

    Atlas Searchページが表示されます。

3
4

ページで次の選択を行い、Next をクリックしてください。

Search Type

Atlas Search のインデックスタイプを選択します。

Index Name and Data Source

以下の情報を指定してください。

  • Index Name: default はデフォルトのインデックス名です。インデックス名は、インデックスの種類に関係なく、名前空間内で一意である必要があります。デフォルト名を承認するか、またはカスタム名を指定できます。デフォルト名を使用する場合、$search パイプライン ステージで index パラメータを指定する必要はありません。カスタム名を指定する場合は、このパラメーターを指定する必要があります。

  • Database and Collection:

    • インデックスを作成するデータベースを選択してください。

    • インデックスを作成するコレクションを選択してください。

Configuration Method

For a guided experience, select Visual Editor.

To edit the raw index definition, select JSON Editor.
5

デフォルトのインデックス定義を使用することも、カスタムのインデックス定義を指定することもできます。

  • デフォルトのインデックス定義は、ドキュメント内のフィールドを動的にマッピングしたもので、どのコレクションでも機能します。

  • カスタムのインデックス定義は静的マッピングです。インデックス、アナライザ、データ型にフィールドを指定します。

フィールド名
説明
必要性

Index Analyzer

コレクションのデータのインデックス作成に使用するアナライザを指定します。デフォルトでは、Atlas Search は標準アナライザ("lucene.standard")を使用します。

analyzer JSON 設定に対応します。

任意

Query Analyzer

テキストを検索する前にクエリ テキストに適用するアナライザを指定します。このフィールドを省略した場合、インデックスはデフォルトで以下の順序でアナライザを継承します。

  1. このフィールドのanalyzerオプション(指定されている場合)。

  2. インデックスsearchAnalyzerオプション(指定されている場合)。

  3. インデックスanalyzerオプション(指定されている場合)。

  4. lucene.standardアナライザ。

searchAnalyzer JSON 設定に対応します。

任意

Dynamic Mapping

フィールドの動的マッピングまたは静的マッピングを指定します。動的マッピングを無効にするには、"dynamic":Off に設定します。デフォルトでは、動的マッピングは有効になっています。動的マッピングを無効にする場合は、インデックスを作成するフィールドを指定する必要があります。動的マッピングと静的マッピングについて詳しくは、「Atlas Searchインデックス構文の確認」を参照してください。

mappings.dynamic JSON 設定に対応します。

必須

フィールド名
説明
必要性

analyzer

コレクションのデータのインデックス作成に使用するアナライザを指定します。デフォルトでは、Atlas Search は標準アナライザ("lucene.standard")を使用します。

任意

searchAnalyzer

テキストを検索する前にクエリ テキストに適用するアナライザを指定します。このフィールドを省略した場合、インデックスはデフォルトで以下の順序でアナライザを継承します。

  1. このフィールドのanalyzerオプション(指定されている場合)。

  2. インデックスsearchAnalyzerオプション(指定されている場合)。

  3. インデックスanalyzerオプション(指定されている場合)。

  4. lucene.standardアナライザ。

任意

mappings.dynamic

フィールドの動的マッピングまたは静的マッピングを指定します。動的マッピングを無効にするには、"dynamic":false に設定します。デフォルトでは、動的マッピングは有効になっています。動的マッピングを無効にする場合は、インデックスを作成するフィールドを指定する必要があります。動的マッピングと静的マッピングについて詳しくは、「Atlas Searchインデックス構文の確認」を参照してください。

必須

これらのインデックス定義設定について詳しくは、「Atlas Search インデックス構文の確認」を参照してください。

デフォルト設定に問題がなければ、先に進みます。Atlas Search インデックスを再定義する場合は、次の手順に進みます。

6
  1. 以下の設定のいずれかを変更するには [Refine Your Index] をクリックします。

    フィールド名
    説明
    必要性

    Field Mappings

    Index Configurations セクションの Dynamic Mapping が無効になっている場合は必須です。

    独自のフィールド マッピングを定義することは、上級ユーザーのみにおすすめします。

    インデックスを作成するフィールドを指定します。フィールドを追加するには、次の操作を行う必要があります。

    1. Add FieldをクリックするとAdd Field Mappingウィンドウが開きます。

    2. フィールドに関する次の情報を指定します。

      • Field name - インデックスを作成するフィールドの名前。

      • Data Type Configuration - フィールドのデータ型。サポートされているデータ型とそのオプションについて詳しくは、「データ型」を参照してください。

      • Enable Dynamic Mapping - ドキュメントおよび埋め込みドキュメント型のフィールドに使用する静的または動的マッピング。動的マッピングを無効にすると、フィールドのデータは自動的にインデックス化されません。

    3. [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 と指定したフィールドをストアします。フィールドを指定するには、次の手順を実行します。

      1. Field Name 列のドロップダウンから、Atlas Search に保存するフィールドを選択します。

      2. [Add] をクリックして、保存するフィールドのリストにフィールドを追加します。

      3. [Add Field] をクリックして、リストに追加するフィールドごとに手順 ab を繰り返します。

      4. (任意)次のいずれかをクリックします。

        • Edit 別のフィールドを選択します。

        • Delete 保存するフィールドのリストからフィールドを削除します。

    • All Except Specified - 選択すると、Atlas Search は特定のフィールドを Atlas Search のストレージから除外します。

      1. Field Name 列のドロップダウンから、除外するフィールドを選択します。

      2. [Add] をクリックして、除外するフィールドのリストにフィールドを追加します。

      3. [Add Field] をクリックして、リストから除外するフィールドごとに手順 ab を繰り返します。

      4. (任意)次のいずれかをクリックします。

        • Edit 別のフィールドを選択します。

        • Delete 除外するフィールドのリストからフィールドを削除します。

    フィールドの保存の詳細については、「Atlas Search インデックスに保存されたソース フィールドの定義」を参照してください。

    storedSource JSON 設定に対応します。

    任意

    Synonyms Mappings

    インデックスで使用するシノニム マッピングを指定します。詳しくは、「Atlas Searchインデックスでのシノニム マッピングの定義」を参照してください。

    シノニム マッピングを追加するには、シノニムごとに次の設定を指定する必要があります。

    synonyms JSON 設定に対応します。

    任意。

    Index Partitions

    フィールドオブジェクトが 2.1 00 億を超える場合に使用するパーティションの数。

    numPartitions JSON 設定に対応します。

    重要

    numPartitionsオプションはプレビュー機能として利用できます。

    任意。

  2. [Save Changes] をクリックします。

  1. 次のいずれかの設定をインデックスに追加します。

    フィールド名
    説明
    必要性

    mappings.fields

    mappings.dynamicfalseの場合は必須です。

    独自のフィールド マッピングを定義することは、上級ユーザーのみにおすすめします。

    インデックスを作成するフィールドを指定します。詳しくは「フィールドマッピングの定義」を参照してください。

    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 インデックス構文の確認」を参照してください。

  2. [Next] をクリックします。

7

注意

Visual Editor を使用しており、インデックス定義に静的マッピングが含まれている場合は、インデックス定義をドラフトとして保存できます。デフォルトのインデックス定義を下書きとして保存することはできません。下書きとして保存できるのは、カスタムのインデックス定義のみです。

  1. [Cancel] をクリックします。

  2. [Save Draft] または [Delete Draft] をクリックします。

    重要

    保留中のインデックス ドラフトがある場合は、インデックスを新規作成できません。

    インデックス ドラフトを使用したインデックスの作成方法について詳しくは、「Atlas Search インデックス ドラフトの再開または削除」を参照してください。

8

Atlas はインデックスが構築中であることを知らせるトースト(短時間の非インタラクティブ通知)を表示します。

9

新規作成したインデックスは Atlas Search タブに表示されます。インデックスを作成する間、Status フィールドには Build in Progress と表示されます。インデックスの作成が完了すると、Status フィールドの表示は Active になります。

注意

コレクションが大きいほど、インデックスの作成に時間がかかります。インデックスの作成が完了すると、メール通知が届きます。

このビデオ チュートリアルでは、複雑度がさまざまに異なる Atlas Search インデックスの作成方法を紹介します。

所要時間: 15 分

mongosh を通じて Atlas Search インデックスを作成するには以下の手順を行います。

1

詳しくは、「 mongosh経由で接続 」を参照してください。

2

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
1

Compass を開き、Atlas クラスターに接続します。接続の詳細な手順については、「Compass 経由での接続」を参照してください。

2

Database 画面で、データベースの名前をクリックし、コレクションの名前をクリックします。

3
  1. [ Indexesタブをクリックし、[ ] を選択します。Search Indexes

  2. [ Create Indexをクリックして、インデックス作成ダイアログボックスを開きます。

  3. インデックスの名前を指定し、検索インデックスの定義を指定します。

    インデックス名

    default

    インデックスの定義

    {
    mappings: { dynamic: true }
    }
  4. [Create Search Index] をクリックします。

C ドライバーを使用して Atlas Search インデックスを作成するには、アプリケーションで検索インデックスを定義し、mongoc_collection_command_simple() メソッドを呼び出します。

注意

Atlas Search インデックス マネジメントのメソッドは非同期で実行されます。ドライバー メソッドは、正常に実行されたことを確認する前に戻ることができます。検索インデックスの現在のステータスを判別するには、$listSearchIndexes パイプライン ステージで集計操作を実行します。

1
2

次のサンプルアプリケーションでは、createSearchIndexes コマンドを指定して、コレクション内のフィールドに動的にインデックスを付ける検索インデックスを定義します。次に、アプリケーションはコマンドと検索インデックス情報を BSON に変換し、この情報を mongoc_collection_command_simple() メソッドに渡して検索インデックスを作成します。詳しくは「Atlas Search インデックス構文の確認」を参照してください。

#include <mongoc/mongoc.h>
#include <stdlib.h>
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() メソッドを呼び出して検索インデックスを作成します。

#include <mongoc/mongoc.h>
#include <stdlib.h>
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;
}
3
  • Atlas 接続文字列。詳しくは、「ドライバーによる接続」を参照してください。

  • インデックスを作成するデータベースとコレクション。

  • インデックスの名前。インデックス名を省略すると、Atlas Search はインデックスに default という名前を付けます。

4
gcc -o create-index create-index.c $(pkg-config --libs --cflags libmongoc-1.0)
./create-index

C++ ドライバーを使用して Atlas Search インデックスを作成するには、アプリケーションで検索インデックスを定義し、create_one() メソッドを呼び出します。

注意

Atlas Search インデックスマネジメントのメソッドは非同期で実行されます。ドライバーメソッドは、正常に実行されたことを確認する前に戻ることができます。検索インデックスの現在の状態を確認するには、検索インデックスビューのインスタンスで list() メソッドを呼び出します。

1
2

次のサンプルアプリケーションでは、検索インデックスの名前と定義を search_index_model() メソッドに渡して、コレクション内のフィールドに動的にインデックスを付けます。次に、アプリケーションは検索インデックスの仕様を create_one() メソッドに渡して検索インデックスを作成します。詳しくは「Atlas Search インデックス構文の確認」を参照してください。

#include <bsoncxx/builder/basic/document.hpp>
#include <bsoncxx/builder/basic/kvp.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/search_index_view.hpp>
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() メソッドに渡して検索インデックスを作成します。

#include <bsoncxx/builder/basic/document.hpp>
#include <bsoncxx/builder/basic/kvp.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/search_index_view.hpp>
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;
}
3
  • Atlas 接続文字列。詳しくは、「ドライバーによる接続」を参照してください。

  • インデックスを作成するデータベースとコレクション。

  • インデックスの名前。インデックス名を省略すると、Atlas Search はインデックスに default という名前を付けます。

4
g++ -o create-index create-index.cpp $(pkg-config --cflags --libs libmongocxx)
./create-index

.NET/C# ドライバーを使用して MongoDB Atlas Search 検索インデックスを作成するには、次の手順を行います。

  1. インデックスを定義する BsonDocument を構築します。

  2. BsonDocumentCreateOne() またはCreateOneAsync() メソッドに渡します。

次のサンプル アプリケーションでは、コレクション内のフィールドに動的にインデックスを付ける検索インデックスを定義し、CreateOne() メソッドを実行してインデックスを作成します。詳しくは、「Atlas Search インデックス構文の確認」を参照してください。

1
  1. 以下のコマンドを実行して、csharp-create-index という新しいディレクトリを作成します。

    mkdir csharp-create-index
  2. 以下のコマンドを実行して、新しいディレクトリに変更します。

    cd csharp-create-index
  3. 以下のコマンドを実行して、プロジェクトを初期化します。

    dotnet new console
2

次のコマンドを実行します:

dotnet add package MongoDB.Driver
3

以下の例のプレースホルダー値を置き換えます。

説明

<connection-string>

Atlas 接続文字列。詳しくは、「ドライバーによる接続」を参照してください。

<databaseName>

インデックスを作成するデータベース。

<collectionName>

インデックスを作成するコレクション。

<IndexName>

インデックスの名前。インデックス名を省略すると、Atlas Search はインデックスに default という名前を付けます。

Program.cs
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);
4

以下のコマンドを使用して、プロジェクトを実行します。

dotnet run csharp-create-index.csproj
default

複数の Atlas Search インデックスを一括で作成する方法

  1. 検索インデックスの定義を含む IEnumerable<CreateSearchIndexModel> インスタンスを構築します。

  2. CreateMany() またはCreateManyAsync() メソッドにコレクションを渡します。

次の例は、CreateMany() メソッドを使用して複数のインデックスを作成する方法を示しています。

1
  1. 以下のコマンドを実行して、csharp-create-index という新しいディレクトリを作成します。

    mkdir csharp-create-index-mult
  2. 以下のコマンドを実行して、新しいディレクトリに変更します。

    cd csharp-create-index-mult
  3. 以下のコマンドを実行して、プロジェクトを初期化します。

    dotnet new console
2

次のコマンドを実行します:

dotnet add package MongoDB.Driver
3

以下の例のプレースホルダー値を置き換えます。

説明

<connection-string>

Atlas 接続文字列。詳しくは、「ドライバーによる接続」を参照してください。

<databaseName>

インデックスを作成するデータベース。

<collectionName>

インデックスを作成するコレクション。

<first-index-name>

最初のインデックスの名前。

<last-index-name>

最後のインデックスの名前。

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);
4

以下のコマンドを使用して、プロジェクトを実行します。

dotnet run csharp-create-index-mult.csproj
default

Tip

API ドキュメント

このページのメソッドについて詳しくは、.NET/C# ドライバー用の APIドキュメント を参照してください。

Java ドライバーを使用して Atlas Search インデックスを作成するには、検索インデックスを定義するドキュメントを作成し、そのドキュメントを createSearchIndex() または createSearchIndexes() メソッドに渡します。詳しくは「ドライバーのドキュメント」を参照してください。

注意

Atlas Search インデックス マネジメントのメソッドは非同期で実行されます。ドライバー メソッドは、正常に実行されたことを確認する前に戻ることができます。インデックスの現在のステータスを確認するには、listSearchIndexes() メソッドを呼び出します。

1
2

次のサンプルアプリケーションでは、コレクション内のフィールドに動的インデックスを付ける検索インデックスを定義し、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));
}
}
}
3
  • Atlas 接続文字列。詳しくは、「ドライバーによる接続」を参照してください。

  • インデックスを作成するデータベースとコレクション。

  • インデックスの名前。インデックス名を省略すると、Atlas Search はインデックスに default という名前を付けます。

4
javac CreateIndex.java
java CreateIndex

ノード ドライバーを使用して Atlas Search インデックスを作成する方法

  1. アプリケーションから検索インデックスを定義します。

  2. createSearchIndex または createSearchIndexes ヘルパー メソッドを実行します。

次の create-index.js という名前のサンプル アプリケーションでは、コレクション内のフィールドに動的にインデックスを付けるための検索インデックスを定義し、createSearchIndex コマンドを実行してインデックスを作成します。詳しくは「Atlas Search インデックス構文の確認」を参照してください。

1
2

以下の例のプレースホルダー値を置き換えます。

説明

<connection-string>

Atlas 接続文字列。詳しくは、「ドライバーによる接続」を参照してください。

<databaseName>

インデックスを作成するデータベース。

<collectionName>

インデックスを作成するコレクション。

<index-name>

インデックスの名前。 インデックス名を省略すると、Atlas Search はインデックスにdefaultという名前を付けます。

create-index.js
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);
3

以下のコマンドを使用します。

node create-index.js
<index-name>

複数の Atlas Search インデックスを一括で作成する方法

  1. アプリケーションで、検索インデックスの配列を定義します。

  2. 配列を createSearchIndexes コマンドに渡します。

以下の例は、createSearchIndexes コマンドを使用して複数のインデックスを作成する方法を示しています。

1
2

以下の例のプレースホルダー値を置き換えます。

説明

<connection-string>

Atlas 接続文字列。詳しくは、「ドライバーによる接続」を参照してください。

<databaseName>

インデックスを作成するデータベース。

<collectionName>

インデックスを作成するコレクション。

<first-index-name>

最初のインデックスの名前。

<last-index-name>

最後のインデックスの名前。

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);
3

以下のコマンドを使用します。

node create-index-mult.js
<index-name>

Python ドライバーを使用して Atlas Search インデックスを作成するには、アプリケーションから検索インデックスを定義し、create_search_index() メソッドを呼び出します。

注意

Atlas Search インデックス マネジメントのメソッドは非同期で実行されます。ドライバー メソッドは、正常に実行されたことを確認する前に戻ることができます。検索インデックスの現在のステータスを確認するには、コレクションで list_search_indexes() メソッドを呼び出します。

1
2

次のサンプル アプリケーションでは、コレクション内のフィールドに動的にインデックスを付ける検索インデックスを定義します。次に、アプリケーションはコレクションの 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)
3
  • Atlas 接続文字列。詳しくは、「ドライバーによる接続」を参照してください。

  • インデックスを作成するデータベースとコレクション。

  • インデックスの名前。インデックス名を省略すると、Atlas Search はインデックスに default という名前を付けます。

4
python create_index.py

アトラス検索インデックスを作成すると、アトラス検索ページにはAtlas Search インデックスに関する情報が表示されます。Status 列には、クラスターのプライマリノードにおけるインデックスの現在の状態が表示されます。詳細については、「インデックスステータスの確認」を参照してください。

警告

Atlas Search インデックスが既に存在するコレクションをシャーディングする場合、コレクションがシャードに表示され始めるときにクエリのダウンタイムが短時間発生することがあります。また、シャードを Atlas Search インデックスなどのシャーディングされたコレクションに追加する場合、追加されたシャードで最初の同期プロセスが完了するまで、そのコレクションに対する検索クエリは失敗します。詳しくは、「最初の同期プロセス」を参照してください。