For AI agents: a documentation index is available at https://www.mongodb.com/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.
Docs Menu

Define Synonym Mappings in Your MongoDB Search Index

The synonyms option in a MongoDB Search index definition specifies synonym mappings that allow you to index and search your collection for words that have the same or nearly the same meaning. To configure a MongoDB Search index with synonym mappings, you must:

  1. Add a collection of synonym documents to your cluster. Ensure that:

    • Your collection is in the same database as the index that will reference the collection

    • The documents are properly formatted

  2. Reference the synonym source collection in a synonym mapping in the index definition.

A synonym mapping configures a MongoDB Search index to support queries that apply synonyms from a synonym source collection in the same database as the collection you are indexing. You can use synonyms only in queries that use the text or phrase operator.

Note

Free (M0) Tier Cluster Limitation

An index definition can have only one synonym mapping.

This page describes the format of the synonyms source collection and how to define synonym mappings that reference the synonym source collection in your MongoDB Search index.

synonyms has the following syntax in an index definition:

Syntax
1{
2 "synonyms": [
3 {
4 "name": "<synonym-mapping-name>",
5 "source": {
6 "collection": "<source-collection-name>"
7 },
8 "analyzer": "<synonym-mapping-analyzer>"
9 }
10 ]
11}

synonyms takes the following fields in an index definition:

Field
Type
Description
Necessity

analyzer

string

Name of the analyzer to use with this synonym mapping.

You can use a synonym mapping to query only fields analyzed with the same analyzer.

To use synonyms with stop words, you must either index the field using the Standard Analyzer or add the synonym entry without the stop word.

You can use any MongoDB Search analyzer except the following:

Language analyzers:

  • lucene.kuromoji

  • lucene.cjk

Custom analyzer tokenizers and token filters:

Required

name

string

Name of the synonym mapping. Name must be unique in the index definition. Value can't be an empty string.

Required

source

document

Source collection for synonyms. The source option takes the collection field.

Required

source.collection

string

Name of the MongoDB collection that is in the same database as the MongoDB Search index. Documents in this collection must be in the format described in the Synonyms Source Collection Documents.

Required

Each document in the collection specified as the source for the synonyms describe how one or more words map to one or more synonyms of those words.

Note

On free clusters, the synonyms collection can't exceed 10,000 documents.

You must configure each document with the following fields:

Field
Type
Description
Necessity

input

array of strings

Required for mappingType: explicit mappings.

For explicit mappings, synonyms values are synonyms of each input token. Value can't be an empty or all-whitespace string. You can specify the same input value in multiple documents.

Conditional

mappingType

string

Type of mapping. Value can be one of the following:

  • equivalent - describes a set of tokens that are equivalent to one another. For an example of this mappingType, see Example.

  • explicit - matches input tokens and replaces them with all alternative synonyms tokens. For an example of this mappingType, see Example.

Required

synonyms

array of strings

Words that are synonyms of one another if mappingType is equivalent or synonyms of input tokens if mappingType is explicit. synonyms must have at least one value.

To use synonyms with stop words, you must either add the synonym entry without the stop word or index the field using the Standard Analyzer.

For an example of each mappingType see Source Collection Document Examples.

Required

The documents in the collection can contain other fields. The documents in the collection are additive, and mappings are deduplicated. MongoDB Search synonyms are stored as a separate Atlas collection, which counts against the same storage quota as any other collection in Atlas. MongoDB Search might use more compute resources to apply synonyms from larger synonyms source collections.

Warning

Don't include invalid synonym documents in the synonym source collection. MongoDB Search doesn't create indexes if the indexes use synonym mappings that reference collections with invalid documents. Only include synonym documents that are properly formatted in your synonym source collection.

MongoDB doesn't recommend adding synonym documents to synonym source collections in a production environment without first validating that they are properly formatted and behave as expected in a test environment.

If you make changes to your synonyms source collection:

  • You don't need to reindex because MongoDB Search watches for changes and automatically updates its internal synonym map.

  • The time it takes MongoDB Search to update the synonym mappings increases with the synonym source collection size. Note that the changes to synonym documents are reflected in your MongoDB Search query results eventually.

Atlas provides the documents for the following MongoDB Search mapping type examples in a collection named sample_synonyms. You can load these documents on your cluster in the same database as your collection. To load these documents on your cluster, when you create the index for your collection, do the following:

  1. When you select the Configuration Method, select the Visual Editor.

  2. When you Add synonym mapping to your index, select Load sample collection from the Synonym source collection dropdown.

In the following example source collection document, the mappingType is set to equivalent so that the tokens car, vehicle, and automobile are configured to be synonyms of one another.

{
"mappingType": "equivalent",
"synonyms": ["car", "vehicle", "automobile"]
}

For a text query for car, vehicle, or automobile applying a synonym mapping that includes such a document, MongoDB Search returns documents that contain the term car, vehicle, or automobile.

In the following example source collection document, mappingType is set to explicit so that the tokens beer, brew, and pint are configured to be synonyms of the input token beer.

{
"mappingType": "explicit",
"input": ["beer"],
"synonyms": ["beer", "brew", "pint"]
}

For a text query for beer applying a synonym mapping that includes such a document, MongoDB Search returns documents that contain the terms "beer", "brew", or "pint" because the input token beer is explicitly mapped to all these synonyms tokens. However, for a query for pint, MongoDB Search does not find documents that contain beer because pint is not explicitly mapped to beer.

The following collection named synonymous_terms is an example synonym source collection that can be used with the movies collection in the sample_mflix database.

The sample_mflix.synonymous_terms collection contains the following documents:

{
"mappingType": "equivalent",
"synonyms": ["car", "vehicle", "automobile"]
}
{
"mappingType": "explicit",
"input": ["race"],
"synonyms": ["contest", "rally"]
}
{
"mappingType": "equivalent",
"synonyms": ["dress", "apparel", "attire"]
}
{
"mappingType": "explicit",
"input": ["boat"],
"synonyms": ["vessel", "sail"]
}

The following examples for the sample_mflix.movies collection create index definitions that use static and dynamic mappings. These examples use the synonymous_terms synonym source collection described in the Synonym Source Collection Example section to enable synonym mappings.

This example performs the following actions:

  • Configures an index with a single text field and a single synonym mapping definition that uses the mapping configured in the synonymous_terms collection.

  • Analyzes the plot field with the lucene.english analyzer.

  • Enables synonyms from the synonymous_terms collection for queries on fields analyzed with the lucene.english analyzer.

You can use the Atlas Administration API to configure the index. Replace the following values in the sample curl command:

  • Replace {ACCESS-TOKEN} with your Service Account access token. To learn how to generate an access token, see Make an API (Application Programming Interface) Request.

  • Replace {groupId} with the project ID of the project where you want to create the MongoDB Search index.

  • Replace {clusterName} with the name of the cluster where you want to create the MongoDB Search index.

1curl --header "Authorization: Bearer ${ACCESS_TOKEN}" \
2 --header "Accept: application/vnd.atlas.2025-03-12+json" \
3 --header "Content-Type: application/json" \
4 -X POST "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes" \
5 -d '{ "collectionName": "movies",
6 "database": "sample_mflix",
7 "name": "default",
8 "type": "search",
9 "definition": {
10 "mappings": {
11 "dynamic": false,
12 "fields": {
13 "plot": {
14 "type": "string",
15 "analyzer": "lucene.english"
16 }
17 }
18 },
19 "synonyms": [
20 {
21 "analyzer": "lucene.english",
22 "name": "my_synonyms",
23 "source": {
24 "collection": "synonymous_terms"
25 }
26 }
27 ]
28 }
29 }'

This example performs the following actions:

  • Configures an index for all document fields and a single synonym mapping definition that uses the mapping configured in the synonymous_terms collection.

  • Uses the default analyzer, lucene.standard, to analyze all the fields.

  • Enables synonyms from the synonymous_terms collection for queries on fields analyzed with the lucene.standard analyzer.

You can use the Atlas Administration API to configure the index. Replace the following values in the sample curl command:

  • Replace {ACCESS-TOKEN} with your Service Account access token. To learn how to generate an access token, see Make an API (Application Programming Interface) Request.

  • Replace {groupId} with the project ID of the project where you want to create the MongoDB Search index.

  • Replace {clusterName} with the name of the cluster where you want to create the MongoDB Search index.

1curl --header "Authorization: Bearer ${ACCESS_TOKEN}" \
2 --header "Accept: application/vnd.atlas.2025-03-12+json" \
3 --header "Content-Type: application/json" \
4 -X POST "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes" \
5 -d '{ "collectionName": "movies",
6 "database": "sample_mflix",
7 "name": "default",
8 "type": "search",
9 "definition": {
10 "mappings": {
11 "dynamic": true
12 },
13 "synonyms": [
14 {
15 "analyzer": "lucene.standard",
16 "name": "my_synonyms",
17 "source": {
18 "collection": "synonymous_terms"
19 }
20 }
21 ]
22 }
23 }'

To learn how to add a collection that configures words as synonyms to your cluster, and use this collection to create a MongoDB Search index and run MongoDB Search queries using synonyms, see How to Use Synonyms with MongoDB Search.

To see examples of text queries that use synonyms, see Synonyms Examples in the text reference page.

To see an example phrase queries that uses synonyms, see Synonyms Example in the phrase reference page.

The following examples for the sample_mflix.movies collection create index definitions that use static and dynamic mappings. These examples use the synonymous_terms synonym source collection described in the Synonym Source Collection Example section to enable synonym mappings.

This example performs the following actions:

  • Configures an index with a single text field and a single synonym mapping definition that uses the mapping configured in the synonymous_terms collection.

  • Analyzes the plot field with the lucene.english analyzer.

  • Enables synonyms from the synonymous_terms collection for queries on fields analyzed with the lucene.english analyzer.

1
static-index.json
1{
2 "name": "default",
3 "collectionName": "movies",
4 "database": "sample_mflix",
5 "mappings": {
6 "dynamic": false,
7 "fields": {
8 "plot": {
9 "type": "string",
10 "analyzer": "lucene.english"
11 }
12 }
13 },
14 "synonyms": [
15 {
16 "analyzer": "lucene.english",
17 "name": "my_synonyms",
18 "source": {
19 "collection": "synonymous_terms"
20 }
21 }
22 ]
23}
2

In your terminal, connect to your cluster from the Atlas CLI. To learn more, see Connect from the Atlas CLI.

3

Run the atlas clusters search indexes create command in your terminal, replacing <clusterName> with the name of the cluster, and <path-to-file> with the path to the static-index.json file:

1atlas clusters search indexes create <clusterName> --file <path-to-file>

This example performs the following actions:

  • Configures an index for all document fields and a single synonym mapping definition that uses the mapping configured in the synonymous_terms collection.

  • Uses the default analyzer, lucene.standard, to analyze all the fields.

  • Enables synonyms from the synonymous_terms collection for queries on fields analyzed with the lucene.standard analyzer.

1
dynamic-index.json
1{
2 "name": "default",
3 "collectionName": "movies",
4 "database": "sample_mflix",
5 "mappings": {
6 "dynamic": true
7 },
8 "synonyms": [
9 {
10 "analyzer": "lucene.standard",
11 "name": "my_synonyms",
12 "source": {
13 "collection": "synonymous_terms"
14 }
15 }
16 ]
17}
2

In your terminal, connect to your cluster from the Atlas CLI. To learn more, see Connect from the Atlas CLI.

3

Run the atlas clusters search indexes create command in your terminal, replacing <clusterName> with the name of the cluster, and <path-to-file> with the path to the dynamic-index.json file:

1atlas clusters search indexes create <clusterName> --file <path-to-file>

To learn how to add a collection that configures words as synonyms to your cluster, and use this collection to create a MongoDB Search index and run MongoDB Search queries using synonyms, see How to Use Synonyms with MongoDB Search.

To see examples of text queries that use synonyms, see Synonyms Examples in the text reference page.

To see an example phrase queries that uses synonyms, see Synonyms Example in the phrase reference page.

The following examples for the sample_mflix.movies collection create index definitions that use static and dynamic mappings. These examples use the synonymous_terms synonym source collection described in the Synonym Source Collection Example section to enable synonym mappings.

This example performs the following actions:

  • Configures an index with a single text field and a single synonym mapping definition that uses the mapping configured in the synonymous_terms collection.

  • Analyzes the plot field with the lucene.english analyzer.

  • Enables synonyms from the synonymous_terms collection for queries on fields analyzed with the lucene.english analyzer.

1

Open Compass and connect to your cluster. For detailed instructions, see Connect to a Cluster via Compass.

2

On the Database screen, click the sample_mflix database, then click the name of the movies collection.

3
  1. Click the Indexes tab, then select Search Indexes.

  2. Click Create Atlas Search Index to open the index creation dialog box.

  3. Specify a name for the index.

    Your MongoDB Search index is named default by default. If you keep this name, then your index will be the default Search index for any MongoDB Search query that does not specify a different index option in its operators. If you are creating multiple indexes, we recommend that you maintain a consistent, descriptive naming convention across your indexes.

  4. Specify the JSON MongoDB Search index definition.

    1{
    2 "mappings": {
    3 "dynamic": false,
    4 "fields": {
    5 "plot": {
    6 "type": "string",
    7 "analyzer": "lucene.english"
    8 }
    9 }
    10 },
    11 "synonyms": [
    12 {
    13 "analyzer": "lucene.english",
    14 "name": "my_synonyms",
    15 "source": {
    16 "collection": "synonymous_terms"
    17 }
    18 }
    19 ]
    20}
  5. Click Create Search Index.

This example performs the following actions:

  • Configures an index for all document fields and a single synonym mapping definition that uses the mapping configured in the synonymous_terms collection.

  • Uses the default analyzer, lucene.standard, to analyze all the fields.

  • Enables synonyms from the synonymous_terms collection for queries on fields analyzed with the lucene.standard analyzer.

1

Open Compass and connect to your cluster. For detailed instructions, see Connect to a Cluster via Compass.

2

On the Database screen, click the sample_mflix database, then click the name of the movies collection.

3
  1. Click the Indexes tab, then select Search Indexes.

  2. Click Create Atlas Search Index to open the index creation dialog box.

  3. Specify a name for the index.

    Your MongoDB Search index is named default by default. If you keep this name, then your index will be the default Search index for any MongoDB Search query that does not specify a different index option in its operators. If you are creating multiple indexes, we recommend that you maintain a consistent, descriptive naming convention across your indexes.

  4. Specify the JSON MongoDB Search index definition.

    1{
    2 "mappings": {
    3 "dynamic": true
    4 },
    5 "synonyms": [
    6 {
    7 "analyzer": "lucene.standard",
    8 "name": "my_synonyms",
    9 "source": {
    10 "collection": "synonymous_terms"
    11 }
    12 }
    13 ]
    14}
  5. Click Create Search Index.

To learn how to add a collection that configures words as synonyms to your cluster, and use this collection to create a MongoDB Search index and run MongoDB Search queries using synonyms, see How to Use Synonyms with MongoDB Search.

To see examples of text queries that use synonyms, see Synonyms Examples in the text reference page.

To see an example phrase queries that uses synonyms, see Synonyms Example in the phrase reference page.

The following examples for the sample_mflix.movies collection create index definitions that use static and dynamic mappings. These examples use the synonymous_terms synonym source collection described in the Synonym Source Collection Example section to enable synonym mappings.

This example performs the following actions:

  • Configures an index with a single text field and a single synonym mapping definition that uses the mapping configured in the synonymous_terms collection.

  • Analyzes the plot field with the lucene.english analyzer.

  • Enables synonyms from the synonymous_terms collection for queries on fields analyzed with the lucene.english analyzer.

1

In your terminal, connect to your Atlas cloud-hosted deployment or local deployment from mongosh. For detailed instructions on how to connect, see Connect to a Deployment.

2
use sample_mflix
switched to db sample_mflix
3
1db.movies.createSearchIndex(
2 "default",
3 {
4 "mappings": {
5 "dynamic": false,
6 "fields": {
7 "plot": {
8 "type": "string",
9 "analyzer": "lucene.english"
10 }
11 }
12 },
13 "synonyms": [
14 {
15 "analyzer": "lucene.english",
16 "name": "my_synonyms",
17 "source": {
18 "collection": "synonymous_terms"
19 }
20 }
21 ]}
22)
default

This example performs the following actions:

  • Configures an index for all document fields and a single synonym mapping definition that uses the mapping configured in the synonymous_terms collection.

  • Uses the default analyzer, lucene.standard, to analyze all the fields.

  • Enables synonyms from the synonymous_terms collection for queries on fields analyzed with the lucene.standard analyzer.

1

In your terminal, connect to your Atlas cloud-hosted deployment or local deployment from mongosh. For detailed instructions on how to connect, see Connect to a Deployment.

2
use sample_mflix
switched to db sample_mflix
3
1db.movies.createSearchIndex(
2 "default",
3 {
4 "mappings": {
5 "dynamic": true
6 },
7 "synonyms": [
8 {
9 "analyzer": "lucene.standard",
10 "name": "my_synonyms",
11 "source": {
12 "collection": "synonymous_terms"
13 }
14 }
15 ]}
16)
default

To learn how to add a collection that configures words as synonyms to your cluster, and use this collection to create a MongoDB Search index and run MongoDB Search queries using synonyms, see How to Use Synonyms with MongoDB Search.

To see examples of text queries that use synonyms, see Synonyms Examples in the text reference page.

To see an example phrase queries that uses synonyms, see Synonyms Example in the phrase reference page.

The following examples for the sample_mflix.movies collection create index definitions that use static and dynamic mappings. These examples use the synonymous_terms synonym source collection described in the Synonym Source Collection Example section to enable synonym mappings.

This example performs the following actions:

  • Configures an index with a single text field and a single synonym mapping definition that uses the mapping configured in the synonymous_terms collection.

  • Analyzes the plot field with the lucene.english analyzer.

  • Enables synonyms from the synonymous_terms collection for queries on fields analyzed with the lucene.english analyzer.

You can use the Visual Editor or the JSON Editor in the Atlas UI to configure the following index. To configure this index, after you select your configuration method, select the movies collection in the sample_mflix database.

  1. Click Refine Your Index.

  2. In the Field Mappings section, click Add Field.

  3. Click Customized Configuration.

  4. Configure the following settings in the Add Field Mapping window:

    Field Name
    Enable Dynamic Mapping
    Data Type Configuration

    Select plot.

    Toggle to disable.

    1. Click Add Data Type.

    2. Select String from the dropdown.

    3. Select lucene.english under lucene.language from the Index Analyzer dropdown.

  5. Click Add.

  6. In the Synonyms Mappings section, click Add Synonym Mapping.

  7. Configure the following settings in the Add Synonym Mapping window:

    Synonym mapping name
    Synonym source collection
    Analyzer

    Enter my_synonyms

    Select synonymous_terms.

    Select lucene.english under lucene.language from dropdown.

  8. Click Add.

This example performs the following actions:

  • Configures an index for all document fields and a single synonym mapping definition that uses the mapping configured in the synonymous_terms collection.

  • Uses the default analyzer, lucene.standard, to analyze all the fields.

  • Enables synonyms from the synonymous_terms collection for queries on fields analyzed with the lucene.standard analyzer.

You can use the Visual Editor or the JSON Editor in the Atlas UI to configure the following index. To configure this index, after you select your configuration method, select the movies collection in the sample_mflix database.

  1. Click Refine Your Index.

  2. In the Synonyms Mappings section, click Add Synonym Mapping.

  3. Configure the following settings in the Add Synonym Mapping window:

    Synonym mapping name
    Synonym source collection
    Analyzer

    Enter my_synonyms

    Select synonymous_terms.

    Select lucene.standard from the dropdown if it isn't already selected.

  4. Click Add.

To learn how to add a collection that configures words as synonyms to your cluster, and use this collection to create a MongoDB Search index and run MongoDB Search queries using synonyms, see How to Use Synonyms with MongoDB Search.

To see examples of text queries that use synonyms, see Synonyms Examples in the text reference page.

To see an example phrase queries that uses synonyms, see Synonyms Example in the phrase reference page.

The following examples for the sample_mflix.movies collection create index definitions that use static and dynamic mappings. These examples use the synonymous_terms synonym source collection described in the Synonym Source Collection Example section to enable synonym mappings.

This example performs the following actions:

  • Configures an index with a single text field and a single synonym mapping definition that uses the mapping configured in the synonymous_terms collection.

  • Analyzes the plot field with the lucene.english analyzer.

  • Enables synonyms from the synonymous_terms collection for queries on fields analyzed with the lucene.english analyzer.

1

To learn how to install the driver and configure your C application, see the Get Started tutorial in the MongoDB C Driver documentation.

2

Create a create-static-index.c file in your application directory, and copy and paste the following code into the file.

create-static-index.c
1#include <mongoc/mongoc.h>
2#include <stdio.h>
3
4int main(int argc, char *argv[]) {
5 mongoc_client_t *client;
6 mongoc_collection_t *collection;
7 bson_error_t error;
8 bson_t cmd;
9 bson_t *index_definition;
10 bool success;
11
12 /* Initialize the MongoDB C Driver. */
13 mongoc_init();
14
15 /* Connect to your MongoDB deployment. */
16 client = mongoc_client_new("<connection-string>");
17 collection = mongoc_client_get_collection (client, "sample_mflix", "movies");
18
19 if (!client) {
20 fprintf(stderr, "Failed to create client.\n");
21 return 1;
22 }
23
24 /* Create the MongoDB Search index definition for the plot field with synonyms. */
25 char *cmd_str = bson_strdup_printf (
26 BSON_STR ({
27 "createSearchIndexes": "%s",
28 "indexes": [{
29 "name": "default",
30 "definition": {
31 "mappings": {
32 "dynamic": false,
33 "fields": {
34 "plot": {
35 "type": "string",
36 "analyzer": "lucene.english"
37 }
38 }
39 },
40 "synonyms": [
41 {
42 "analyzer": "lucene.english",
43 "name": "my_synonyms",
44 "source": {
45 "collection": "synonymous_terms"
46 }
47 }
48 ]
49 }
50 }]
51 }),
52 "movies"
53 );
54 bson_init_from_json (&cmd, cmd_str, -1, &error);
55 bson_free (cmd_str);
56
57 if (mongoc_collection_command_simple (collection, &cmd, NULL, NULL, &error)) {
58 printf ("Index created!\n");
59 } else {
60 fprintf (stderr, "Failed to create search index: %s", error.message);
61 }
62
63 /* Clean up. */
64 bson_destroy (&cmd);
65 mongoc_collection_destroy (collection);
66 mongoc_client_destroy(client);
67 mongoc_cleanup();
68
69 return 0;
70}
3

In your terminal, run the following commands to build and run this application:

cmake -S. -Bcmake-build
cmake --build cmake-build --target index.out
./cmake-build/index.out
Index created!

This example performs the following actions:

  • Configures an index for all document fields and a single synonym mapping definition that uses the mapping configured in the synonymous_terms collection.

  • Uses the default analyzer, lucene.standard, to analyze all the fields.

  • Enables synonyms from the synonymous_terms collection for queries on fields analyzed with the lucene.standard analyzer.

1

To learn how to install the driver and configure your C application, see the Get Started tutorial in the MongoDB C Driver documentation.

2

Create a create-dynamic-index.c file in your application directory, and copy and paste the following code into the file.

create-dynamic-index.c
1#include <mongoc/mongoc.h>
2#include <stdio.h>
3
4int main(int argc, char *argv[]) {
5 mongoc_client_t *client;
6 mongoc_collection_t *collection;
7 bson_error_t error;
8 bson_t cmd;
9 bson_t *index_definition;
10 bool success;
11
12 /* Initialize the MongoDB C Driver. */
13 mongoc_init();
14
15 /* Connect to your MongoDB deployment. */
16 client = mongoc_client_new("<connection-string>");
17 collection = mongoc_client_get_collection (client, "sample_mflix", "movies");
18
19 if (!client) {
20 fprintf(stderr, "Failed to create client.\n");
21 return 1;
22 }
23
24 /* Create the MongoDB Search index definition for a dynamic index with synonyms. */
25 char *cmd_str = bson_strdup_printf (
26 BSON_STR ({
27 "createSearchIndexes": "%s",
28 "indexes": [{
29 "name": "default",
30 "definition": {
31 "mappings": {
32 "dynamic": true
33 },
34 "synonyms": [
35 {
36 "analyzer": "lucene.standard",
37 "name": "my_synonyms",
38 "source": {
39 "collection": "synonymous_terms"
40 }
41 }
42 ]
43 }
44 }]
45 }),
46 "movies"
47 );
48 bson_init_from_json (&cmd, cmd_str, -1, &error);
49 bson_free (cmd_str);
50
51 if (mongoc_collection_command_simple (collection, &cmd, NULL, NULL, &error)) {
52 printf ("Index created!\n");
53 } else {
54 fprintf (stderr, "Failed to create search index: %s", error.message);
55 }
56
57 /* Clean up. */
58 bson_destroy (&cmd);
59 mongoc_collection_destroy (collection);
60 mongoc_client_destroy(client);
61 mongoc_cleanup();
62
63 return 0;
64}
3

In your terminal, run the following commands to build and run this application:

cmake -S. -Bcmake-build
cmake --build cmake-build --target index.out
./cmake-build/index.out
Index created!

To learn how to add a collection that configures words as synonyms to your cluster, and use this collection to create a MongoDB Search index and run MongoDB Search queries using synonyms, see How to Use Synonyms with MongoDB Search.

To see examples of text queries that use synonyms, see Synonyms Examples in the text reference page.

To see an example phrase queries that uses synonyms, see Synonyms Example in the phrase reference page.

The following examples for the sample_mflix.movies collection create index definitions that use static and dynamic mappings. These examples use the synonymous_terms synonym source collection described in the Synonym Source Collection Example section to enable synonym mappings.

This example performs the following actions:

  • Configures an index with a single text field and a single synonym mapping definition that uses the mapping configured in the synonymous_terms collection.

  • Analyzes the plot field with the lucene.english analyzer.

  • Enables synonyms from the synonymous_terms collection for queries on fields analyzed with the lucene.english analyzer.

1

To learn how to install the driver and configure your C++ application, see the Get Started tutorial in the MongoDB C++ Driver documentation.

2

Create a CreateStaticIndex.cpp file in your project directory, and copy and paste the following code into the file.

CreateStaticIndex.cpp
1#include <iostream>
2
3#include <bsoncxx/builder/basic/document.hpp>
4#include <bsoncxx/json.hpp>
5#include <mongocxx/client.hpp>
6#include <mongocxx/instance.hpp>
7#include <mongocxx/uri.hpp>
8
9using bsoncxx::builder::basic::kvp;
10using bsoncxx::builder::basic::make_document;
11
12int main() {
13 // Initialize the MongoDB C++ driver
14 mongocxx::instance instance{};
15
16 // Connect to your MongoDB deployment
17 mongocxx::uri uri("<connection-string>");
18 mongocxx::client client(uri);
19
20 auto db = client["sample_mflix"];
21 auto collection = db["movies"];
22 auto siv = collection.search_indexes();
23
24 // Create the MongoDB Search index definition for the plot field with synonyms
25 auto name = "default";
26 auto synonyms = bsoncxx::builder::basic::make_array(
27 make_document(
28 kvp("analyzer", "lucene.english"),
29 kvp("name", "my_synonyms"),
30 kvp("source", make_document(
31 kvp("collection", "synonymous_terms")
32 ))
33 )
34 );
35
36 auto definition = make_document(
37 kvp("mappings", make_document(
38 kvp("dynamic", false),
39 kvp("fields", make_document(
40 kvp("plot", make_document(
41 kvp("type", "string"),
42 kvp("analyzer", "lucene.english")
43 ))
44 ))
45 )),
46 kvp("synonyms", synonyms)
47 );
48 auto model = mongocxx::search_index_model(name, definition.view());
49
50 try {
51 // Execute the command to create the index
52 auto result = siv.create_one(model);
53 std::cout << "New index name: " << result << std::endl;
54 } catch (const std::exception& e) {
55 std::cerr << "Error creating Atlas Search index: " << e.what() << std::endl;
56 }
57
58}
3
c++ --std=c++17 CreateStaticIndex.cpp $(pkg-config --cflags --libs libmongocxx) -o ./app.out
./app.out
New index name: default

This example performs the following actions:

  • Configures an index for all document fields and a single synonym mapping definition that uses the mapping configured in the synonymous_terms collection.

  • Uses the default analyzer, lucene.standard, to analyze all the fields.

  • Enables synonyms from the synonymous_terms collection for queries on fields analyzed with the lucene.standard analyzer.

1

To learn how to install the driver and configure your C++ application, see the Get Started tutorial in the MongoDB C++ Driver documentation.

2

Create a CreateDynamicIndex.cpp file in your project directory, and copy and paste the following code into the file.

CreateDynamicIndex.cpp
1#include <iostream>
2
3#include <bsoncxx/builder/basic/document.hpp>
4#include <bsoncxx/json.hpp>
5#include <mongocxx/client.hpp>
6#include <mongocxx/instance.hpp>
7#include <mongocxx/uri.hpp>
8
9using bsoncxx::builder::basic::kvp;
10using bsoncxx::builder::basic::make_document;
11
12int main() {
13 // Initialize the MongoDB C++ driver
14 mongocxx::instance instance{};
15
16 // Connect to your MongoDB deployment
17 mongocxx::uri uri("<connection-string>");
18 mongocxx::client client(uri);
19
20 auto db = client["sample_mflix"];
21 auto collection = db["movies"];
22 auto siv = collection.search_indexes();
23
24 // Define the synonym mapping for the lucene.standard analyzer
25 auto name = "default";
26 auto synonyms = bsoncxx::builder::basic::make_array(
27 make_document(
28 kvp("analyzer", "lucene.standard"),
29 kvp("name", "my_synonyms"),
30 kvp("source", make_document(
31 kvp("collection", "synonymous_terms")
32 ))
33 )
34 );
35
36 // Create the MongoDB Search index definition
37 auto definition = make_document(
38 kvp("mappings", make_document(
39 kvp("dynamic", true))
40 ),
41 kvp("synonyms", synonyms)
42 );
43 auto model = mongocxx::search_index_model(name, definition.view());
44
45 try {
46 // Execute the command to create the index
47 auto result = siv.create_one(model);
48 std::cout << "New index name: " << result << std::endl;
49 } catch (const std::exception& e) {
50 std::cerr << "Error creating Atlas Search index: " << e.what() << std::endl;
51 }
52
53}
3
c++ --std=c++17 CreateDynamicIndex.cpp $(pkg-config --cflags --libs libmongocxx) -o ./app.out
./app.out
New index name: default

To learn how to add a collection that configures words as synonyms to your cluster, and use this collection to create a MongoDB Search index and run MongoDB Search queries using synonyms, see How to Use Synonyms with MongoDB Search.

To see examples of text queries that use synonyms, see Synonyms Examples in the text reference page.

To see an example phrase queries that uses synonyms, see Synonyms Example in the phrase reference page.

The following examples for the sample_mflix.movies collection create index definitions that use static and dynamic mappings. These examples use the synonymous_terms synonym source collection described in the Synonym Source Collection Example section to enable synonym mappings.

This example performs the following actions:

  • Configures an index with a single text field and a single synonym mapping definition that uses the mapping configured in the synonymous_terms collection.

  • Analyzes the plot field with the lucene.english analyzer.

  • Enables synonyms from the synonymous_terms collection for queries on fields analyzed with the lucene.english analyzer.

1

To learn how to install the driver and configure your Go application, see the Get Started tutorial in the MongoDB Go Driver documentation.

2

Create a create-static-index.go file in your project directory, and copy and paste the following code into the file.

create_static_index.go
1package main
2
3import (
4 "context"
5 "fmt"
6 "log"
7
8 "go.mongodb.org/mongo-driver/v2/bson"
9 "go.mongodb.org/mongo-driver/v2/mongo"
10 "go.mongodb.org/mongo-driver/v2/mongo/options"
11)
12
13func main() {
14 ctx := context.Background()
15
16 // Replace the placeholder with your MongoDB deployment's connection string
17 uri := "<connection-string>"
18 client, err := mongo.Connect(options.Client().
19 ApplyURI(uri))
20 if err != nil {
21 panic(err)
22 }
23
24 defer func() {
25 if err := client.Disconnect(context.TODO()); err != nil {
26 panic(err)
27 }
28 }()
29
30 coll := client.Database("sample_mflix").Collection("movies")
31 const indexName = "default"
32 opts := options.SearchIndexes().SetName(indexName).SetType("search")
33
34 // Create the search index definition
35
36 searchIndexModel := mongo.SearchIndexModel{
37 Definition: bson.M{
38 "mappings": bson.M{
39 "dynamic": false,
40 "fields": bson.M{
41 "plot": bson.M{
42 "type": "string",
43 "analyzer": "lucene.english",
44 },
45 },
46 },
47 "synonyms": []bson.M{
48 {
49 "analyzer": "lucene.english",
50 "name": "my_synonyms",
51 "source": bson.M{
52 "collection": "synonymous_terms",
53 },
54 },
55 },
56 },
57 Options: opts,
58 }
59
60 // Create the index
61 searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, searchIndexModel)
62 if err != nil {
63 log.Fatalf("Failed to create the Atlas Search index: %v", err)
64 }
65
66 fmt.Println("Name of index created: " + searchIndexName)
67}
3
go run create_static_index.go
New index name: default

This example performs the following actions:

  • Configures an index for all document fields and a single synonym mapping definition that uses the mapping configured in the synonymous_terms collection.

  • Uses the default analyzer, lucene.standard, to analyze all the fields.

  • Enables synonyms from the synonymous_terms collection for queries on fields analyzed with the lucene.standard analyzer.

1

To learn how to install the driver and configure your Go application, see the Get Started tutorial in the MongoDB Go Driver documentation.

2

Create a create-dynamic-index.go file in your project directory, and copy and paste the following code into the file.

create_dynamic_index.go
1package main
2
3import (
4 "context"
5 "fmt"
6 "log"
7
8 "go.mongodb.org/mongo-driver/v2/bson"
9 "go.mongodb.org/mongo-driver/v2/mongo"
10 "go.mongodb.org/mongo-driver/v2/mongo/options"
11)
12
13func main() {
14 ctx := context.Background()
15
16 // Replace the placeholder with your MongoDB deployment's connection string
17 uri := "<connection-string>"
18 client, err := mongo.Connect(options.Client().
19 ApplyURI(uri))
20 if err != nil {
21 panic(err)
22 }
23
24 defer func() {
25 if err := client.Disconnect(context.TODO()); err != nil {
26 panic(err)
27 }
28 }()
29
30 coll := client.Database("sample_mflix").Collection("movies")
31 const indexName = "default"
32 opts := options.SearchIndexes().SetName(indexName).SetType("search")
33
34 // Create the search index definition
35 searchIndexModel := mongo.SearchIndexModel{
36 Definition: bson.M{
37 "mappings": bson.M{
38 "dynamic": true,
39 },
40 "synonyms": []bson.M{
41 {
42 "analyzer": "lucene.standard",
43 "name": "my_synonyms",
44 "source": bson.M{
45 "collection": "synonymous_terms",
46 },
47 },
48 },
49 },
50 Options: opts,
51 }
52
53 // Create the index
54 searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, searchIndexModel)
55 if err != nil {
56 log.Fatalf("Failed to create the Atlas Search index: %v", err)
57 }
58
59 fmt.Println("Name of index created: " + searchIndexName)
60}
3
go run create_dynamic_index.go
New index name: default

To learn how to add a collection that configures words as synonyms to your cluster, and use this collection to create a MongoDB Search index and run MongoDB Search queries using synonyms, see How to Use Synonyms with MongoDB Search.

To see examples of text queries that use synonyms, see Synonyms Examples in the text reference page.

To see an example phrase queries that uses synonyms, see Synonyms Example in the phrase reference page.

The following examples for the sample_mflix.movies collection create index definitions that use static and dynamic mappings. These examples use the synonymous_terms synonym source collection described in the Synonym Source Collection Example section to enable synonym mappings.

This example performs the following actions:

  • Configures an index with a single text field and a single synonym mapping definition that uses the mapping configured in the synonymous_terms collection.

  • Analyzes the plot field with the lucene.english analyzer.

  • Enables synonyms from the synonymous_terms collection for queries on fields analyzed with the lucene.english analyzer.

1

To learn how to install the driver and configure your Java application, see the Get Started tutorial in the MongoDB Java Driver documentation.

2

In your project's base package directory, create a CreateStaticIndex.java file and copy and paste the following code into this file.

CreateStaticIndex.java
1import com.mongodb.client.*;
2import org.bson.Document;
3
4import java.util.List;
5
6public class CreateStaticIndex {
7 public static void main(String[] args) {
8 // Replace the placeholder with your MongoDB deployment's connection string
9 String connectionString = "<connection-string>";
10
11 try (MongoClient mongoClient = MongoClients.create(connectionString)) {
12 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
13 MongoCollection<Document> collection = database.getCollection("movies");
14 String indexName = "default";
15
16 // Define the synonym mapping for the lucene.english analyzer
17 List<Document> synonymsList = List.of(
18 new Document("analyzer", "lucene.english")
19 .append("name", "my_synonyms")
20 .append("source", new Document("collection", "synonymous_terms"))
21 );
22
23 // Create the MongoDB Search index definition for the plot field with synonyms
24 Document searchIdx = new Document(
25 "mappings",
26 new Document("dynamic", false)
27 .append("fields",
28 new Document("plot",
29 new Document("type", "string")
30 .append("analyzer", "lucene.english")
31 )
32 )
33 ).append("synonyms", synonymsList);
34
35 // Create the index by using the Java Sync Driver
36 collection.createSearchIndex(indexName, searchIdx);
37 System.out.println("New index name: " + indexName);
38 } catch (Exception e) {
39 System.err.println("Error creating Atlas Search index: " + e.getMessage());
40 }
41 }
42}
3

Compile and run your application in your IDE or your shell.

javac CreateStaticIndex.java
java CreateStaticIndex
New index name: default

This example performs the following actions:

  • Configures an index for all document fields and a single synonym mapping definition that uses the mapping configured in the synonymous_terms collection.

  • Uses the default analyzer, lucene.standard, to analyze all the fields.

  • Enables synonyms from the synonymous_terms collection for queries on fields analyzed with the lucene.standard analyzer.

1

To learn how to install the driver and configure your Java application, see the Get Started tutorial in the MongoDB Java Driver documentation.

2

In your project's base package directory, create a CreateDynamicIndex.java file and copy and paste the following code into this file.

CreateDynamicIndex.java
1import com.mongodb.client.*;
2import org.bson.Document;
3
4import java.util.List;
5
6public class CreateDynamicIndex {
7 public static void main(String[] args) {
8 // Replace the placeholder with your MongoDB deployment's connection string
9 String connectionString = "<connection-string>";
10
11 try (MongoClient mongoClient = MongoClients.create(connectionString)) {
12 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
13 MongoCollection<Document> collection = database.getCollection("movies");
14 String indexName = "default";
15
16 // Define the synonym mapping for the lucene.standard analyzer
17 List<Document> synonymsList = List.of(
18 new Document("analyzer", "lucene.standard")
19 .append("name", "my_synonyms")
20 .append("source", new Document("collection", "synonymous_terms"))
21 );
22
23 // Create the MongoDB Search index definition
24 Document searchIdx = new Document(
25 "mappings",
26 new Document("dynamic", true)
27 ).append("synonyms", synonymsList);
28
29 // Create the index by using the Java Sync Driver
30 collection.createSearchIndex(indexName, searchIdx);
31 System.out.println("New index name: " + indexName);
32 } catch (Exception e) {
33 System.err.println("Error creating Atlas Search index: " + e.getMessage());
34 }
35 }
36}
3

Compile and run your application in your IDE or your shell.

javac CreateDynamicIndex.java
java CreateDynamicIndex
New index name: default

To learn how to add a collection that configures words as synonyms to your cluster, and use this collection to create a MongoDB Search index and run MongoDB Search queries using synonyms, see How to Use Synonyms with MongoDB Search.

To see examples of text queries that use synonyms, see Synonyms Examples in the text reference page.

To see an example phrase queries that uses synonyms, see Synonyms Example in the phrase reference page.

The following examples for the sample_mflix.movies collection create index definitions that use static and dynamic mappings. These examples use the synonymous_terms synonym source collection described in the Synonym Source Collection Example section to enable synonym mappings.

This example performs the following actions:

  • Configures an index with a single text field and a single synonym mapping definition that uses the mapping configured in the synonymous_terms collection.

  • Analyzes the plot field with the lucene.english analyzer.

  • Enables synonyms from the synonymous_terms collection for queries on fields analyzed with the lucene.english analyzer.

1

To learn how to install the driver and configure your Node.js application, see the Get Started tutorial in the MongoDB Node.js Driver documentation.

2

Create a create-static-index.js file in your project directory, and copy and paste the following code into the file.

create-static-index.js
1const { MongoClient } = require("mongodb");
2
3// Replace the connection string with your MongoDB deployment's connection string
4const uri = "<connection-string>";
5
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10 const database = client.db("sample_mflix");
11 const collection = database.collection("movies");
12
13 // Create the MongoDB Search index definition for the plot field with synonyms
14 const index = {
15 name: "default",
16 definition: {
17 "mappings": {
18 "dynamic": false,
19 "fields": {
20 "plot": {
21 "type": "string",
22 "analyzer": "lucene.english"
23 }
24 }
25 },
26 "synonyms": [
27 {
28 "analyzer": "lucene.english",
29 "name": "my_synonyms",
30 "source": {
31 "collection": "synonymous_terms"
32 }
33 }
34 ]
35 }
36 }
37
38 // Create the index
39 const result = await collection.createSearchIndex(index);
40 console.log("New index name: " + result);
41 } finally {
42 await client.close();
43 }
44}
45
46run().catch(console.dir);
3
node create-static-index.js
New index name: default

This example performs the following actions:

  • Configures an index for all document fields and a single synonym mapping definition that uses the mapping configured in the synonymous_terms collection.

  • Uses the default analyzer, lucene.standard, to analyze all the fields.

  • Enables synonyms from the synonymous_terms collection for queries on fields analyzed with the lucene.standard analyzer.

1

To learn how to install the driver and configure your Node.js application, see the Get Started tutorial in the MongoDB Node.js Driver documentation.

2

Create a create-dynamic-index.js file in your project directory, and copy and paste the following code into the file.

create-dynamic-index.js
1const { MongoClient } = require("mongodb");
2
3// Replace the connection string with your MongoDB deployment's connection string
4const uri = "<connection-string>";
5
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10 const database = client.db("sample_mflix");
11 const collection = database.collection("movies");
12
13 // Create the MongoDB Search index definition with dynamic mapping and synonyms
14 const index = {
15 name: "default",
16 definition: {
17 "mappings": {
18 "dynamic": true
19 },
20 "synonyms": [
21 {
22 "analyzer": "lucene.standard",
23 "name": "my_synonyms",
24 "source": {
25 "collection": "synonymous_terms"
26 }
27 }
28 ]
29 }
30 }
31
32 // Create the index
33 const result = await collection.createSearchIndex(index);
34 console.log("New index name: " + result);
35 } finally {
36 await client.close();
37 }
38}
39
40run().catch(console.dir);
3
node create-dynamic-index.js
New index name: default

To learn how to add a collection that configures words as synonyms to your cluster, and use this collection to create a MongoDB Search index and run MongoDB Search queries using synonyms, see How to Use Synonyms with MongoDB Search.

To see examples of text queries that use synonyms, see Synonyms Examples in the text reference page.

To see an example phrase queries that uses synonyms, see Synonyms Example in the phrase reference page.

The following examples for the sample_mflix.movies collection create index definitions that use static and dynamic mappings. These examples use the synonymous_terms synonym source collection described in the Synonym Source Collection Example section to enable synonym mappings.

This example performs the following actions:

  • Configures an index with a single text field and a single synonym mapping definition that uses the mapping configured in the synonymous_terms collection.

  • Analyzes the plot field with the lucene.english analyzer.

  • Enables synonyms from the synonymous_terms collection for queries on fields analyzed with the lucene.english analyzer.

1

To learn how to install the driver and configure your Python application, see the Get Started tutorial in the MongoDB Python Driver documentation.

2

Create a create-static-index.py file in your project directory, and copy and paste the following code into the file.

create-static-index.py
1from pymongo import MongoClient
2from pymongo.operations import SearchIndexModel
3
4# Connect to your Atlas deployment
5uri = "<connection-string>"
6client = MongoClient(uri)
7
8database = client["sample_mflix"]
9collection = database["movies"]
10
11# Create the MongoDB Search index definition for the plot field with synonyms
12search_index_model = SearchIndexModel(
13 definition={
14 "mappings": {
15 "dynamic": False,
16 "fields": {
17 "plot": {
18 "type": "string",
19 "analyzer": "lucene.english"
20 }
21 }
22 },
23 "synonyms": [
24 {
25 "analyzer": "lucene.english",
26 "name": "my_synonyms",
27 "source": {
28 "collection": "synonymous_terms"
29 }
30 }
31 ]
32 },
33 name="default",
34)
35
36# Create the index
37result = collection.create_search_index(model=search_index_model)
38print(f"New index name: {result}")
3
python create-static-index.py
New index name: default

This example performs the following actions:

  • Configures an index for all document fields and a single synonym mapping definition that uses the mapping configured in the synonymous_terms collection.

  • Uses the default analyzer, lucene.standard, to analyze all the fields.

  • Enables synonyms from the synonymous_terms collection for queries on fields analyzed with the lucene.standard analyzer.

1

To learn how to install the driver and configure your Python application, see the Get Started tutorial in the MongoDB Python Driver documentation.

2

Create a create-dynamic-index.py file in your project directory, and copy and paste the following code into the file.

create-dynamic-index.py
1from pymongo import MongoClient
2from pymongo.operations import SearchIndexModel
3
4# Connect to your Atlas deployment
5uri = "<connection-string>"
6client = MongoClient(uri)
7
8database = client["sample_mflix"]
9collection = database["movies"]
10
11# Create the MongoDB Search index definition
12search_index_model = SearchIndexModel(
13 definition={
14 "mappings": {
15 "dynamic": True,
16 },
17 "synonyms": [
18 {
19 "analyzer": "lucene.standard",
20 "name": "my_synonyms",
21 "source": {
22 "collection": "synonymous_terms"
23 }
24 }
25 ]
26 },
27 name="default",
28)
29
30# Create the index
31result = collection.create_search_index(model=search_index_model)
32print(f"New index name: {result}")
3
python create-dynamic-index.py
New index name: default

To learn how to add a collection that configures words as synonyms to your cluster, and use this collection to create a MongoDB Search index and run MongoDB Search queries using synonyms, see How to Use Synonyms with MongoDB Search.

To see examples of text queries that use synonyms, see Synonyms Examples in the text reference page.

To see an example phrase queries that uses synonyms, see Synonyms Example in the phrase reference page.

The following examples for the sample_mflix.movies collection create index definitions that use static and dynamic mappings. These examples use the synonymous_terms synonym source collection described in the Synonym Source Collection Example section to enable synonym mappings.

This example performs the following actions:

  • Configures an index with a single text field and a single synonym mapping definition that uses the mapping configured in the synonymous_terms collection.

  • Analyzes the plot field with the lucene.english analyzer.

  • Enables synonyms from the synonymous_terms collection for queries on fields analyzed with the lucene.english analyzer.

1
static-index.json
1{
2 "name": "default",
3 "collectionName": "movies",
4 "database": "sample_mflix",
5 "mappings": {
6 "dynamic": false,
7 "fields": {
8 "plot": {
9 "type": "string",
10 "analyzer": "lucene.english"
11 }
12 }
13 },
14 "synonyms": [
15 {
16 "analyzer": "lucene.english",
17 "name": "my_synonyms",
18 "source": {
19 "collection": "synonymous_terms"
20 }
21 }
22 ]
23}
2

In your terminal, connect to your local deployment from the Atlas CLI. To learn more, see Connect from the Atlas CLI.

3

Run the atlas deployments search indexes create command in your terminal, replacing <path-to-file> with the path to the static-index.json file:

1atlas deployments search indexes create --file <path-to-file>

This example performs the following actions:

  • Configures an index for all document fields and a single synonym mapping definition that uses the mapping configured in the synonymous_terms collection.

  • Uses the default analyzer, lucene.standard, to analyze all the fields.

  • Enables synonyms from the synonymous_terms collection for queries on fields analyzed with the lucene.standard analyzer.

1
dynamic-index.json
1{
2 "name": "default",
3 "collectionName": "movies",
4 "database": "sample_mflix",
5 "mappings": {
6 "dynamic": true
7 },
8 "synonyms": [
9 {
10 "analyzer": "lucene.standard",
11 "name": "my_synonyms",
12 "source": {
13 "collection": "synonymous_terms"
14 }
15 }
16 ]
17}
2

In your terminal, connect to your local deployment from the Atlas CLI. To learn more, see Connect from the Atlas CLI.

3

Run the atlas deployments search indexes create command in your terminal, replacing <path-to-file> with the path to the dynamic-index.json file:

1atlas deployments search indexes create --file <path-to-file>

To learn how to add a collection that configures words as synonyms to your cluster, and use this collection to create a MongoDB Search index and run MongoDB Search queries using synonyms, see How to Use Synonyms with MongoDB Search.

To see examples of text queries that use synonyms, see Synonyms Examples in the text reference page.

To see an example phrase queries that uses synonyms, see Synonyms Example in the phrase reference page.

The following examples for the sample_mflix.movies collection create index definitions that use static and dynamic mappings. These examples use the synonymous_terms synonym source collection described in the Synonym Source Collection Example section to enable synonym mappings.

This example performs the following actions:

  • Configures an index with a single text field and a single synonym mapping definition that uses the mapping configured in the synonymous_terms collection.

  • Analyzes the plot field with the lucene.english analyzer.

  • Enables synonyms from the synonymous_terms collection for queries on fields analyzed with the lucene.english analyzer.

1

Open Compass and connect to your cluster. For detailed instructions, see Connect to a Cluster via Compass.

2

On the Database screen, click the sample_mflix database, then click the name of the movies collection.

3
  1. Click the Indexes tab, then select Search Indexes.

  2. Click Create Atlas Search Index to open the index creation dialog box.

  3. Specify a name for the index.

    Your MongoDB Search index is named default by default. If you keep this name, then your index will be the default Search index for any MongoDB Search query that does not specify a different index option in its operators. If you are creating multiple indexes, we recommend that you maintain a consistent, descriptive naming convention across your indexes.

  4. Specify the JSON MongoDB Search index definition.

    1{
    2 "mappings": {
    3 "dynamic": false,
    4 "fields": {
    5 "plot": {
    6 "type": "string",
    7 "analyzer": "lucene.english"
    8 }
    9 }
    10 },
    11 "synonyms": [
    12 {
    13 "analyzer": "lucene.english",
    14 "name": "my_synonyms",
    15 "source": {
    16 "collection": "synonymous_terms"
    17 }
    18 }
    19 ]
    20}
  5. Click Create Search Index.

This example performs the following actions:

  • Configures an index for all document fields and a single synonym mapping definition that uses the mapping configured in the synonymous_terms collection.

  • Uses the default analyzer, lucene.standard, to analyze all the fields.

  • Enables synonyms from the synonymous_terms collection for queries on fields analyzed with the lucene.standard analyzer.

1

Open Compass and connect to your cluster. For detailed instructions, see Connect to a Cluster via Compass.

2

On the Database screen, click the sample_mflix database, then click the name of the movies collection.

3
  1. Click the Indexes tab, then select Search Indexes.

  2. Click Create Atlas Search Index to open the index creation dialog box.

  3. Specify a name for the index.

    Your MongoDB Search index is named default by default. If you keep this name, then your index will be the default Search index for any MongoDB Search query that does not specify a different index option in its operators. If you are creating multiple indexes, we recommend that you maintain a consistent, descriptive naming convention across your indexes.

  4. Specify the JSON MongoDB Search index definition.

    1{
    2 "mappings": {
    3 "dynamic": true
    4 },
    5 "synonyms": [
    6 {
    7 "analyzer": "lucene.standard",
    8 "name": "my_synonyms",
    9 "source": {
    10 "collection": "synonymous_terms"
    11 }
    12 }
    13 ]
    14}
  5. Click Create Search Index.

To learn how to add a collection that configures words as synonyms to your cluster, and use this collection to create a MongoDB Search index and run MongoDB Search queries using synonyms, see How to Use Synonyms with MongoDB Search.

To see examples of text queries that use synonyms, see Synonyms Examples in the text reference page.

To see an example phrase queries that uses synonyms, see Synonyms Example in the phrase reference page.

The following examples for the sample_mflix.movies collection create index definitions that use static and dynamic mappings. These examples use the synonymous_terms synonym source collection described in the Synonym Source Collection Example section to enable synonym mappings.

This example performs the following actions:

  • Configures an index with a single text field and a single synonym mapping definition that uses the mapping configured in the synonymous_terms collection.

  • Analyzes the plot field with the lucene.english analyzer.

  • Enables synonyms from the synonymous_terms collection for queries on fields analyzed with the lucene.english analyzer.

1

In your terminal, connect to your Atlas cloud-hosted deployment or local deployment from mongosh. For detailed instructions on how to connect, see Connect to a Deployment.

2
use sample_mflix
switched to db sample_mflix
3
1db.movies.createSearchIndex(
2 "default",
3 {
4 "mappings": {
5 "dynamic": false,
6 "fields": {
7 "plot": {
8 "type": "string",
9 "analyzer": "lucene.english"
10 }
11 }
12 },
13 "synonyms": [
14 {
15 "analyzer": "lucene.english",
16 "name": "my_synonyms",
17 "source": {
18 "collection": "synonymous_terms"
19 }
20 }
21 ]}
22)
default

This example performs the following actions:

  • Configures an index for all document fields and a single synonym mapping definition that uses the mapping configured in the synonymous_terms collection.

  • Uses the default analyzer, lucene.standard, to analyze all the fields.

  • Enables synonyms from the synonymous_terms collection for queries on fields analyzed with the lucene.standard analyzer.

1

In your terminal, connect to your Atlas cloud-hosted deployment or local deployment from mongosh. For detailed instructions on how to connect, see Connect to a Deployment.

2
use sample_mflix
switched to db sample_mflix
3
1db.movies.createSearchIndex(
2 "default",
3 {
4 "mappings": {
5 "dynamic": true
6 },
7 "synonyms": [
8 {
9 "analyzer": "lucene.standard",
10 "name": "my_synonyms",
11 "source": {
12 "collection": "synonymous_terms"
13 }
14 }
15 ]}
16)
default

To learn how to add a collection that configures words as synonyms to your cluster, and use this collection to create a MongoDB Search index and run MongoDB Search queries using synonyms, see How to Use Synonyms with MongoDB Search.

To see examples of text queries that use synonyms, see Synonyms Examples in the text reference page.

To see an example phrase queries that uses synonyms, see Synonyms Example in the phrase reference page.

The following examples for the sample_mflix.movies collection create index definitions that use static and dynamic mappings. These examples use the synonymous_terms synonym source collection described in the Synonym Source Collection Example section to enable synonym mappings.

This example performs the following actions:

  • Configures an index with a single text field and a single synonym mapping definition that uses the mapping configured in the synonymous_terms collection.

  • Analyzes the plot field with the lucene.english analyzer.

  • Enables synonyms from the synonymous_terms collection for queries on fields analyzed with the lucene.english analyzer.

1

To learn how to install the driver and configure your C application, see the Get Started tutorial in the MongoDB C Driver documentation.

2

Create a create-static-index.c file in your application directory, and copy and paste the following code into the file.

create-static-index.c
1#include <mongoc/mongoc.h>
2#include <stdio.h>
3
4int main(int argc, char *argv[]) {
5 mongoc_client_t *client;
6 mongoc_collection_t *collection;
7 bson_error_t error;
8 bson_t cmd;
9 bson_t *index_definition;
10 bool success;
11
12 /* Initialize the MongoDB C Driver. */
13 mongoc_init();
14
15 /* Connect to your MongoDB deployment. */
16 client = mongoc_client_new("<connection-string>");
17 collection = mongoc_client_get_collection (client, "sample_mflix", "movies");
18
19 if (!client) {
20 fprintf(stderr, "Failed to create client.\n");
21 return 1;
22 }
23
24 /* Create the MongoDB Search index definition for the plot field with synonyms. */
25 char *cmd_str = bson_strdup_printf (
26 BSON_STR ({
27 "createSearchIndexes": "%s",
28 "indexes": [{
29 "name": "default",
30 "definition": {
31 "mappings": {
32 "dynamic": false,
33 "fields": {
34 "plot": {
35 "type": "string",
36 "analyzer": "lucene.english"
37 }
38 }
39 },
40 "synonyms": [
41 {
42 "analyzer": "lucene.english",
43 "name": "my_synonyms",
44 "source": {
45 "collection": "synonymous_terms"
46 }
47 }
48 ]
49 }
50 }]
51 }),
52 "movies"
53 );
54 bson_init_from_json (&cmd, cmd_str, -1, &error);
55 bson_free (cmd_str);
56
57 if (mongoc_collection_command_simple (collection, &cmd, NULL, NULL, &error)) {
58 printf ("Index created!\n");
59 } else {
60 fprintf (stderr, "Failed to create search index: %s", error.message);
61 }
62
63 /* Clean up. */
64 bson_destroy (&cmd);
65 mongoc_collection_destroy (collection);
66 mongoc_client_destroy(client);
67 mongoc_cleanup();
68
69 return 0;
70}
3

In your terminal, run the following commands to build and run this application:

cmake -S. -Bcmake-build
cmake --build cmake-build --target index.out
./cmake-build/index.out
Index created!

This example performs the following actions:

  • Configures an index for all document fields and a single synonym mapping definition that uses the mapping configured in the synonymous_terms collection.

  • Uses the default analyzer, lucene.standard, to analyze all the fields.

  • Enables synonyms from the synonymous_terms collection for queries on fields analyzed with the lucene.standard analyzer.

1

To learn how to install the driver and configure your C application, see the Get Started tutorial in the MongoDB C Driver documentation.

2

Create a create-dynamic-index.c file in your application directory, and copy and paste the following code into the file.

create-dynamic-index.c
1#include <mongoc/mongoc.h>
2#include <stdio.h>
3
4int main(int argc, char *argv[]) {
5 mongoc_client_t *client;
6 mongoc_collection_t *collection;
7 bson_error_t error;
8 bson_t cmd;
9 bson_t *index_definition;
10 bool success;
11
12 /* Initialize the MongoDB C Driver. */
13 mongoc_init();
14
15 /* Connect to your MongoDB deployment. */
16 client = mongoc_client_new("<connection-string>");
17 collection = mongoc_client_get_collection (client, "sample_mflix", "movies");
18
19 if (!client) {
20 fprintf(stderr, "Failed to create client.\n");
21 return 1;
22 }
23
24 /* Create the MongoDB Search index definition for a dynamic index with synonyms. */
25 char *cmd_str = bson_strdup_printf (
26 BSON_STR ({
27 "createSearchIndexes": "%s",
28 "indexes": [{
29 "name": "default",
30 "definition": {
31 "mappings": {
32 "dynamic": true
33 },
34 "synonyms": [
35 {
36 "analyzer": "lucene.standard",
37 "name": "my_synonyms",
38 "source": {
39 "collection": "synonymous_terms"
40 }
41 }
42 ]
43 }
44 }]
45 }),
46 "movies"
47 );
48 bson_init_from_json (&cmd, cmd_str, -1, &error);
49 bson_free (cmd_str);
50
51 if (mongoc_collection_command_simple (collection, &cmd, NULL, NULL, &error)) {
52 printf ("Index created!\n");
53 } else {
54 fprintf (stderr, "Failed to create search index: %s", error.message);
55 }
56
57 /* Clean up. */
58 bson_destroy (&cmd);
59 mongoc_collection_destroy (collection);
60 mongoc_client_destroy(client);
61 mongoc_cleanup();
62
63 return 0;
64}
3

In your terminal, run the following commands to build and run this application:

cmake -S. -Bcmake-build
cmake --build cmake-build --target index.out
./cmake-build/index.out
Index created!

To learn how to add a collection that configures words as synonyms to your cluster, and use this collection to create a MongoDB Search index and run MongoDB Search queries using synonyms, see How to Use Synonyms with MongoDB Search.

To see examples of text queries that use synonyms, see Synonyms Examples in the text reference page.

To see an example phrase queries that uses synonyms, see Synonyms Example in the phrase reference page.

The following examples for the sample_mflix.movies collection create index definitions that use static and dynamic mappings. These examples use the synonymous_terms synonym source collection described in the Synonym Source Collection Example section to enable synonym mappings.

This example performs the following actions:

  • Configures an index with a single text field and a single synonym mapping definition that uses the mapping configured in the synonymous_terms collection.

  • Analyzes the plot field with the lucene.english analyzer.

  • Enables synonyms from the synonymous_terms collection for queries on fields analyzed with the lucene.english analyzer.

1

To learn how to install the driver and configure your C++ application, see the Get Started tutorial in the MongoDB C++ Driver documentation.

2

Create a CreateStaticIndex.cpp file in your project directory, and copy and paste the following code into the file.

CreateStaticIndex.cpp
1#include <iostream>
2
3#include <bsoncxx/builder/basic/document.hpp>
4#include <bsoncxx/json.hpp>
5#include <mongocxx/client.hpp>
6#include <mongocxx/instance.hpp>
7#include <mongocxx/uri.hpp>
8
9using bsoncxx::builder::basic::kvp;
10using bsoncxx::builder::basic::make_document;
11
12int main() {
13 // Initialize the MongoDB C++ driver
14 mongocxx::instance instance{};
15
16 // Connect to your MongoDB deployment
17 mongocxx::uri uri("<connection-string>");
18 mongocxx::client client(uri);
19
20 auto db = client["sample_mflix"];
21 auto collection = db["movies"];
22 auto siv = collection.search_indexes();
23
24 // Create the MongoDB Search index definition for the plot field with synonyms
25 auto name = "default";
26 auto synonyms = bsoncxx::builder::basic::make_array(
27 make_document(
28 kvp("analyzer", "lucene.english"),
29 kvp("name", "my_synonyms"),
30 kvp("source", make_document(
31 kvp("collection", "synonymous_terms")
32 ))
33 )
34 );
35
36 auto definition = make_document(
37 kvp("mappings", make_document(
38 kvp("dynamic", false),
39 kvp("fields", make_document(
40 kvp("plot", make_document(
41 kvp("type", "string"),
42 kvp("analyzer", "lucene.english")
43 ))
44 ))
45 )),
46 kvp("synonyms", synonyms)
47 );
48 auto model = mongocxx::search_index_model(name, definition.view());
49
50 try {
51 // Execute the command to create the index
52 auto result = siv.create_one(model);
53 std::cout << "New index name: " << result << std::endl;
54 } catch (const std::exception& e) {
55 std::cerr << "Error creating Atlas Search index: " << e.what() << std::endl;
56 }
57
58}
3
c++ --std=c++17 CreateStaticIndex.cpp $(pkg-config --cflags --libs libmongocxx) -o ./app.out
./app.out
New index name: default

This example performs the following actions:

  • Configures an index for all document fields and a single synonym mapping definition that uses the mapping configured in the synonymous_terms collection.

  • Uses the default analyzer, lucene.standard, to analyze all the fields.

  • Enables synonyms from the synonymous_terms collection for queries on fields analyzed with the lucene.standard analyzer.

1

To learn how to install the driver and configure your C++ application, see the Get Started tutorial in the MongoDB C++ Driver documentation.

2

Create a CreateDynamicIndex.cpp file in your project directory, and copy and paste the following code into the file.

CreateDynamicIndex.cpp
1#include <iostream>
2
3#include <bsoncxx/builder/basic/document.hpp>
4#include <bsoncxx/json.hpp>
5#include <mongocxx/client.hpp>
6#include <mongocxx/instance.hpp>
7#include <mongocxx/uri.hpp>
8
9using bsoncxx::builder::basic::kvp;
10using bsoncxx::builder::basic::make_document;
11
12int main() {
13 // Initialize the MongoDB C++ driver
14 mongocxx::instance instance{};
15
16 // Connect to your MongoDB deployment
17 mongocxx::uri uri("<connection-string>");
18 mongocxx::client client(uri);
19
20 auto db = client["sample_mflix"];
21 auto collection = db["movies"];
22 auto siv = collection.search_indexes();
23
24 // Define the synonym mapping for the lucene.standard analyzer
25 auto name = "default";
26 auto synonyms = bsoncxx::builder::basic::make_array(
27 make_document(
28 kvp("analyzer", "lucene.standard"),
29 kvp("name", "my_synonyms"),
30 kvp("source", make_document(
31 kvp("collection", "synonymous_terms")
32 ))
33 )
34 );
35
36 // Create the MongoDB Search index definition
37 auto definition = make_document(
38 kvp("mappings", make_document(
39 kvp("dynamic", true))
40 ),
41 kvp("synonyms", synonyms)
42 );
43 auto model = mongocxx::search_index_model(name, definition.view());
44
45 try {
46 // Execute the command to create the index
47 auto result = siv.create_one(model);
48 std::cout << "New index name: " << result << std::endl;
49 } catch (const std::exception& e) {
50 std::cerr << "Error creating Atlas Search index: " << e.what() << std::endl;
51 }
52
53}
3
c++ --std=c++17 CreateDynamicIndex.cpp $(pkg-config --cflags --libs libmongocxx) -o ./app.out
./app.out
New index name: default

To learn how to add a collection that configures words as synonyms to your cluster, and use this collection to create a MongoDB Search index and run MongoDB Search queries using synonyms, see How to Use Synonyms with MongoDB Search.

To see examples of text queries that use synonyms, see Synonyms Examples in the text reference page.

To see an example phrase queries that uses synonyms, see Synonyms Example in the phrase reference page.

The following examples for the sample_mflix.movies collection create index definitions that use static and dynamic mappings. These examples use the synonymous_terms synonym source collection described in the Synonym Source Collection Example section to enable synonym mappings.

This example performs the following actions:

  • Configures an index with a single text field and a single synonym mapping definition that uses the mapping configured in the synonymous_terms collection.

  • Analyzes the plot field with the lucene.english analyzer.

  • Enables synonyms from the synonymous_terms collection for queries on fields analyzed with the lucene.english analyzer.

1

To learn how to install the driver and configure your Go application, see the Get Started tutorial in the MongoDB Go Driver documentation.

2

Create a create-static-index.go file in your project directory, and copy and paste the following code into the file.

create_static_index.go
1package main
2
3import (
4 "context"
5 "fmt"
6 "log"
7
8 "go.mongodb.org/mongo-driver/v2/bson"
9 "go.mongodb.org/mongo-driver/v2/mongo"
10 "go.mongodb.org/mongo-driver/v2/mongo/options"
11)
12
13func main() {
14 ctx := context.Background()
15
16 // Replace the placeholder with your MongoDB deployment's connection string
17 uri := "<connection-string>"
18 client, err := mongo.Connect(options.Client().
19 ApplyURI(uri))
20 if err != nil {
21 panic(err)
22 }
23
24 defer func() {
25 if err := client.Disconnect(context.TODO()); err != nil {
26 panic(err)
27 }
28 }()
29
30 coll := client.Database("sample_mflix").Collection("movies")
31 const indexName = "default"
32 opts := options.SearchIndexes().SetName(indexName).SetType("search")
33
34 // Create the search index definition
35
36 searchIndexModel := mongo.SearchIndexModel{
37 Definition: bson.M{
38 "mappings": bson.M{
39 "dynamic": false,
40 "fields": bson.M{
41 "plot": bson.M{
42 "type": "string",
43 "analyzer": "lucene.english",
44 },
45 },
46 },
47 "synonyms": []bson.M{
48 {
49 "analyzer": "lucene.english",
50 "name": "my_synonyms",
51 "source": bson.M{
52 "collection": "synonymous_terms",
53 },
54 },
55 },
56 },
57 Options: opts,
58 }
59
60 // Create the index
61 searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, searchIndexModel)
62 if err != nil {
63 log.Fatalf("Failed to create the Atlas Search index: %v", err)
64 }
65
66 fmt.Println("Name of index created: " + searchIndexName)
67}
3
go run create_static_index.go
New index name: default

This example performs the following actions:

  • Configures an index for all document fields and a single synonym mapping definition that uses the mapping configured in the synonymous_terms collection.

  • Uses the default analyzer, lucene.standard, to analyze all the fields.

  • Enables synonyms from the synonymous_terms collection for queries on fields analyzed with the lucene.standard analyzer.

1

To learn how to install the driver and configure your Go application, see the Get Started tutorial in the MongoDB Go Driver documentation.

2

Create a create-dynamic-index.go file in your project directory, and copy and paste the following code into the file.

create_dynamic_index.go
1package main
2
3import (
4 "context"
5 "fmt"
6 "log"
7
8 "go.mongodb.org/mongo-driver/v2/bson"
9 "go.mongodb.org/mongo-driver/v2/mongo"
10 "go.mongodb.org/mongo-driver/v2/mongo/options"
11)
12
13func main() {
14 ctx := context.Background()
15
16 // Replace the placeholder with your MongoDB deployment's connection string
17 uri := "<connection-string>"
18 client, err := mongo.Connect(options.Client().
19 ApplyURI(uri))
20 if err != nil {
21 panic(err)
22 }
23
24 defer func() {
25 if err := client.Disconnect(context.TODO()); err != nil {
26 panic(err)
27 }
28 }()
29
30 coll := client.Database("sample_mflix").Collection("movies")
31 const indexName = "default"
32 opts := options.SearchIndexes().SetName(indexName).SetType("search")
33
34 // Create the search index definition
35 searchIndexModel := mongo.SearchIndexModel{
36 Definition: bson.M{
37 "mappings": bson.M{
38 "dynamic": true,
39 },
40 "synonyms": []bson.M{
41 {
42 "analyzer": "lucene.standard",
43 "name": "my_synonyms",
44 "source": bson.M{
45 "collection": "synonymous_terms",
46 },
47 },
48 },
49 },
50 Options: opts,
51 }
52
53 // Create the index
54 searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, searchIndexModel)
55 if err != nil {
56 log.Fatalf("Failed to create the Atlas Search index: %v", err)
57 }
58
59 fmt.Println("Name of index created: " + searchIndexName)
60}
3
go run create_dynamic_index.go
New index name: default

To learn how to add a collection that configures words as synonyms to your cluster, and use this collection to create a MongoDB Search index and run MongoDB Search queries using synonyms, see How to Use Synonyms with MongoDB Search.

To see examples of text queries that use synonyms, see Synonyms Examples in the text reference page.

To see an example phrase queries that uses synonyms, see Synonyms Example in the phrase reference page.

The following examples for the sample_mflix.movies collection create index definitions that use static and dynamic mappings. These examples use the synonymous_terms synonym source collection described in the Synonym Source Collection Example section to enable synonym mappings.

This example performs the following actions:

  • Configures an index with a single text field and a single synonym mapping definition that uses the mapping configured in the synonymous_terms collection.

  • Analyzes the plot field with the lucene.english analyzer.

  • Enables synonyms from the synonymous_terms collection for queries on fields analyzed with the lucene.english analyzer.

1

To learn how to install the driver and configure your Java application, see the Get Started tutorial in the MongoDB Java Driver documentation.

2

In your project's base package directory, create a CreateStaticIndex.java file and copy and paste the following code into this file.

CreateStaticIndex.java
1import com.mongodb.client.*;
2import org.bson.Document;
3
4import java.util.List;
5
6public class CreateStaticIndex {
7 public static void main(String[] args) {
8 // Replace the placeholder with your MongoDB deployment's connection string
9 String connectionString = "<connection-string>";
10
11 try (MongoClient mongoClient = MongoClients.create(connectionString)) {
12 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
13 MongoCollection<Document> collection = database.getCollection("movies");
14 String indexName = "default";
15
16 // Define the synonym mapping for the lucene.english analyzer
17 List<Document> synonymsList = List.of(
18 new Document("analyzer", "lucene.english")
19 .append("name", "my_synonyms")
20 .append("source", new Document("collection", "synonymous_terms"))
21 );
22
23 // Create the MongoDB Search index definition for the plot field with synonyms
24 Document searchIdx = new Document(
25 "mappings",
26 new Document("dynamic", false)
27 .append("fields",
28 new Document("plot",
29 new Document("type", "string")
30 .append("analyzer", "lucene.english")
31 )
32 )
33 ).append("synonyms", synonymsList);
34
35 // Create the index by using the Java Sync Driver
36 collection.createSearchIndex(indexName, searchIdx);
37 System.out.println("New index name: " + indexName);
38 } catch (Exception e) {
39 System.err.println("Error creating Atlas Search index: " + e.getMessage());
40 }
41 }
42}
3

Compile and run your application in your IDE or your shell.

javac CreateStaticIndex.java
java CreateStaticIndex
New index name: default

This example performs the following actions:

  • Configures an index for all document fields and a single synonym mapping definition that uses the mapping configured in the synonymous_terms collection.

  • Uses the default analyzer, lucene.standard, to analyze all the fields.

  • Enables synonyms from the synonymous_terms collection for queries on fields analyzed with the lucene.standard analyzer.

1

To learn how to install the driver and configure your Java application, see the Get Started tutorial in the MongoDB Java Driver documentation.

2

In your project's base package directory, create a CreateDynamicIndex.java file and copy and paste the following code into this file.

CreateDynamicIndex.java
1import com.mongodb.client.*;
2import org.bson.Document;
3
4import java.util.List;
5
6public class CreateDynamicIndex {
7 public static void main(String[] args) {
8 // Replace the placeholder with your MongoDB deployment's connection string
9 String connectionString = "<connection-string>";
10
11 try (MongoClient mongoClient = MongoClients.create(connectionString)) {
12 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
13 MongoCollection<Document> collection = database.getCollection("movies");
14 String indexName = "default";
15
16 // Define the synonym mapping for the lucene.standard analyzer
17 List<Document> synonymsList = List.of(
18 new Document("analyzer", "lucene.standard")
19 .append("name", "my_synonyms")
20 .append("source", new Document("collection", "synonymous_terms"))
21 );
22
23 // Create the MongoDB Search index definition
24 Document searchIdx = new Document(
25 "mappings",
26 new Document("dynamic", true)
27 ).append("synonyms", synonymsList);
28
29 // Create the index by using the Java Sync Driver
30 collection.createSearchIndex(indexName, searchIdx);
31 System.out.println("New index name: " + indexName);
32 } catch (Exception e) {
33 System.err.println("Error creating Atlas Search index: " + e.getMessage());
34 }
35 }
36}
3

Compile and run your application in your IDE or your shell.

javac CreateDynamicIndex.java
java CreateDynamicIndex
New index name: default

To learn how to add a collection that configures words as synonyms to your cluster, and use this collection to create a MongoDB Search index and run MongoDB Search queries using synonyms, see How to Use Synonyms with MongoDB Search.

To see examples of text queries that use synonyms, see Synonyms Examples in the text reference page.

To see an example phrase queries that uses synonyms, see Synonyms Example in the phrase reference page.

The following examples for the sample_mflix.movies collection create index definitions that use static and dynamic mappings. These examples use the synonymous_terms synonym source collection described in the Synonym Source Collection Example section to enable synonym mappings.

This example performs the following actions:

  • Configures an index with a single text field and a single synonym mapping definition that uses the mapping configured in the synonymous_terms collection.

  • Analyzes the plot field with the lucene.english analyzer.

  • Enables synonyms from the synonymous_terms collection for queries on fields analyzed with the lucene.english analyzer.

1

To learn how to install the driver and configure your Node.js application, see the Get Started tutorial in the MongoDB Node.js Driver documentation.

2

Create a create-static-index.js file in your project directory, and copy and paste the following code into the file.

create-static-index.js
1const { MongoClient } = require("mongodb");
2
3// Replace the connection string with your MongoDB deployment's connection string
4const uri = "<connection-string>";
5
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10 const database = client.db("sample_mflix");
11 const collection = database.collection("movies");
12
13 // Create the MongoDB Search index definition for the plot field with synonyms
14 const index = {
15 name: "default",
16 definition: {
17 "mappings": {
18 "dynamic": false,
19 "fields": {
20 "plot": {
21 "type": "string",
22 "analyzer": "lucene.english"
23 }
24 }
25 },
26 "synonyms": [
27 {
28 "analyzer": "lucene.english",
29 "name": "my_synonyms",
30 "source": {
31 "collection": "synonymous_terms"
32 }
33 }
34 ]
35 }
36 }
37
38 // Create the index
39 const result = await collection.createSearchIndex(index);
40 console.log("New index name: " + result);
41 } finally {
42 await client.close();
43 }
44}
45
46run().catch(console.dir);
3
node create-static-index.js
New index name: default

This example performs the following actions:

  • Configures an index for all document fields and a single synonym mapping definition that uses the mapping configured in the synonymous_terms collection.

  • Uses the default analyzer, lucene.standard, to analyze all the fields.

  • Enables synonyms from the synonymous_terms collection for queries on fields analyzed with the lucene.standard analyzer.

1

To learn how to install the driver and configure your Node.js application, see the Get Started tutorial in the MongoDB Node.js Driver documentation.

2

Create a create-dynamic-index.js file in your project directory, and copy and paste the following code into the file.

create-dynamic-index.js
1const { MongoClient } = require("mongodb");
2
3// Replace the connection string with your MongoDB deployment's connection string
4const uri = "<connection-string>";
5
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10 const database = client.db("sample_mflix");
11 const collection = database.collection("movies");
12
13 // Create the MongoDB Search index definition with dynamic mapping and synonyms
14 const index = {
15 name: "default",
16 definition: {
17 "mappings": {
18 "dynamic": true
19 },
20 "synonyms": [
21 {
22 "analyzer": "lucene.standard",
23 "name": "my_synonyms",
24 "source": {
25 "collection": "synonymous_terms"
26 }
27 }
28 ]
29 }
30 }
31
32 // Create the index
33 const result = await collection.createSearchIndex(index);
34 console.log("New index name: " + result);
35 } finally {
36 await client.close();
37 }
38}
39
40run().catch(console.dir);
3
node create-dynamic-index.js
New index name: default

To learn how to add a collection that configures words as synonyms to your cluster, and use this collection to create a MongoDB Search index and run MongoDB Search queries using synonyms, see How to Use Synonyms with MongoDB Search.

To see examples of text queries that use synonyms, see Synonyms Examples in the text reference page.

To see an example phrase queries that uses synonyms, see Synonyms Example in the phrase reference page.

The following examples for the sample_mflix.movies collection create index definitions that use static and dynamic mappings. These examples use the synonymous_terms synonym source collection described in the Synonym Source Collection Example section to enable synonym mappings.

This example performs the following actions:

  • Configures an index with a single text field and a single synonym mapping definition that uses the mapping configured in the synonymous_terms collection.

  • Analyzes the plot field with the lucene.english analyzer.

  • Enables synonyms from the synonymous_terms collection for queries on fields analyzed with the lucene.english analyzer.

1

To learn how to install the driver and configure your Python application, see the Get Started tutorial in the MongoDB Python Driver documentation.

2

Create a create-static-index.py file in your project directory, and copy and paste the following code into the file.

create-static-index.py
1from pymongo import MongoClient
2from pymongo.operations import SearchIndexModel
3
4# Connect to your Atlas deployment
5uri = "<connection-string>"
6client = MongoClient(uri)
7
8database = client["sample_mflix"]
9collection = database["movies"]
10
11# Create the MongoDB Search index definition for the plot field with synonyms
12search_index_model = SearchIndexModel(
13 definition={
14 "mappings": {
15 "dynamic": False,
16 "fields": {
17 "plot": {
18 "type": "string",
19 "analyzer": "lucene.english"
20 }
21 }
22 },
23 "synonyms": [
24 {
25 "analyzer": "lucene.english",
26 "name": "my_synonyms",
27 "source": {
28 "collection": "synonymous_terms"
29 }
30 }
31 ]
32 },
33 name="default",
34)
35
36# Create the index
37result = collection.create_search_index(model=search_index_model)
38print(f"New index name: {result}")
3
python create-static-index.py
New index name: default

This example performs the following actions:

  • Configures an index for all document fields and a single synonym mapping definition that uses the mapping configured in the synonymous_terms collection.

  • Uses the default analyzer, lucene.standard, to analyze all the fields.

  • Enables synonyms from the synonymous_terms collection for queries on fields analyzed with the lucene.standard analyzer.

1

To learn how to install the driver and configure your Python application, see the Get Started tutorial in the MongoDB Python Driver documentation.

2

Create a create-dynamic-index.py file in your project directory, and copy and paste the following code into the file.

create-dynamic-index.py
1from pymongo import MongoClient
2from pymongo.operations import SearchIndexModel
3
4# Connect to your Atlas deployment
5uri = "<connection-string>"
6client = MongoClient(uri)
7
8database = client["sample_mflix"]
9collection = database["movies"]
10
11# Create the MongoDB Search index definition
12search_index_model = SearchIndexModel(
13 definition={
14 "mappings": {
15 "dynamic": True,
16 },
17 "synonyms": [
18 {
19 "analyzer": "lucene.standard",
20 "name": "my_synonyms",
21 "source": {
22 "collection": "synonymous_terms"
23 }
24 }
25 ]
26 },
27 name="default",
28)
29
30# Create the index
31result = collection.create_search_index(model=search_index_model)
32print(f"New index name: {result}")
3
python create-dynamic-index.py
New index name: default

To learn how to add a collection that configures words as synonyms to your cluster, and use this collection to create a MongoDB Search index and run MongoDB Search queries using synonyms, see How to Use Synonyms with MongoDB Search.

To see examples of text queries that use synonyms, see Synonyms Examples in the text reference page.

To see an example phrase queries that uses synonyms, see Synonyms Example in the phrase reference page.