> For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt

<!--
Tab options on this page. Append to the .md URL to filter:
  ?tabs=<id,...>   select specific tabs (e.g. ?tabs=nodejs,shell)
  ?allTabs=true    include every tab
  (no param)       default: one tab per tabset

Available tabs:
  other tabs: vib, jsonib, cloud, local, maven bom, gradle bom, maven, gradle, jib
-->

# How to Index Fields for Autocompletion

You can use the MongoDB Search `autocomplete` type to index text values in string fields for autocompletion. You can query fields indexed as `autocomplete` type using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator.

You can also use the `autocomplete` type to index:

- Fields whose value is an array of strings. To learn more, see [How to Index the Elements of an Array.](https://www.mongodb.com/docs/search/indexes/field-types/array-type.md#std-label-fts-array-ref)

- String fields inside an array of documents indexed as the [embeddedDocuments](https://www.mongodb.com/docs/search/indexes/field-types/embedded-documents-type.md#std-label-bson-data-types-embedded-documents) type. For index build time considerations, see [Index Build Time.](https://www.mongodb.com/docs/search/indexes/field-types/autocomplete-type.md#std-label-autocomplete-index-build-time)

For dynamic mapping considerations, see [Dynamic Mappings.](https://www.mongodb.com/docs/search/indexes/field-types/autocomplete-type.md#std-label-autocomplete-dynamic-mappings)

## Define the Index for the `autocomplete` Type

1. Retrieve your Service Account access token for the project.

   Use your service account to generate an access token, which authenticates your requests to the Atlas Administration API. To learn how to generate an access token, see [Make an API (Application Programming Interface) Request.](https://www.mongodb.com/docs/atlas/configure-api-access.md#std-label-example-api-request)

2. Make an API (Application Programming Interface) call.

   Replace the following values in the `curl` command below. This command sends a `POST` request to your cluster to create a MongoDB Search index with the `autocomplete` field type.

   - Replace \{`ACCESS-TOKEN`} with the output from the preceding step

   - 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

   ```shell
   curl --header "Authorization: Bearer ${ACCESS_TOKEN}" \
       --header "Accept: application/vnd.atlas.2025-03-12+json" \
       --header "Content-Type: application/json" \
       -X POST "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes" \
       -d '{ "collectionName": "<collection>",
           "database": "<database>",
           "name": "default",
           "type": "search",
           "definition": {
             "mappings": { 
               "dynamic": true|false, 
               "fields": { 
                 "<field-name>": { 
                   "type": "autocomplete",
                   "analyzer": "<lucene.analyzer>",
                   "tokenization": "edgeGram|rightEdgeGram|nGram",
                   "minGrams": <2>,
                   "maxGrams": <15>,
                   "foldDiacritics": true|false,
                   "similarity": { "type": "bm25|boolean|stableTfl" }
                 } 
               }
             }
           }
       }'
   ```

1) Create a `search-index.json` configuration file and specify the `autocomplete` type.

   ```json
   {
     "name": "default",
     "collectionName": "<collection>",
     "database": "<database>",
     "type": "search",
     "definition": {
       "mappings": {
         "dynamic": true|false, 
         "fields": {
           "<field-name>": {
             "type": "autocomplete",
             "analyzer": "<lucene.analyzer>",
             "tokenization": "edgeGram|rightEdgeGram|nGram",
             "minGrams": <2>,
             "maxGrams": <15>,
             "foldDiacritics": true|false,
             "similarity": { "type": "bm25|boolean|stableTfl" }
           }
         }
       }
     }
   }
   ```

2) Connect to the Atlas CLI

   In your terminal, connect to your cluster from the Atlas CLI. To learn more, see [Connect from the Atlas CLI.](https://www.mongodb.com/docs/atlas/cli/current/connect-atlas-cli/)

3) Create a MongoDB Search index.

   Run the [atlas clusters search indexes create](https://www.mongodb.com/docs/atlas/cli/current/command/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 `search-index.json` file:

   ```shell
   atlas clusters search indexes create --clusterName <cluster-name> --file <path-to-file>
   ```

1. Connect to your cluster using MongoDB Compass.

   Open [Compass](https://www.mongodb.com/try/download/compass) and connect to your cluster. For detailed instructions, see [Connect to a Cluster via Compass.](https://www.mongodb.com/docs/atlas/compass-connection.md#std-label-atlas-connect-via-compass)

2. Specify the database and collection.

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

3. Create the MongoDB Search index.

   Click the Indexes tab, then select Search Indexes.

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

   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](https://www.mongodb.com/docs/search/query/operators-collectors/overview.md#std-label-fts-operators). If you are creating multiple indexes, we recommend that you maintain a consistent, descriptive naming convention across your indexes.

   Specify the JSON (Javascript Object Notation) MongoDB Search index definition.

   ```json
   {
       "mappings": {
           "dynamic": true|false,
           "fields": {
               "<field-name>": {
                   "type": "autocomplete",
                   "analyzer": "<lucene-analyzer>",
                   "tokenization": "edgeGram|rightEdgeGram|nGram",
                   "minGrams": <2>,
                   "maxGrams": <15>,
                   "foldDiacritics": true|false,
                   "similarity": { "type": "bm25|boolean|stableTfl" }
               }
           }
       }
   }
   ```

   Click Create Search Index.

1) Connect to the deployment using `mongosh`.

   In your terminal, connect to your Atlas cloud-hosted deployment or local deployment from [`mongosh`](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh). For detailed instructions on how to connect, see [Connect to a Deployment.](https://www.mongodb.com/docs/mongodb-shell/connect/)

2) Switch to the database that contains the collection for which you want to create the index.

   ```shell
    use <database>
   ```

   **Output:**

   ```shell
   switched to db <database>
   ```

3) Run the `db.collection.createSearchIndex()` method to create the index.

   ```shell
   db.<collection>.createSearchIndex(
     "default",
       {
         "mappings": {
           "dynamic": true|false,
           "fields": {
           "<field-name>": {
             "type": "autocomplete",
             "analyzer": "<lucene-analyzer>",
             "tokenization": "edgeGram|rightEdgeGram|nGram",
             "minGrams": <2>,
             "maxGrams": <15>,
             "foldDiacritics": true|false,
             "similarity": { "type": "bm25|boolean|stableTfl" }
           }
         }
       }
     }
   )
   ```

   **Output:**

   ```text
   default
   ```

Choose your preferred configuration method in the Atlas UI and then select the database and collection.

### Visual Editor

1. Click Refine Your Index to configure your index.

2. In the Field Mappings section, click Add
   Field Mapping to open the Add Field Mapping window.

3. Click Customized Configuration.

4. Select the field to index from the Field Name dropdown.

   **Note:**

   You can't index fields that contain the dollar (`$`) sign at the start of the field name.

5. Click the Data Type dropdown and select Autocomplete.

6. Configure the field properties for the `autocomplete` type. To learn more, see [Field Properties](https://www.mongodb.com/docs/search/indexes/field-types/uuid-type.md#std-label-fts-field-types-uuid-options).

7. Click Add.

**Note:**

To configure the `similarity.type` property for string fields, use the JSON (Javascript Object Notation) Editor.

1. Set up the C project.

   In your terminal, navigate to where you want to create your application, then run the following command to create a directory called `atlas-search-project` for this project:

   ```shell
   # Create a new directory for the project
   mkdir atlas-search-project && cd atlas-search-project
   ```

   Add the C driver to your project by following the instructions in the [MongoDB C Driver documentation.](https://www.mongodb.com/docs/languages/c/c-driver/current/get-started/)

2. Define the index.

   Create a `create_index.c` file in your project directory, and copy and paste the following code into the file.

   ```c
   #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" : [ {
               "name" : "default",
               "definition" : {
                 "mappings": {
                   "dynamic": true|false,
                   "fields": {
                     "<field-name>": {
                       "type": "autocomplete",
                       "analyzer": "<lucene.analyzer>",
                       "tokenization": "edgeGram|rightEdgeGram|nGram",
                       "minGrams": <2>,
                       "maxGrams": <15>,
                       "foldDiacritics": true|false,
                       "similarity": { "type": "bm25|boolean|stableTfl" }
                     }
                   }
                 },
               }
   	    } ]
   	});

       // 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 MongoDB 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;
   }
   ```

   Replace `<connection-string>` with the connection string for your Atlas cluster or local Atlas deployment.

   ### Atlas Cluster

   Your connection string should use the following format:

   ```text
   mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net
   ```

   To learn more, see [Connect to a Cluster via Client Libraries.](https://www.mongodb.com/docs/atlas/driver-connection.md#std-label-connect-via-driver)

3. Set up a CMake application

   To configure your application, create a `CMakeLists.txt` file in your project directory. Then, add the following code to the file:

   ```txt
   cmake_minimum_required(VERSION 3.11)
   project(atlas-search-index LANGUAGES C)
   add_executable (index.out create_index.c)
   find_package(mongoc <version> REQUIRED)
   target_link_libraries(index.out mongoc::mongoc)

   ```

   The preceding code performs the following actions:

   - Configures a C project.

   - Creates a `index.out` executable for your application.

   - Finds and requires the C driver. Replace the `<version>` placeholder with your C driver version autocomplete, such as `2.0.0`.

   - Links the program to the `libmongoc` library.

   **Note:**

   In the sample `CMakeLists.txt` file, the `mongoc::mongoc` target points to either the static library or the shared library. The library type depends on which one is available and whichever type the user specifies in the `MONGOC_DEFAULT_IMPORTED_LIBRARY_TYPE` CMake configuration setting. If you don't set this value and both library types are available, `mongoc::mongoc` uses the static library.

   You can use the `mongoc::static` target to explicitly use the static library or the `mongoc::shared` target to use the shared library.

4. Create the index.

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

   ```shell
   cmake -S. -Bcmake-build
   cmake --build cmake-build --target index.out
   ./cmake-build/index.out
   ```

   **Output:**

   ```text
   Index created!
   ```

1) Set up and initialize the .NET/C# project.

   In your terminal, navigate to where you want to create your application, then run the following command to create a directory called `atlas-search-project` and initialize your project in that directory:

   ```shell
   # Create a new directory and initialize the project
   mkdir atlas-search-project && cd atlas-search-project
   dotnet new console

   # Add the MongoDB .NET/C# Driver to your project
   dotnet add package MongoDB.Driver
   ```

   For more detailed installation instructions, see the [MongoDB .NET/C# Driver documentation.](https://www.mongodb.com/docs/drivers/csharp/current/get-started/)

2) Define the index.

   Paste the following code into the `Program.cs` file.

   ```csharp
   using MongoDB.Bson;
   using MongoDB.Driver;

   // connect to your Atlas deployment
   var uri = "<connection-string>";

   var client = new MongoClient(uri);

   var db = client.GetDatabase("<database>");
   var collection = db.GetCollection<BsonDocument>("<collection>");

   // define your MongoDB Search index
   var index =  new CreateSearchIndexModel(
     "default", new BsonDocument
     {
       { "mappings", new BsonDocument
         {
           { "dynamic", true|false },
           { "fields", new BsonDocument
             {
               { "<field-name>", new BsonDocument
                 {
                   { "type", "autocomplete" },
                   { "analyzer", "<lucene.analyzer>" },
                   { "tokenization", "edgeGram|rightEdgeGram|nGram" },
                   { "minGrams", <2> },
                   { "maxGrams", <15> },
                   { "foldDiacritics", true|false },
                   { "similarity", new BsonDocument { { "type", "bm25|boolean|stableTfl" } } }
                 }
               }
             }
           }
         }
       }
     });

   var result = collection.SearchIndexes.CreateOne(index);
   Console.WriteLine($"New index name: {result}");
   ```

   Replace `<connection-string>` with the connection string for your Atlas cluster or local Atlas deployment.

   ### Atlas Cluster

   Your connection string should use the following format:

   ```text
   mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net
   ```

   To learn more, see [Connect to a Cluster via Client Libraries.](https://www.mongodb.com/docs/atlas/driver-connection.md#std-label-connect-via-driver)

3) Create the index.

   ```shell
   dotnet run Program.cs
   ```

   **Output:**

   ```text
   New index name: default
   ```

1. Set up the C++ project.

   In your terminal, navigate to where you want to create your application, then run the following command to create a directory called `atlas-search-project` for this project:

   ```shell
   # Create a new directory for the project
   mkdir atlas-search-project && cd atlas-search-project
   ```

   For more detailed installation instructions, see the [MongoDB C++ Driver documentation.](https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/get-started/)

2. Define the index.

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

   ```cpp
   #include <iostream>

   #include <bsoncxx/builder/basic/document.hpp>
   #include <bsoncxx/json.hpp>
   #include <mongocxx/client.hpp>
   #include <mongocxx/instance.hpp>
   #include <mongocxx/uri.hpp>

   using bsoncxx::builder::basic::kvp;
   using bsoncxx::builder::basic::make_document;

   int main(){

       mongocxx::instance instance;
       mongocxx::uri uri("<connection-string>");
       mongocxx::client client(uri);

       auto db = client["<database>"];
       auto collection = db["<collection>"];

       // instantiate a ``mongocxx::search_index_view`` on your collection
       auto siv = collection.search_indexes();

       {
           auto name = "default";
           auto definition = make_document(
               kvp("mappings", make_document(
                   kvp("dynamic", true|false),
                   kvp("fields", make_document(
                       kvp("<field-name>", make_document(
                           kvp("type", "autocomplete"),
                           kvp("analyzer", "<lucene.analyzer>"),
                           kvp("tokenization", "edgeGram|rightEdgeGram|nGram"),
                           kvp("minGrams", <2>),
                           kvp("maxGrams", <15>),
                           kvp("foldDiacritics", true|false),
                           kvp("similarity", make_document(
                               kvp("type", "bm25|boolean|stableTfl")
                           ))
                       ))
                   ))
               ))
           );

           auto model = mongocxx::search_index_model(name, definition.view());

           // Create the search index
           auto result = siv.create_one(model);
           std::cout << "New index name: " << result << std::endl;
       }
   }

   ```

   Replace `<connection-string>` with the connection string for your Atlas cluster or local Atlas deployment.

   ### Atlas Cluster

   Your connection string should use the following format:

   ```text
   mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net
   ```

   To learn more, see [Connect to a Cluster via Client Libraries.](https://www.mongodb.com/docs/atlas/driver-connection.md#std-label-connect-via-driver)

3. Create the index.

   ```shell
   c++ --std=c++17 CreateIndex.cpp $(pkg-config --cflags --libs libmongocxx) -o ./app.out
   ./app.out
   ```

   **Output:**

   ```text
   New index name: default
   ```

   **Tip: MacOS Error**

   MacOS users might see the following error after running the preceding commands:

   ```sh
   dyld[54430]: Library not loaded: @rpath/libmongocxx._noabi.dylib
   ```

   To resolve this error, use the `-Wl,-rpath` linker option to set the `@rpath`, as shown in the following code:

   ```sh
   c++ --std=c++17 CreateIndex.cpp -Wl,-rpath,/usr/local/lib/ $(pkg-config --cflags --libs libmongocxx) -o ./app.out
   ./app.out
   ```

1) Set up and initialize the Go module.

   In your terminal, navigate to where you want to create your application, then run the following command to create a directory called `atlas-search-project` and initialize your project in that directory:

   ```shell
   # Create a new directory and initialize the project
   mkdir atlas-search-project && cd atlas-search-project
   go mod init atlas-search-project

   # Add the MongoDB Go Driver to your project
   go get go.mongodb.org/mongo-driver/v2/mongo
   ```

   For more detailed installation instructions, see the [MongoDB Go Driver documentation.](https://www.mongodb.com/docs/drivers/go/current/get-started.md#std-label-go-get-started)

2) Define the index.

   Create a `create_index.go` file in your project directory, and copy and paste the following code into the file.

   ```go
   package main

   import (
   	"context"
   	"fmt"
   	"log"

   	"go.mongodb.org/mongo-driver/v2/bson"
   	"go.mongodb.org/mongo-driver/v2/mongo"
   	"go.mongodb.org/mongo-driver/v2/mongo/options"
   )

   func main() {
   	ctx := context.Background()
   	uri := "<connection-string>"
   	client, err := mongo.Connect(options.Client().
   		ApplyURI(uri))
   	if err != nil {
   		panic(err)
   	}

   	defer func() {
   		if err := client.Disconnect(context.TODO()); err != nil {
   			panic(err)
   		}
   	}()

   	coll := client.Database("<database>").Collection("<collection>")
   	const indexName = "default"
   	opts := options.SearchIndexes().SetName(indexName).SetType("search")

   	// Define the MongoDB Search index for the autocomplete field type
   	searchIndexModel := mongo.SearchIndexModel{
   		Definition: bson.D{
   			{"mappings", bson.D{
   				{"dynamic", true|false},
   				{"fields", bson.D{
   					{"<field-name>", bson.D{
   						{"type", "autocomplete"},
   						{"analyzer", "<lucene.analyzer>"},
   						{"tokenization", "edgeGram|rightEdgeGram|nGram"},
   						{"minGrams", <2>},
   						{"maxGrams", <15>},
   						{"foldDiacritics", true|false},
   						{"similarity", bson.D{ {"type", "bm25|boolean|stableTfl"} }},
   					}},
   				}},
   			}},
   		},
   		Options: opts,
   	}

   	// Create the index
   	searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, searchIndexModel)
   	if err != nil {
   		log.Fatalf("Failed to create the Atlas Search index: %v", err)
   	}

   	fmt.Println("Name of index created: " + searchIndexName)
   }
   ```

   Replace `<connection-string>` with the connection string for your Atlas cluster or local Atlas deployment.

   ### Atlas Cluster

   Your connection string should use the following format:

   ```text
   mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net
   ```

   IMPORTANT: Ensure that your connection string includes your database user's credentials. To learn more about finding your connection string, see [Connect to a Cluster via Client Libraries.](https://www.mongodb.com/docs/atlas/driver-connection.md#std-label-connect-via-driver)

3) Create the index.

   ```shell
   go run create_index.go
   ```

   **Output:**

   ```text
   New index name: default
   ```

1. Set up your Java project with the MongoDB Java driver.

   In your IDE, create a new [Maven](https://maven.apache.org/) or [Gradle](https://gradle.org/) project. Add the Bill of Materials (BOM) for MongoDB JVM artifacts to your project to organize dependency versions. The BOM simplifies dependency management by ensuring that you maintain consistent and compatible versions of dependencies, such as between the Java driver and the core driver library. Use the BOM to avoid version conflicts and simplify upgrades.

   Select from the following **Maven** and **Gradle** tabs to view instructions for adding the BOM for each dependency manager:

   ### Maven

   Add the following code to the `dependencyManagement` list in your `pom.xml` file:

   ```xml
   <dependencyManagement>
       <dependencies>
           <dependency>
               <groupId>org.mongodb</groupId>
               <artifactId>mongodb-driver-bom</artifactId>
               <version>5.5.1</version>
               <type>pom</type>
               <scope>import</scope>
           </dependency>
       </dependencies>
   </dependencyManagement>
   ```

   To view a list of dependencies that the BOM manages, see the [mongodb-driver-bom dependency listing](https://mvnrepository.com/artifact/org.mongodb/mongodb-driver-bom/5.51) on the Maven Repository website.

   After adding the BOM, select from the following **Maven** and **Gradle** tabs to view instructions for adding the MongoDB Java Sync Driver as a dependency in your project:

   ### Maven

   Add the following code to the `dependencies` array in your Maven project's `pom.xml` file:

   ```xml
   <dependencies>
       <dependency>    
         <groupId>org.mongodb</groupId>    
         <artifactId>mongodb-driver-sync</artifactId>    
         <version>4.11.1</version>    
       </dependency>
   </dependencies>

   ```

   Run your package manager to install the dependencies to your project.

   For more detailed installation instructions and version compatibility, see the [MongoDB Java Driver documentation.](https://www.mongodb.com/docs/drivers/java/sync/current/get-started/)

2. Define the index.

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

   ```java
   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("<database>");
               MongoCollection<Document> collection = database.getCollection("<collection>");
               String indexName = "default";

               Document searchIdx = new Document("mappings",
                       new Document("dynamic", true|false)
                           .append("fields", new Document("<field-name>", 
                                                 new Document("type", "autocomplete") 
                                                     .append("analyzer", "<lucene.analyzer>")
                                                     .append("tokenization", "edgeGram|rightEdgeGram|nGram")
                                                     .append("minGrams", <2>)
                                                     .append("analymaxGramszer", <15>)
                                                     .append("foldDiacritics", true|false)
                                                     .append("similarity", new Document("type", "bm25|boolean|stableTfl"))
                                                     )));

               collection.createSearchIndex(indexName, searchIdx);
               System.out.println("New index name: " + indexName);
           } catch (Exception e) {
               System.err.println("Error creating Atlas Search index: " + e.getMessage());
           }
       }
   }
   ```

   Replace `<connection-string>` with the connection string for your Atlas cluster or local Atlas deployment.

   ### Atlas Cluster

   Your connection string should use the following format:

   ```text
   mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net
   ```

   To learn more, see [Connect to a Cluster via Client Libraries.](https://www.mongodb.com/docs/atlas/driver-connection.md#std-label-connect-via-driver)

3. Compile and run the file to create the index.

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

   ```shell
   javac CreateIndex.java
   java CreateIndex
   ```

   **Output:**

   ```text
   New index name: default
   ```

1) Initialize your Node.js project.

   ```shell
   # Create a new directory and initialize the project
   mkdir atlas-search-project && cd atlas-search-project
   npm init -y

   # Add the MongoDB Node.js Driver to your project
   npm install mongodb
   ```

   For detailed installation instructions, see the [MongoDB Node Driver documentation.](https://www.mongodb.com/docs/drivers/node/current/)

2) Define the index.

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

   ```javascript
   const { MongoClient } = require("mongodb");

   // connect to your Atlas deployment
   const uri =  "<connection-string>";

   const client = new MongoClient(uri);

   async function run() {
     try {

       // set namespace
       const database = client.db("<database>");
       const collection = database.collection("<collection>");

       // define your MongoDB Search index
       const index = {
         name: "default",
         definition: {
           /* search index definition fields */
           "mappings": {
             "dynamic": true|false,
             "fields": {
               "<field-name>": {
                 "type": "autocomplete",
                 "analyzer": "<lucene.analyzer>",
                 "tokenization": "edgeGram|rightEdgeGram|nGram",
                 "minGrams": <2>,
                 "maxGrams": <15>,
                 "foldDiacritics": true|false,
                 "similarity": { "type": "bm25|boolean|stableTfl" }
               }
             }
           }
         }
       }

       // run the helper method
       const result = await collection.createSearchIndex(index);
       console.log("New index name: " + result);
     } finally {
       await client.close();
     }
   }

   run().catch(console.dir);
   ```

   Replace `<connection-string>` with the connection string for your Atlas cluster or local Atlas deployment.

   ### Atlas Cluster

   Your connection string should use the following format:

   ```text
   mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net
   ```

   To learn more, see [Connect to a Cluster via Client Libraries.](https://www.mongodb.com/docs/atlas/driver-connection.md#std-label-connect-via-driver)

3) Create the index.

   ```shell
   node create-index.js
   ```

   **Output:**

   ```text
   New index name: default
   ```

1. Set up the Python project.

   ```shell
   # Create a new directory for the project
   mkdir atlas-search-project && cd atlas-search-project

   # Install PyMongo
   pip install pymongo
   ```

   For detailed installation instructions, see [MongoDB Python Driver (PyMongo).](https://www.mongodb.com/docs/languages/python/pymongo-driver/get-started.md#std-label-pymongo-get-started-download-and-install)

2. Define the index.

   Create a `create_index.py` file in your project directory, and copy and paste the following code into the file.

   ```python
   from pymongo import MongoClient
   from pymongo.operations import SearchIndexModel

   # connect to your Atlas deployment
   uri = "<connection-string>"
   client = MongoClient(uri)

   # set namespace
   database = client["<database>"]
   collection = database["<collection>"]

   # define your MongoDB Search index
   search_index_model = SearchIndexModel(
       definition={
           "mappings": {
               "dynamic": True|False,
               "fields": {
                   "<field_name>":{
                      "type": "autocomplete",
                      "analyzer": "<lucene.analyzer>",
                      "tokenization": "nGram",
                      "minGrams": <2>,
                      "maxGrams": <15>,
                      "foldDiacritics": True|False,
                      "similarity": { "type": "bm25|boolean|stableTfl" }
                   }
               }
           },
       },
       name="default",
   )

   # create the index
   result = collection.create_search_index(model=search_index_model)
   print(f"New index name: {result}")

   ```

   Replace `<connection-string>` with the connection string for your Atlas cluster or local Atlas deployment.

   ### Atlas Cluster

   Your connection string should use the following format:

   ```text
   mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net
   ```

   To learn more, see [Connect to a Cluster via Client Libraries.](https://www.mongodb.com/docs/atlas/driver-connection.md#std-label-connect-via-driver)

3. Create the index.

   ```shell
   python create_index.py
   ```

   **Output:**

   ```text
   New index name: default
   ```

1) Create a `search-index.json` configuration file and specify the `autocomplete` type.

   ```json
   {
     "name": "default",
     "collectionName": "<collection>",
     "database": "<database>",
     "type": "search",
     "definition": {
       "mappings": {
         "dynamic": true|false, 
         "fields": {
           "<field-name>": {
             "type": "autocomplete",
             "analyzer": "<lucene.analyzer>",
             "tokenization": "edgeGram|rightEdgeGram|nGram",
             "minGrams": <2>,
             "maxGrams": <15>,
             "foldDiacritics": true|false,
             "similarity": { "type": "bm25|boolean|stableTfl" }
           }
         }
       }
     }
   }
   ```

2) Connect to the Atlas CLI

   In your terminal, connect to your local deployment from the Atlas CLI. To learn more, see [Connect from the Atlas CLI.](https://www.mongodb.com/docs/atlas/cli/current/connect-atlas-cli/)

3) Create a MongoDB Search index.

   Run the [atlas deployments search indexes create](https://www.mongodb.com/docs/atlas/cli/current/command/atlas-deployments-search-indexes-create/) command in your terminal, replacing `<path-to-file>` with the path to the `search-index.json` file:

   ```shell
   atlas deployments search indexes create --file <path-to-file>
   ```

1. Connect to your cluster using MongoDB Compass.

   Open [Compass](https://www.mongodb.com/try/download/compass) and connect to your cluster. For detailed instructions, see [Connect to a Cluster via Compass.](https://www.mongodb.com/docs/atlas/compass-connection.md#std-label-atlas-connect-via-compass)

2. Specify the database and collection.

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

3. Create the MongoDB Search index.

   Click the Indexes tab, then select Search Indexes.

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

   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](https://www.mongodb.com/docs/search/query/operators-collectors/overview.md#std-label-fts-operators). If you are creating multiple indexes, we recommend that you maintain a consistent, descriptive naming convention across your indexes.

   Specify the JSON (Javascript Object Notation) MongoDB Search index definition.

   ```json
   {
       "mappings": {
           "dynamic": true|false,
           "fields": {
               "<field-name>": {
                   "type": "autocomplete",
                   "analyzer": "<lucene-analyzer>",
                   "tokenization": "edgeGram|rightEdgeGram|nGram",
                   "minGrams": <2>,
                   "maxGrams": <15>,
                   "foldDiacritics": true|false,
                   "similarity": { "type": "bm25|boolean|stableTfl" }
               }
           }
       }
   }
   ```

   Click Create Search Index.

1) Connect to the deployment using `mongosh`.

   In your terminal, connect to your Atlas cloud-hosted deployment or local deployment from [`mongosh`](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh). For detailed instructions on how to connect, see [Connect to a Deployment.](https://www.mongodb.com/docs/mongodb-shell/connect/)

2) Switch to the database that contains the collection for which you want to create the index.

   ```shell
    use <database>
   ```

   **Output:**

   ```shell
   switched to db <database>
   ```

3) Run the `db.collection.createSearchIndex()` method to create the index.

   ```shell
   db.<collection>.createSearchIndex(
     "default",
       {
         "mappings": {
           "dynamic": true|false,
           "fields": {
           "<field-name>": {
             "type": "autocomplete",
             "analyzer": "<lucene-analyzer>",
             "tokenization": "edgeGram|rightEdgeGram|nGram",
             "minGrams": <2>,
             "maxGrams": <15>,
             "foldDiacritics": true|false,
             "similarity": { "type": "bm25|boolean|stableTfl" }
           }
         }
       }
     }
   )
   ```

   **Output:**

   ```text
   default
   ```

1. Set up the C project.

   In your terminal, navigate to where you want to create your application, then run the following command to create a directory called `atlas-search-project` for this project:

   ```shell
   # Create a new directory for the project
   mkdir atlas-search-project && cd atlas-search-project
   ```

   Add the C driver to your project by following the instructions in the [MongoDB C Driver documentation.](https://www.mongodb.com/docs/languages/c/c-driver/current/get-started/)

2. Define the index.

   Create a `create_index.c` file in your project directory, and copy and paste the following code into the file.

   ```c
   #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" : [ {
               "name" : "default",
               "definition" : {
                 "mappings": {
                   "dynamic": true|false,
                   "fields": {
                     "<field-name>": {
                       "type": "autocomplete",
                       "analyzer": "<lucene.analyzer>",
                       "tokenization": "edgeGram|rightEdgeGram|nGram",
                       "minGrams": <2>,
                       "maxGrams": <15>,
                       "foldDiacritics": true|false,
                       "similarity": { "type": "bm25|boolean|stableTfl" }
                     }
                   }
                 },
               }
   	    } ]
   	});

       // 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 MongoDB 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;
   }
   ```

   Replace `<connection-string>` with the connection string for your Atlas cluster or local Atlas deployment.

   ### Atlas Cluster

   Your connection string should use the following format:

   ```text
   mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net
   ```

   To learn more, see [Connect to a Cluster via Client Libraries.](https://www.mongodb.com/docs/atlas/driver-connection.md#std-label-connect-via-driver)

3. Set up a CMake application

   To configure your application, create a `CMakeLists.txt` file in your project directory. Then, add the following code to the file:

   ```txt
   cmake_minimum_required(VERSION 3.11)
   project(atlas-search-index LANGUAGES C)
   add_executable (index.out create_index.c)
   find_package(mongoc <version> REQUIRED)
   target_link_libraries(index.out mongoc::mongoc)

   ```

   The preceding code performs the following actions:

   - Configures a C project.

   - Creates a `index.out` executable for your application.

   - Finds and requires the C driver. Replace the `<version>` placeholder with your C driver version autocomplete, such as `2.0.0`.

   - Links the program to the `libmongoc` library.

   **Note:**

   In the sample `CMakeLists.txt` file, the `mongoc::mongoc` target points to either the static library or the shared library. The library type depends on which one is available and whichever type the user specifies in the `MONGOC_DEFAULT_IMPORTED_LIBRARY_TYPE` CMake configuration setting. If you don't set this value and both library types are available, `mongoc::mongoc` uses the static library.

   You can use the `mongoc::static` target to explicitly use the static library or the `mongoc::shared` target to use the shared library.

4. Create the index.

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

   ```shell
   cmake -S. -Bcmake-build
   cmake --build cmake-build --target index.out
   ./cmake-build/index.out
   ```

   **Output:**

   ```text
   Index created!
   ```

1) Set up and initialize the .NET/C# project.

   In your terminal, navigate to where you want to create your application, then run the following command to create a directory called `atlas-search-project` and initialize your project in that directory:

   ```shell
   # Create a new directory and initialize the project
   mkdir atlas-search-project && cd atlas-search-project
   dotnet new console

   # Add the MongoDB .NET/C# Driver to your project
   dotnet add package MongoDB.Driver
   ```

   For more detailed installation instructions, see the [MongoDB .NET/C# Driver documentation.](https://www.mongodb.com/docs/drivers/csharp/current/get-started/)

2) Define the index.

   Paste the following code into the `Program.cs` file.

   ```csharp
   using MongoDB.Bson;
   using MongoDB.Driver;

   // connect to your Atlas deployment
   var uri = "<connection-string>";

   var client = new MongoClient(uri);

   var db = client.GetDatabase("<database>");
   var collection = db.GetCollection<BsonDocument>("<collection>");

   // define your MongoDB Search index
   var index =  new CreateSearchIndexModel(
     "default", new BsonDocument
     {
       { "mappings", new BsonDocument
         {
           { "dynamic", true|false },
           { "fields", new BsonDocument
             {
               { "<field-name>", new BsonDocument
                 {
                   { "type", "autocomplete" },
                   { "analyzer", "<lucene.analyzer>" },
                   { "tokenization", "edgeGram|rightEdgeGram|nGram" },
                   { "minGrams", <2> },
                   { "maxGrams", <15> },
                   { "foldDiacritics", true|false },
                   { "similarity", new BsonDocument { { "type", "bm25|boolean|stableTfl" } } }
                 }
               }
             }
           }
         }
       }
     });

   var result = collection.SearchIndexes.CreateOne(index);
   Console.WriteLine($"New index name: {result}");
   ```

   Replace `<connection-string>` with the connection string for your Atlas cluster or local Atlas deployment.

   ### Atlas Cluster

   Your connection string should use the following format:

   ```text
   mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net
   ```

   To learn more, see [Connect to a Cluster via Client Libraries.](https://www.mongodb.com/docs/atlas/driver-connection.md#std-label-connect-via-driver)

3) Create the index.

   ```shell
   dotnet run Program.cs
   ```

   **Output:**

   ```text
   New index name: default
   ```

1. Set up the C++ project.

   In your terminal, navigate to where you want to create your application, then run the following command to create a directory called `atlas-search-project` for this project:

   ```shell
   # Create a new directory for the project
   mkdir atlas-search-project && cd atlas-search-project
   ```

   For more detailed installation instructions, see the [MongoDB C++ Driver documentation.](https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/get-started/)

2. Define the index.

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

   ```cpp
   #include <iostream>

   #include <bsoncxx/builder/basic/document.hpp>
   #include <bsoncxx/json.hpp>
   #include <mongocxx/client.hpp>
   #include <mongocxx/instance.hpp>
   #include <mongocxx/uri.hpp>

   using bsoncxx::builder::basic::kvp;
   using bsoncxx::builder::basic::make_document;

   int main(){

       mongocxx::instance instance;
       mongocxx::uri uri("<connection-string>");
       mongocxx::client client(uri);

       auto db = client["<database>"];
       auto collection = db["<collection>"];

       // instantiate a ``mongocxx::search_index_view`` on your collection
       auto siv = collection.search_indexes();

       {
           auto name = "default";
           auto definition = make_document(
               kvp("mappings", make_document(
                   kvp("dynamic", true|false),
                   kvp("fields", make_document(
                       kvp("<field-name>", make_document(
                           kvp("type", "autocomplete"),
                           kvp("analyzer", "<lucene.analyzer>"),
                           kvp("tokenization", "edgeGram|rightEdgeGram|nGram"),
                           kvp("minGrams", <2>),
                           kvp("maxGrams", <15>),
                           kvp("foldDiacritics", true|false),
                           kvp("similarity", make_document(
                               kvp("type", "bm25|boolean|stableTfl")
                           ))
                       ))
                   ))
               ))
           );

           auto model = mongocxx::search_index_model(name, definition.view());

           // Create the search index
           auto result = siv.create_one(model);
           std::cout << "New index name: " << result << std::endl;
       }
   }

   ```

   Replace `<connection-string>` with the connection string for your Atlas cluster or local Atlas deployment.

   ### Atlas Cluster

   Your connection string should use the following format:

   ```text
   mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net
   ```

   To learn more, see [Connect to a Cluster via Client Libraries.](https://www.mongodb.com/docs/atlas/driver-connection.md#std-label-connect-via-driver)

3. Create the index.

   ```shell
   c++ --std=c++17 CreateIndex.cpp $(pkg-config --cflags --libs libmongocxx) -o ./app.out
   ./app.out
   ```

   **Output:**

   ```text
   New index name: default
   ```

   **Tip: MacOS Error**

   MacOS users might see the following error after running the preceding commands:

   ```sh
   dyld[54430]: Library not loaded: @rpath/libmongocxx._noabi.dylib
   ```

   To resolve this error, use the `-Wl,-rpath` linker option to set the `@rpath`, as shown in the following code:

   ```sh
   c++ --std=c++17 CreateIndex.cpp -Wl,-rpath,/usr/local/lib/ $(pkg-config --cflags --libs libmongocxx) -o ./app.out
   ./app.out
   ```

1) Set up and initialize the Go module.

   In your terminal, navigate to where you want to create your application, then run the following command to create a directory called `atlas-search-project` and initialize your project in that directory:

   ```shell
   # Create a new directory and initialize the project
   mkdir atlas-search-project && cd atlas-search-project
   go mod init atlas-search-project

   # Add the MongoDB Go Driver to your project
   go get go.mongodb.org/mongo-driver/v2/mongo
   ```

   For more detailed installation instructions, see the [MongoDB Go Driver documentation.](https://www.mongodb.com/docs/drivers/go/current/get-started.md#std-label-go-get-started)

2) Define the index.

   Create a `create_index.go` file in your project directory, and copy and paste the following code into the file.

   ```go
   package main

   import (
   	"context"
   	"fmt"
   	"log"

   	"go.mongodb.org/mongo-driver/v2/bson"
   	"go.mongodb.org/mongo-driver/v2/mongo"
   	"go.mongodb.org/mongo-driver/v2/mongo/options"
   )

   func main() {
   	ctx := context.Background()
   	uri := "<connection-string>"
   	client, err := mongo.Connect(options.Client().
   		ApplyURI(uri))
   	if err != nil {
   		panic(err)
   	}

   	defer func() {
   		if err := client.Disconnect(context.TODO()); err != nil {
   			panic(err)
   		}
   	}()

   	coll := client.Database("<database>").Collection("<collection>")
   	const indexName = "default"
   	opts := options.SearchIndexes().SetName(indexName).SetType("search")

   	// Define the MongoDB Search index for the autocomplete field type
   	searchIndexModel := mongo.SearchIndexModel{
   		Definition: bson.D{
   			{"mappings", bson.D{
   				{"dynamic", true|false},
   				{"fields", bson.D{
   					{"<field-name>", bson.D{
   						{"type", "autocomplete"},
   						{"analyzer", "<lucene.analyzer>"},
   						{"tokenization", "edgeGram|rightEdgeGram|nGram"},
   						{"minGrams", <2>},
   						{"maxGrams", <15>},
   						{"foldDiacritics", true|false},
   						{"similarity", bson.D{ {"type", "bm25|boolean|stableTfl"} }},
   					}},
   				}},
   			}},
   		},
   		Options: opts,
   	}

   	// Create the index
   	searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, searchIndexModel)
   	if err != nil {
   		log.Fatalf("Failed to create the Atlas Search index: %v", err)
   	}

   	fmt.Println("Name of index created: " + searchIndexName)
   }
   ```

   Replace `<connection-string>` with the connection string for your Atlas cluster or local Atlas deployment.

   ### Atlas Cluster

   Your connection string should use the following format:

   ```text
   mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net
   ```

   IMPORTANT: Ensure that your connection string includes your database user's credentials. To learn more about finding your connection string, see [Connect to a Cluster via Client Libraries.](https://www.mongodb.com/docs/atlas/driver-connection.md#std-label-connect-via-driver)

3) Create the index.

   ```shell
   go run create_index.go
   ```

   **Output:**

   ```text
   New index name: default
   ```

1. Set up your Java project with the MongoDB Java driver.

   In your IDE, create a new [Maven](https://maven.apache.org/) or [Gradle](https://gradle.org/) project. Add the Bill of Materials (BOM) for MongoDB JVM artifacts to your project to organize dependency versions. The BOM simplifies dependency management by ensuring that you maintain consistent and compatible versions of dependencies, such as between the Java driver and the core driver library. Use the BOM to avoid version conflicts and simplify upgrades.

   Select from the following **Maven** and **Gradle** tabs to view instructions for adding the BOM for each dependency manager:

   ### Maven

   Add the following code to the `dependencyManagement` list in your `pom.xml` file:

   ```xml
   <dependencyManagement>
       <dependencies>
           <dependency>
               <groupId>org.mongodb</groupId>
               <artifactId>mongodb-driver-bom</artifactId>
               <version>5.5.1</version>
               <type>pom</type>
               <scope>import</scope>
           </dependency>
       </dependencies>
   </dependencyManagement>
   ```

   To view a list of dependencies that the BOM manages, see the [mongodb-driver-bom dependency listing](https://mvnrepository.com/artifact/org.mongodb/mongodb-driver-bom/5.51) on the Maven Repository website.

   After adding the BOM, select from the following **Maven** and **Gradle** tabs to view instructions for adding the MongoDB Java Sync Driver as a dependency in your project:

   ### Maven

   Add the following code to the `dependencies` array in your Maven project's `pom.xml` file:

   ```xml
   <dependencies>
       <dependency>    
         <groupId>org.mongodb</groupId>    
         <artifactId>mongodb-driver-sync</artifactId>    
         <version>4.11.1</version>    
       </dependency>
   </dependencies>

   ```

   Run your package manager to install the dependencies to your project.

   For more detailed installation instructions and version compatibility, see the [MongoDB Java Driver documentation.](https://www.mongodb.com/docs/drivers/java/sync/current/get-started/)

2. Define the index.

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

   ```java
   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("<database>");
               MongoCollection<Document> collection = database.getCollection("<collection>");
               String indexName = "default";

               Document searchIdx = new Document("mappings",
                       new Document("dynamic", true|false)
                           .append("fields", new Document("<field-name>", 
                                                 new Document("type", "autocomplete") 
                                                     .append("analyzer", "<lucene.analyzer>")
                                                     .append("tokenization", "edgeGram|rightEdgeGram|nGram")
                                                     .append("minGrams", <2>)
                                                     .append("analymaxGramszer", <15>)
                                                     .append("foldDiacritics", true|false)
                                                     .append("similarity", new Document("type", "bm25|boolean|stableTfl"))
                                                     )));

               collection.createSearchIndex(indexName, searchIdx);
               System.out.println("New index name: " + indexName);
           } catch (Exception e) {
               System.err.println("Error creating Atlas Search index: " + e.getMessage());
           }
       }
   }
   ```

   Replace `<connection-string>` with the connection string for your Atlas cluster or local Atlas deployment.

   ### Atlas Cluster

   Your connection string should use the following format:

   ```text
   mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net
   ```

   To learn more, see [Connect to a Cluster via Client Libraries.](https://www.mongodb.com/docs/atlas/driver-connection.md#std-label-connect-via-driver)

3. Compile and run the file to create the index.

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

   ```shell
   javac CreateIndex.java
   java CreateIndex
   ```

   **Output:**

   ```text
   New index name: default
   ```

1) Initialize your Node.js project.

   ```shell
   # Create a new directory and initialize the project
   mkdir atlas-search-project && cd atlas-search-project
   npm init -y

   # Add the MongoDB Node.js Driver to your project
   npm install mongodb
   ```

   For detailed installation instructions, see the [MongoDB Node Driver documentation.](https://www.mongodb.com/docs/drivers/node/current/)

2) Define the index.

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

   ```javascript
   const { MongoClient } = require("mongodb");

   // connect to your Atlas deployment
   const uri =  "<connection-string>";

   const client = new MongoClient(uri);

   async function run() {
     try {

       // set namespace
       const database = client.db("<database>");
       const collection = database.collection("<collection>");

       // define your MongoDB Search index
       const index = {
         name: "default",
         definition: {
           /* search index definition fields */
           "mappings": {
             "dynamic": true|false,
             "fields": {
               "<field-name>": {
                 "type": "autocomplete",
                 "analyzer": "<lucene.analyzer>",
                 "tokenization": "edgeGram|rightEdgeGram|nGram",
                 "minGrams": <2>,
                 "maxGrams": <15>,
                 "foldDiacritics": true|false,
                 "similarity": { "type": "bm25|boolean|stableTfl" }
               }
             }
           }
         }
       }

       // run the helper method
       const result = await collection.createSearchIndex(index);
       console.log("New index name: " + result);
     } finally {
       await client.close();
     }
   }

   run().catch(console.dir);
   ```

   Replace `<connection-string>` with the connection string for your Atlas cluster or local Atlas deployment.

   ### Atlas Cluster

   Your connection string should use the following format:

   ```text
   mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net
   ```

   To learn more, see [Connect to a Cluster via Client Libraries.](https://www.mongodb.com/docs/atlas/driver-connection.md#std-label-connect-via-driver)

3) Create the index.

   ```shell
   node create-index.js
   ```

   **Output:**

   ```text
   New index name: default
   ```

1. Set up the Python project.

   ```shell
   # Create a new directory for the project
   mkdir atlas-search-project && cd atlas-search-project

   # Install PyMongo
   pip install pymongo
   ```

   For detailed installation instructions, see [MongoDB Python Driver (PyMongo).](https://www.mongodb.com/docs/languages/python/pymongo-driver/get-started.md#std-label-pymongo-get-started-download-and-install)

2. Define the index.

   Create a `create_index.py` file in your project directory, and copy and paste the following code into the file.

   ```python
   from pymongo import MongoClient
   from pymongo.operations import SearchIndexModel

   # connect to your Atlas deployment
   uri = "<connection-string>"
   client = MongoClient(uri)

   # set namespace
   database = client["<database>"]
   collection = database["<collection>"]

   # define your MongoDB Search index
   search_index_model = SearchIndexModel(
       definition={
           "mappings": {
               "dynamic": True|False,
               "fields": {
                   "<field_name>":{
                      "type": "autocomplete",
                      "analyzer": "<lucene.analyzer>",
                      "tokenization": "nGram",
                      "minGrams": <2>,
                      "maxGrams": <15>,
                      "foldDiacritics": True|False,
                      "similarity": { "type": "bm25|boolean|stableTfl" }
                   }
               }
           },
       },
       name="default",
   )

   # create the index
   result = collection.create_search_index(model=search_index_model)
   print(f"New index name: {result}")

   ```

   Replace `<connection-string>` with the connection string for your Atlas cluster or local Atlas deployment.

   ### Atlas Cluster

   Your connection string should use the following format:

   ```text
   mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net
   ```

   To learn more, see [Connect to a Cluster via Client Libraries.](https://www.mongodb.com/docs/atlas/driver-connection.md#std-label-connect-via-driver)

3. Create the index.

   ```shell
   python create_index.py
   ```

   **Output:**

   ```text
   New index name: default
   ```

## Configure `autocomplete` Field Properties

The MongoDB Search `autocomplete` type takes the following parameters:

| Option | Type | Necessity | Description | Default |
| --- | --- | --- | --- | --- |
| `type` | string | required | Human-readable label that identifies this field type. Value must be `string`. | |
| `analyzer` | string | optional | Name of the [analyzer](https://www.mongodb.com/docs/search/indexes/analyzers/overview.md#std-label-analyzers-ref) to use with this autocomplete mapping. You can use any MongoDB Search analyzer except the `lucene.kuromoji` [language analyzer](https://www.mongodb.com/docs/search/indexes/analyzers/language.md#std-label-ref-language-analyzers) and the following [custom analyzer](https://www.mongodb.com/docs/search/indexes/analyzers/custom.md#std-label-custom-analyzers) tokenizers and token filters: [nGram](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-nGram-tokenizer-ref) Tokenizer; [edgeGram](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-edgeGram-tokenizer-ref) Tokenizer; [daitchMokotoffSoundex](https://www.mongodb.com/docs/search/indexes/analyzers/token-filters.md#std-label-daitchmokotoffsoundex-tf-ref) Token Filter; [nGram](https://www.mongodb.com/docs/search/indexes/analyzers/token-filters.md#std-label-ngram-tf-ref) Token Filter; [edgeGram](https://www.mongodb.com/docs/search/indexes/analyzers/token-filters.md#std-label-edgegram-tf-ref) Token Filter; [shingle](https://www.mongodb.com/docs/search/indexes/analyzers/token-filters.md#std-label-shingle-tf-ref) Token Filter | `lucene.standard` |
| `maxGrams` | int | optional | Maximum number of characters per indexed sequence. The value limits the character length of indexed tokens. When you search for terms longer than the `maxGrams` value, MongoDB Search truncates the tokens to the `maxGrams` length. For `maxGrams` best practices, see [`maxGrams` Configuration.](https://www.mongodb.com/docs/search/indexes/field-types/autocomplete-type.md#std-label-autocomplete-maxgrams-config) | `15` |
| `minGrams` | int | optional | Minimum number of characters per indexed sequence. We recommend `4` for the minimum value. A value that is less than `4` could impact performance because the size of the index can become very large. We recommend the default value of `2` for `edgeGram` only. | `2` |
| `tokenization` | enum | optional | Tokenization strategy to use when indexing the field for autocompletion. Value can be one of the following: `edgeGram` - create indexable tokens, referred to as `grams`, from variable-length character sequences starting at the left side of the words as delimited by the analyzer used with this autocomplete mapping.; `rightEdgeGram` -  create indexable tokens, referred to as `grams`, from variable-length character sequences starting at the right side of the words as delimited by the analyzer used with this autocomplete mapping.; `nGram` - create indexable tokens, referred to as `grams`, by sliding a variable-length character window over a word. MongoDB Search creates more tokens for `nGram` than `edgeGram` or `rightEdgeGram`. Therefore, `nGram` takes more space and time to index the field. `nGram` is better suited for querying languages with long, compound words or languages that don't use spaces. `edgeGram`, `rightEdgeGram`, and `nGram` are applied at the letter-level. For example, consider the following sentence: `The quick brown fox jumps over the lazy dog.` When tokenized with a `minGrams` value of `2` and a `maxGrams` value of `5`, MongoDB Search indexes the following sequence of characters based on the `tokenization` value you choose. edgeGram `th
the
the{SPACE}
the q
qu
qui
quic
uick
...` rightEdgeGram `og
dog
{SPACE}dog
y dog
zy
azy
lazy
{SPACE}lazy
he
the
{SPACE}the
r the
er
ver
over
{SPACE}over
...` nGram `th
the
the{SPACE}
the q
he
he{SPACE}
he q
he qu
e{SPACE}
e q
e qu
e qui
{SPACE}q
{SPACE}qu
{SPACE}qui
{SPACE}quic
qu
qui
quic
quick
...` For performance considerations, see [Tokenization Performance.](https://www.mongodb.com/docs/search/indexes/field-types/autocomplete-type.md#std-label-autocomplete-tokenization-performance) | `edgeGram` |
| `foldDiacritics` | boolean | optional | Flag that indicates whether to perform [normalizations](https://github.com//apache/lucene/blob/main/lucene/analysis/icu/src/java/org/apache/lucene/analysis/icu/ICUFoldingFilter.java#L26-L55) such as including or removing diacritics from the indexed text. Value can be one of the following: `true` - perform normalizations such as ignoring diacritic marks in the index and query text. For example, a search for `cafè` returns results with the characters `cafè` and `cafe` because MongoDB Search returns results with and without diacritics.; `false` - don't perform normalizations such as ignoring diacritic marks in the index and query text. So, MongoDB Search returns only results that match the strings with or without diacritics in the query. For example, a search for `cafè` returns results only with the characters `cafè`. A search for `cafe` returns results only with the characters `cafe`. | `true` |
| `similarity.type` | string | optional | Name of the similarity algorithm to use with this string mapping when scoring with the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. Value can be one of the following: `bm25`, `boolean`, or `stableTfl`. To learn more about the available similarity algorithms, see [Score Details.](https://www.mongodb.com/docs/search/query/score/get-details.md#std-label-fts-similarity-algorithms) | `bm25` |

## Try an Example for the `autocomplete` Type

The following index definition examples use collections in the [sample data](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets). After you [load the sample data](https://www.mongodb.com/docs/atlas/import/load-sample-data.md#std-label-load-sample-data), you can use these examples to index fields as the `autocomplete` type.

To learn how to set up and run the following example code, see [Define the Index for the token Type](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-define-index-token-admin-api).

### Basic Example

#### Index specific field using static mappings as autocomplete type.

The following index definition example uses the `sample_mflix.movies` collection. The index definition indexes only the `title` field as the `autocomplete` type to support search-as-you-type queries against that field using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. The index definition also specifies the following:

- Use the [standard](https://www.mongodb.com/docs/search/indexes/analyzers/standard.md#std-label-ref-standard-analyzer) analyzer to divide text values into terms based on word boundaries.

- Use the `edgeGram` tokenization strategy to index characters starting at the left side of the words .

- Index a minimum of `3` characters per indexed sequence.

- Index a maximum of `5` characters per indexed sequence.

- Include diacritic marks in the index and query text.

- Use the `stableTfl` [similarity algorithm](https://www.mongodb.com/docs/search/query/score/get-details.md#std-label-fts-similarity-algorithms) to ensure consistent document scoring across all search nodes and replica set members.

```json
curl --header "Authorization: Bearer ${ACCESS_TOKEN}" \
    --header "Accept: application/vnd.atlas.2025-03-12+json" \
    --header "Content-Type: application/json" \
    -X POST "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes" \
    -d '{ "collectionName": "movies",
        "database": "sample_mflix",
        "name": "default",
        "type": "search",
        "definition": {
          "mappings": { 
            "dynamic": false, 
            "fields": { 
              "title": { 
                "type": "autocomplete",
                "analyzer": "lucene.standard",
                "tokenization": "edgeGram",
                "minGrams": 3,
                "maxGrams": 5,
                "foldDiacritics": false,
                "similarity": { "type": "stableTfl" }
              } 
            }
          }
        }
    }
```

### Dynamic Index Example

#### Dynamically index string fields as the autocomplete type.

The following index definition for the `sample_mflix.movies` collection in the [sample dataset](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets) indexes all string fields at the root-level in the documents in the collection as the `autocomplete` type with default settings. It also excludes string fields like `poster`, `languages`, `rated`, `lastupdated`, `fullplot`, and `awards` from being indexed.

**Note:**

To configure `typeSet` using the Atlas Administration API for dynamic mappings, you must use API (Application Programming Interface) version 2025-09-10 or higher.

```json
{
  "mappings": {
    "dynamic": {
      "typeSet": "moviesStringIndex"
    },
    "fields": {
      "poster": [],
      "languages": [],
      "rated": [],
      "lastupdated": [],
      "fullplot": [],
      "awards": []
    }
  },
  "typeSets": [
    {
      "name": "moviesStringIndex",
      "types": [
        {
          "type": "autocomplete"
        }
      ]
    }
  ]
}
```

### Multiple Types Example

#### Index specific field as autocomplete and string types.

The following index definition example uses the `sample_mflix.movies` collection to index a field as multiple types. The following index definition indexes the `title` field as the following types:

- `autocomplete` type to support autocompletion for queries using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator.

- `string` type to support text search using operators such [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref), [phrase](https://www.mongodb.com/docs/search/query/operators-collectors/phrase.md#std-label-phrase-ref), and so on.

```json
curl --header "Authorization: Bearer ${ACCESS_TOKEN}" \
    --header "Accept: application/vnd.atlas.2025-03-12+json" \
    --header "Content-Type: application/json" \
    -X POST "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes" \
    -d '{ "collectionName": "movies",
        "database": "sample_mflix",
        "name": "default",
        "type": "search",
        "definition": {
          "mappings": { 
            "dynamic": false, 
            "fields": { 
              "title": [
                {
                  "type": "autocomplete",
                  "analyzer": "lucene.standard",
                  "tokenization": "edgeGram",
                  "minGrams": 2,
                  "maxGrams": 15,
                  "foldDiacritics": false
                },
                {
                  "type": "string"
                }
              ]
            }
          }
        }
    }'
```

### Email Example

#### Index email address as the autocomplete type.

The following index definition example uses the [sample\_mflix.users](https://www.mongodb.com/docs/manual/sample-data/sample-mflix.md#std-label-sample-mflix) collection. The index definition example indexes only the `email` field as the `autocomplete` type to support search-as-you-type queries against that field using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. The index definition specifies the following:

- Use the [keyword](https://www.mongodb.com/docs/search/indexes/analyzers/keyword.md#std-label-ref-keyword-analyzer) analyzer to accept a string or array of strings as a parameter and index them as a single term (token).

- Use the [nGram](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-nGram-tokenizer-ref) tokenizer to tokenize text into chunks, or "n-grams", of given sizes.

- Index a minimum of `3` characters per indexed sequence.

- Index a maximum of `15` characters per indexed sequence.

- Include diacritic marks in the index and query text.

You can also use the `uaxUrlEmail` tokenizer to tokenizes URL (Uniform Resource Locator)s and email addresses. To learn more, see [uaxUrlEmail.](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-uaxUrlEmail-tokenizer-ref)

```json
curl --header "Authorization: Bearer ${ACCESS_TOKEN}" \
    --header "Accept: application/vnd.atlas.2025-03-12+json" \
    --header "Content-Type: application/json" \
    -X POST "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes" \
    -d '{ "collectionName": "users",
        "database": "sample_mflix",
        "name": "default",
        "type": "search",
        "definition": {
          {
            "mappings": {
              "dynamic": true,
              "fields": {
                "email": {
                  "type": "autocomplete",
                  "analyzer": "lucene.keyword",
                  "tokenization": "nGram",
                  "minGrams": 3,
                  "maxGrams": 15,
                  "foldDiacritics": false
                }
              }
            }
          }
        }
    }'
```

### Try an Example for the `autocomplete` Type

The following index definition examples use collections in the [sample data](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets). After you [load the sample data](https://www.mongodb.com/docs/atlas/import/load-sample-data.md#std-label-load-sample-data), you can use these examples to index fields as the `autocomplete` type.

To learn how to set up and run the following example code, see [Define the Index for the token Type](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-define-index-token-admin-api).

#### Basic Example

##### Index specific field using static mappings as autocomplete type.

The following index definition example uses the `sample_mflix.movies` collection. The index definition indexes only the `title` field as the `autocomplete` type to support search-as-you-type queries against that field using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. The index definition also specifies the following:

- Use the [standard](https://www.mongodb.com/docs/search/indexes/analyzers/standard.md#std-label-ref-standard-analyzer) analyzer to divide text values into terms based on word boundaries.

- Use the `edgeGram` tokenization strategy to index characters starting at the left side of the words .

- Index a minimum of `3` characters per indexed sequence.

- Index a maximum of `5` characters per indexed sequence.

- Include diacritic marks in the index and query text.

- Use the `stableTfl` [similarity algorithm](https://www.mongodb.com/docs/search/query/score/get-details.md#std-label-fts-similarity-algorithms) to ensure consistent document scoring across all search nodes and replica set members.

```bash
{
  "mappings": {
    "dynamic": false,
    "fields": {
      "title": {
        "type": "autocomplete",
        "analyzer": "lucene.standard",
        "tokenization": "edgeGram",
        "minGrams": 3,
        "maxGrams": 5,
        "foldDiacritics": false,
        "similarity": { "type": "stableTfl" }
    }
  }
}
```

#### Dynamic Index Example

##### Dynamically index string fields as the autocomplete type.

The following index definition for the `sample_mflix.movies` collection in the [sample dataset](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets) indexes all string fields at the root-level in the documents in the collection as the `autocomplete` type with default settings. It also excludes string fields like `poster`, `languages`, `rated`, `lastupdated`, `fullplot`, and `awards` from being indexed.

```bash
{
  "mappings": {
    "dynamic": {
      "typeSet": "moviesStringIndex"
    },
    "fields": {
      "poster": [],
      "languages": [],
      "rated": [],
      "lastupdated": [],
      "fullplot": [],
      "awards": []
    }
  },
  "typeSets": [
    {
      "name": "moviesStringIndex",
      "types": [
        {
          "type": "autocomplete"
        }
      ]
    }
  ]
}
```

#### Multiple Types Example

##### Index specific field as autocomplete and string types.

The following index definition example uses the `sample_mflix.movies` collection to index a field as multiple types. The following index definition indexes the `title` field as the following types:

- `autocomplete` type to support autocompletion for queries using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator.

- `string` type to support text search using operators such [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref), [phrase](https://www.mongodb.com/docs/search/query/operators-collectors/phrase.md#std-label-phrase-ref), and so on.

```bash
{
  "mappings": {
    "dynamic": true|false,
    "fields": {
      "title": [
        {
          "type": "autocomplete",
          "analyzer": "lucene.standard",
          "tokenization": "edgeGram",
          "minGrams": 2,
          "maxGrams": 15,
          "foldDiacritics": false
        },
        {
          "type": "string"
        }
      ]
    }
  }
}
```

#### Email Example

##### Index email address as the autocomplete type.

The following index definition example uses the [sample\_mflix.users](https://www.mongodb.com/docs/manual/sample-data/sample-mflix.md#std-label-sample-mflix) collection. The index definition example indexes only the `email` field as the `autocomplete` type to support search-as-you-type queries against that field using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. The index definition specifies the following:

- Use the [keyword](https://www.mongodb.com/docs/search/indexes/analyzers/keyword.md#std-label-ref-keyword-analyzer) analyzer to accept a string or array of strings as a parameter and index them as a single term (token).

- Use the [nGram](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-nGram-tokenizer-ref) tokenizer to tokenize text into chunks, or "n-grams", of given sizes.

- Index a minimum of `3` characters per indexed sequence.

- Index a maximum of `15` characters per indexed sequence.

- Include diacritic marks in the index and query text.

You can also use the `uaxUrlEmail` tokenizer to tokenizes URL (Uniform Resource Locator)s and email addresses. To learn more, see [uaxUrlEmail.](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-uaxUrlEmail-tokenizer-ref)

```bash
{
  "mappings": {
    "dynamic": true,
    "fields": {
      "email": {
        "type": "autocomplete",
        "analyzer": "lucene.keyword",
        "tokenization": "nGram",
        "minGrams": 3,
        "maxGrams": 15,
        "foldDiacritics": false
      }
    }
  }
}
```

### Try an Example for the `autocomplete` Type

The following index definition examples use collections in the [sample data](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets). After you [load the sample data](https://www.mongodb.com/docs/atlas/import/load-sample-data.md#std-label-load-sample-data), you can use these examples to index fields as the `autocomplete` type.

To learn how to set up and run the following example code, see [Define the Index for the token Type](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-define-index-token-admin-api).

#### Basic Example

##### Index specific field using static mappings as autocomplete type.

The following index definition example uses the `sample_mflix.movies` collection. The index definition indexes only the `title` field as the `autocomplete` type to support search-as-you-type queries against that field using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. The index definition also specifies the following:

- Use the [standard](https://www.mongodb.com/docs/search/indexes/analyzers/standard.md#std-label-ref-standard-analyzer) analyzer to divide text values into terms based on word boundaries.

- Use the `edgeGram` tokenization strategy to index characters starting at the left side of the words .

- Index a minimum of `3` characters per indexed sequence.

- Index a maximum of `5` characters per indexed sequence.

- Include diacritic marks in the index and query text.

- Use the `stableTfl` [similarity algorithm](https://www.mongodb.com/docs/search/query/score/get-details.md#std-label-fts-similarity-algorithms) to ensure consistent document scoring across all search nodes and replica set members.

```none
{
  "mappings": {
    "dynamic": false,
    "fields": {
      "title": {
        "type": "autocomplete",
        "analyzer": "lucene.standard",
        "tokenization": "edgeGram",
        "minGrams": 3,
        "maxGrams": 5,
        "foldDiacritics": false,
        "similarity": { "type": "stableTfl" }
    }
  }
}
```

#### Dynamic Index Example

##### Dynamically index string fields as the autocomplete type.

The following index definition for the `sample_mflix.movies` collection in the [sample dataset](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets) indexes all string fields at the root-level in the documents in the collection as the `autocomplete` type with default settings. It also excludes string fields like `poster`, `languages`, `rated`, `lastupdated`, `fullplot`, and `awards` from being indexed.

```none
{
  "mappings": {
    "dynamic": {
      "typeSet": "moviesStringIndex"
    },
    "fields": {
      "poster": [],
      "languages": [],
      "rated": [],
      "lastupdated": [],
      "fullplot": [],
      "awards": []
    }
  },
  "typeSets": [
    {
      "name": "moviesStringIndex",
      "types": [
        {
          "type": "autocomplete"
        }
      ]
    }
  ]
}
```

#### Multiple Types Example

##### Index specific field as autocomplete and string types.

The following index definition example uses the `sample_mflix.movies` collection to index a field as multiple types. The following index definition indexes the `title` field as the following types:

- `autocomplete` type to support autocompletion for queries using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator.

- `string` type to support text search using operators such [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref), [phrase](https://www.mongodb.com/docs/search/query/operators-collectors/phrase.md#std-label-phrase-ref), and so on.

```none
{
  "mappings": {
    "dynamic": true|false,
    "fields": {
      "title": [
        {
          "type": "autocomplete",
          "analyzer": "lucene.standard",
          "tokenization": "edgeGram",
          "minGrams": 2,
          "maxGrams": 15,
          "foldDiacritics": false
        },
        {
          "type": "string"
        }
      ]
    }
  }
}
```

#### Email Example

##### Index email address as the autocomplete type.

The following index definition example uses the [sample\_mflix.users](https://www.mongodb.com/docs/manual/sample-data/sample-mflix.md#std-label-sample-mflix) collection. The index definition example indexes only the `email` field as the `autocomplete` type to support search-as-you-type queries against that field using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. The index definition specifies the following:

- Use the [keyword](https://www.mongodb.com/docs/search/indexes/analyzers/keyword.md#std-label-ref-keyword-analyzer) analyzer to accept a string or array of strings as a parameter and index them as a single term (token).

- Use the [nGram](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-nGram-tokenizer-ref) tokenizer to tokenize text into chunks, or "n-grams", of given sizes.

- Index a minimum of `3` characters per indexed sequence.

- Index a maximum of `15` characters per indexed sequence.

- Include diacritic marks in the index and query text.

You can also use the `uaxUrlEmail` tokenizer to tokenizes URL (Uniform Resource Locator)s and email addresses. To learn more, see [uaxUrlEmail.](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-uaxUrlEmail-tokenizer-ref)

```none
{
  "mappings": {
    "dynamic": true,
    "fields": {
      "email": {
        "type": "autocomplete",
        "analyzer": "lucene.keyword",
        "tokenization": "nGram",
        "minGrams": 3,
        "maxGrams": 15,
        "foldDiacritics": false
      }
    }
  }
}
```

### Try an Example for the `autocomplete` Type

The following index definition examples use collections in the [sample data](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets). After you [load the sample data](https://www.mongodb.com/docs/atlas/import/load-sample-data.md#std-label-load-sample-data), you can use these examples to index fields as the `autocomplete` type.

To learn how to set up and run the following example code, see [Define the Index for the token Type](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-define-index-token-admin-api).

#### Basic Example

##### Index specific field using static mappings as autocomplete type.

The following index definition example uses the `sample_mflix.movies` collection. The index definition indexes only the `title` field as the `autocomplete` type to support search-as-you-type queries against that field using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. The index definition also specifies the following:

- Use the [standard](https://www.mongodb.com/docs/search/indexes/analyzers/standard.md#std-label-ref-standard-analyzer) analyzer to divide text values into terms based on word boundaries.

- Use the `edgeGram` tokenization strategy to index characters starting at the left side of the words .

- Index a minimum of `3` characters per indexed sequence.

- Index a maximum of `5` characters per indexed sequence.

- Include diacritic marks in the index and query text.

- Use the `stableTfl` [similarity algorithm](https://www.mongodb.com/docs/search/query/score/get-details.md#std-label-fts-similarity-algorithms) to ensure consistent document scoring across all search nodes and replica set members.

```javascript
db.movies.createSearchIndex(
  "default", 
  {
    "mappings": {
      "dynamic": false,
      "fields": {
        "title": {
          "type": "autocomplete",
          "analyzer": "lucene.standard",
          "tokenization": "edgeGram",
          "minGrams": 3,
          "maxGrams": 5,
          "foldDiacritics": false,
          "similarity": { "type": "stableTfl" }
        }
      }
    }
  }
)
```

#### Dynamic Index Example

##### Dynamically index string fields as the autocomplete type.

The following index definition for the `sample_mflix.movies` collection in the [sample dataset](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets) indexes all string fields at the root-level in the documents in the collection as the `autocomplete` type with default settings. It also excludes string fields like `poster`, `languages`, `rated`, `lastupdated`, `fullplot`, and `awards` from being indexed.

```javascript
db.users.createSearchIndex(
  "default", 
  {
    "mappings": {
      "dynamic": {
        "typeSet": "moviesStringIndex"
      },
      "fields": {
        "poster": [],
        "languages": [],
        "rated": [],
        "lastupdated": [],
        "fullplot": [],
        "awards": []
      }
    },
    "typeSets": [
      {
        "name": "moviesStringIndex",
        "types": [
          {
            "type": "autocomplete"
          }
        ]
      }
    ]
  }
)
```

#### Multiple Types Example

##### Index specific field as autocomplete and string types.

The following index definition example uses the `sample_mflix.movies` collection to index a field as multiple types. The following index definition indexes the `title` field as the following types:

- `autocomplete` type to support autocompletion for queries using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator.

- `string` type to support text search using operators such [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref), [phrase](https://www.mongodb.com/docs/search/query/operators-collectors/phrase.md#std-label-phrase-ref), and so on.

```javascript
db.movies.createSearchIndex(
  "default", 
  {
    "mappings": {
      "dynamic": false,
      "fields": {
        "title": [
          {
            "type": "autocomplete",
            "analyzer": "lucene.standard",
            "tokenization": "edgeGram",
            "minGrams": 2,
            "maxGrams": 15,
            "foldDiacritics": false
          },
          {
            "type": "string"
          }
        ]
      }
    }
  }
)
```

#### Email Example

##### Index email address as the autocomplete type.

The following index definition example uses the [sample\_mflix.users](https://www.mongodb.com/docs/manual/sample-data/sample-mflix.md#std-label-sample-mflix) collection. The index definition example indexes only the `email` field as the `autocomplete` type to support search-as-you-type queries against that field using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. The index definition specifies the following:

- Use the [keyword](https://www.mongodb.com/docs/search/indexes/analyzers/keyword.md#std-label-ref-keyword-analyzer) analyzer to accept a string or array of strings as a parameter and index them as a single term (token).

- Use the [nGram](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-nGram-tokenizer-ref) tokenizer to tokenize text into chunks, or "n-grams", of given sizes.

- Index a minimum of `3` characters per indexed sequence.

- Index a maximum of `15` characters per indexed sequence.

- Include diacritic marks in the index and query text.

You can also use the `uaxUrlEmail` tokenizer to tokenizes URL (Uniform Resource Locator)s and email addresses. To learn more, see [uaxUrlEmail.](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-uaxUrlEmail-tokenizer-ref)

```javascript
db.users.createSearchIndex(
  "default", 
  {
    "mappings": {
      "dynamic": true,
      "fields": {
        "email": {
          "type": "autocomplete",
          "analyzer": "lucene.keyword",
          "tokenization": "nGram",
          "minGrams": 3,
          "maxGrams": 15,
          "foldDiacritics": false
        }
      }
    }
  }
)
```

### Try an Example for the `autocomplete` Type

The following index definition examples use collections in the [sample data](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets). After you [load the sample data](https://www.mongodb.com/docs/atlas/import/load-sample-data.md#std-label-load-sample-data), you can use the Visual Editor or JSON (Javascript Object Notation) Editor to configure these indexes. After you select your preferred configuration method, select the database and collection, and refine your index to add field mappings.

#### Basic Example

##### Index specific field using static mappings as autocomplete type.

The following index definition example uses the `sample_mflix.movies` collection. The index definition indexes only the `title` field as the `autocomplete` type to support search-as-you-type queries against that field using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. The index definition also specifies the following:

- Use the [standard](https://www.mongodb.com/docs/search/indexes/analyzers/standard.md#std-label-ref-standard-analyzer) analyzer to divide text values into terms based on word boundaries.

- Use the `edgeGram` tokenization strategy to index characters starting at the left side of the words .

- Index a minimum of `3` characters per indexed sequence.

- Index a maximum of `5` characters per indexed sequence.

- Include diacritic marks in the index and query text.

- Use the `stableTfl` [similarity algorithm](https://www.mongodb.com/docs/search/query/score/get-details.md#std-label-fts-similarity-algorithms) to ensure consistent document scoring across all search nodes and replica set members.

### Visual Editor

1. In the Add Field Mapping window, select title from the Field
   Name dropdown.

2. Click the Data Type dropdown and select Autocomplete.

3. Modify the Autocomplete Properties to set the following:

   - Analyzer to `lucene.standard`.

   - Tokenization to `edgeGram`.

   - Min Grams to `2`.

   - Max Grams to `15`.

   - Fold Diacritics to `true`.

   - Similarity.type to `stableTfl`.

4. Click Add.

#### Dynamic Index Example

##### Dynamically index string fields as the autocomplete type.

The following index definition for the `sample_mflix.movies` collection in the [sample dataset](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets) indexes all string fields at the root-level in the documents in the collection as the `autocomplete` type with default settings. It also excludes string fields like `poster`, `languages`, `rated`, `lastupdated`, `fullplot`, and `awards` from being indexed.

### Visual Editor

You can't configure `typeSets` using the Atlas UI Visual Editor.

**Note:**

Indexing all string fields as the autocomplete type can take some time and resources. Also, this might cause your index size to grow.

#### Multiple Types Example

##### Index specific field as autocomplete and string types.

The following index definition example uses the `sample_mflix.movies` collection to index a field as multiple types. The following index definition indexes the `title` field as the following types:

- `autocomplete` type to support autocompletion for queries using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator.

- `string` type to support text search using operators such [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref), [phrase](https://www.mongodb.com/docs/search/query/operators-collectors/phrase.md#std-label-phrase-ref), and so on.

### Visual Editor

In the Add Field Mapping window, select title from the Field
Name dropdown.

Click the Data Type dropdown and select Autocomplete.

Modify the Autocomplete Properties to set the following:

- Analyzer to `lucene.standard`.

- Tokenization to `edgeGram`.

- Min Grams to `2`.

- Max Grams to `15`.

- Fold Diacritics to `false`.

Click Add.

Add another field mapping for the same field with Data Type set to String.

Click Add.

#### Email Example

##### Index email address as the autocomplete type.

The following index definition example uses the [sample\_mflix.users](https://www.mongodb.com/docs/manual/sample-data/sample-mflix.md#std-label-sample-mflix) collection. The index definition example indexes only the `email` field as the `autocomplete` type to support search-as-you-type queries against that field using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. The index definition specifies the following:

- Use the [keyword](https://www.mongodb.com/docs/search/indexes/analyzers/keyword.md#std-label-ref-keyword-analyzer) analyzer to accept a string or array of strings as a parameter and index them as a single term (token).

- Use the [nGram](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-nGram-tokenizer-ref) tokenizer to tokenize text into chunks, or "n-grams", of given sizes.

- Index a minimum of `3` characters per indexed sequence.

- Index a maximum of `15` characters per indexed sequence.

- Include diacritic marks in the index and query text.

You can also use the `uaxUrlEmail` tokenizer to tokenizes URL (Uniform Resource Locator)s and email addresses. To learn more, see [uaxUrlEmail.](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-uaxUrlEmail-tokenizer-ref)

### Visual Editor

In the Add Field Mapping window, select email from the Field
Name dropdown.

Click the Data Type dropdown and select Autocomplete.

Modify the Autocomplete Properties to set the following:

- Analyzer to `lucene.keyword`.

- Tokenization to `nGram`.

- Min Grams to `3`.

- Max Grams to `15`.

- Fold Diacritics to `false`.

Click Add.

### Try an Example for the `autocomplete` Type

The following index definition examples use collections in the [sample data](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets). After you [load the sample data](https://www.mongodb.com/docs/atlas/import/load-sample-data.md#std-label-load-sample-data), you can use these examples to index fields as the `autocomplete` type.

To learn how to set up and run the following example code, see [Define the Index for the token Type](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-define-index-token-admin-api).

#### Basic Example

##### Index specific field using static mappings as autocomplete type.

The following index definition example uses the `sample_mflix.movies` collection. The index definition indexes only the `title` field as the `autocomplete` type to support search-as-you-type queries against that field using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. The index definition also specifies the following:

- Use the [standard](https://www.mongodb.com/docs/search/indexes/analyzers/standard.md#std-label-ref-standard-analyzer) analyzer to divide text values into terms based on word boundaries.

- Use the `edgeGram` tokenization strategy to index characters starting at the left side of the words .

- Index a minimum of `3` characters per indexed sequence.

- Index a maximum of `5` characters per indexed sequence.

- Include diacritic marks in the index and query text.

- Use the `stableTfl` [similarity algorithm](https://www.mongodb.com/docs/search/query/score/get-details.md#std-label-fts-similarity-algorithms) to ensure consistent document scoring across all search nodes and replica set members.

```c
#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, "sample_mflix");
    collection = mongoc_database_get_collection(database, "movies");

    // Specify the command and the new index
    const char *cmd_str = BSON_STR({
        "createSearchIndexes" : "movies",
        "indexes" : [ {
            "name" : "default",
            "definition" : {
              "mappings": {
                "dynamic": false,
                 "fields": {
                  "title": {
                    "type": "autocomplete",
                    "analyzer": "lucene.standard",
                    "tokenization": "edgeGram",
                    "minGrams": 3,
                    "maxGrams": 5,
                    "foldDiacritics": false,
                    "similarity": { "type": "stableTfl" }
                  }
                }
              }
            }
	    } ]
	});

    // 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 MongoDB 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;
}
```

#### Dynamic Index Example

##### Dynamically index string fields as the autocomplete type.

The following index definition for the `sample_mflix.movies` collection in the [sample dataset](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets) indexes all string fields at the root-level in the documents in the collection as the `autocomplete` type with default settings. It also excludes string fields like `poster`, `languages`, `rated`, `lastupdated`, `fullplot`, and `awards` from being indexed.

```c
#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, "sample_mflix");
    collection = mongoc_database_get_collection(database, "movies");

    // Specify the command and the new index
    const char *cmd_str = BSON_STR({
        "createSearchIndexes" : "movies",
        "indexes" : [ {
            "name" : "default",
            "definition" : {
              "mappings": {
                "dynamic": {
                  "typeSet": "moviesStringIndex"
                },
                "fields": {
                  "poster": [],
                  "languages": [],
                  "rated": [],
                  "lastupdated": [],
                  "fullplot": [],
                  "awards": []
                }
              },
              "typeSets": [
                {
                  "name": "moviesStringIndex",
                  "types": [
                    {
                      "type": "autocomplete"
                    }
                  ]
                }
              ]
            }
	    } ]
	});

    // 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;
}
```

#### Multiple Types Example

##### Index specific field as autocomplete and string types.

The following index definition example uses the `sample_mflix.movies` collection to index a field as multiple types. The following index definition indexes the `title` field as the following types:

- `autocomplete` type to support autocompletion for queries using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator.

- `string` type to support text search using operators such [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref), [phrase](https://www.mongodb.com/docs/search/query/operators-collectors/phrase.md#std-label-phrase-ref), and so on.

```c
#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, "sample_mflix");
    collection = mongoc_database_get_collection(database, "users");

    // Specify the command and the new index
    const char *cmd_str = BSON_STR({
        "createSearchIndexes" : "users",
        "indexes" : [ {
            "name" : "default",
            "definition" : {
              "mappings": {
                "dynamic": false,
                "fields": {
                  "title": [
                    {
                      "type": "autocomplete",
                      "analyzer": "lucene.standard",
                      "tokenization": "edgeGram",
                      "minGrams": 2,
                      "maxGrams": 15,
                      "foldDiacritics": false
                    },
                    {
                      "type": "string"
                    }
                  ]
                }
              }
            }
	    } ]
	});

    // 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 MongoDB 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;
}
```

#### Email Example

##### Index email address as the autocomplete type.

The following index definition example uses the [sample\_mflix.users](https://www.mongodb.com/docs/manual/sample-data/sample-mflix.md#std-label-sample-mflix) collection. The index definition example indexes only the `email` field as the `autocomplete` type to support search-as-you-type queries against that field using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. The index definition specifies the following:

- Use the [keyword](https://www.mongodb.com/docs/search/indexes/analyzers/keyword.md#std-label-ref-keyword-analyzer) analyzer to accept a string or array of strings as a parameter and index them as a single term (token).

- Use the [nGram](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-nGram-tokenizer-ref) tokenizer to tokenize text into chunks, or "n-grams", of given sizes.

- Index a minimum of `3` characters per indexed sequence.

- Index a maximum of `15` characters per indexed sequence.

- Include diacritic marks in the index and query text.

You can also use the `uaxUrlEmail` tokenizer to tokenizes URL (Uniform Resource Locator)s and email addresses. To learn more, see [uaxUrlEmail.](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-uaxUrlEmail-tokenizer-ref)

```c
#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, "sample_mflix");
    collection = mongoc_database_get_collection(database, "users");

    // Specify the command and the new index
    const char *cmd_str = BSON_STR({
        "createSearchIndexes" : "users",
        "indexes" : [ {
            "name" : "default",
            "definition" : {
              "mappings": {
                "dynamic": true,
                 "fields": {
                  "email": {
                    "type": "autocomplete",
                    "analyzer": "lucene.keyword",
                    "tokenization": "nGram",
                    "minGrams": 3,
                    "maxGrams": 15,
                    "foldDiacritics": false
                  }
                }
              }
            }
	    } ]
	});

    // 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 MongoDB 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;
}
```

### Try an Example for the `autocomplete` Type

The following index definition examples use collections in the [sample data](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets). After you [load the sample data](https://www.mongodb.com/docs/atlas/import/load-sample-data.md#std-label-load-sample-data), you can use these examples to index fields as the `autocomplete` type.

To learn how to set up and run the following example code, see [Define the Index for the token Type](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-define-index-token-admin-api).

#### Basic Example

##### Index specific field using static mappings as autocomplete type.

The following index definition example uses the `sample_mflix.movies` collection. The index definition indexes only the `title` field as the `autocomplete` type to support search-as-you-type queries against that field using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. The index definition also specifies the following:

- Use the [standard](https://www.mongodb.com/docs/search/indexes/analyzers/standard.md#std-label-ref-standard-analyzer) analyzer to divide text values into terms based on word boundaries.

- Use the `edgeGram` tokenization strategy to index characters starting at the left side of the words .

- Index a minimum of `3` characters per indexed sequence.

- Index a maximum of `5` characters per indexed sequence.

- Include diacritic marks in the index and query text.

- Use the `stableTfl` [similarity algorithm](https://www.mongodb.com/docs/search/query/score/get-details.md#std-label-fts-similarity-algorithms) to ensure consistent document scoring across all search nodes and replica set members.

```csharp
using MongoDB.Bson;
using MongoDB.Driver;

// connect to your Atlas deployment
var uri = "<connection-string>";

var client = new MongoClient(uri);

var db = client.GetDatabase("sample_mflix");
var collection = db.GetCollection<BsonDocument>("movies");

// define your MongoDB Search index
var index =  new CreateSearchIndexModel(
  "default", new BsonDocument
  {
    { "mappings", new BsonDocument
      {
        { "dynamic", false },
        { "fields", new BsonDocument
          {
            { "title", new BsonDocument
              {
                { "type", "autocomplete" },
                { "analyzer", "lucene.standard" },
                { "tokenization", "edgeGram" },
                { "minGrams", 3 },
                { "maxGrams", 5 },
                { "foldDiacritics", false },
                { "similarity", new BsonDocument { { "type", "stableTfl" } } }
              }
            }
          }
        }
      }
    }
  });

var result = collection.SearchIndexes.CreateOne(index);
Console.WriteLine($"New index name: {result}");
```

#### Multiple Types Example

##### Index specific field as autocomplete and string types.

The following index definition example uses the `sample_mflix.movies` collection to index a field as multiple types. The following index definition indexes the `title` field as the following types:

- `autocomplete` type to support autocompletion for queries using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator.

- `string` type to support text search using operators such [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref), [phrase](https://www.mongodb.com/docs/search/query/operators-collectors/phrase.md#std-label-phrase-ref), and so on.

```csharp
using MongoDB.Bson;  
using MongoDB.Driver;  
  
// connect to your Atlas deployment  
var uri = "<connection-string>";  
  
var client = new MongoClient(uri);  
  
var db = client.GetDatabase("sample_mflix");  
var collection = db.GetCollection<BsonDocument>("movies");  
  
// define your MongoDB Search index  
var index = new CreateSearchIndexModel(  
  "default", new BsonDocument  
  {  
    { "mappings", new BsonDocument  
      {  
        { "dynamic", false },  
        { "fields", new BsonDocument  
          {  
            { "title", new BsonArray  
              {  
                new BsonDocument  
                {  
                  { "type", "autocomplete" },  
                  { "analyzer", "lucene.standard" },  
                  { "tokenization", "edgeGram" },  
                  { "minGrams", 2 },  
                  { "maxGrams", 15 },  
                  { "foldDiacritics", false }  
                },  
                new BsonDocument  
                {  
                  { "type", "string" }  
                }  
              }  
            }  
          }  
        }  
      }  
    }  
  });  
  
var result = collection.SearchIndexes.CreateOne(index);  
Console.WriteLine($"New index name: {result}");  

```

#### Email Example

##### Index email address as the autocomplete type.

The following index definition example uses the [sample\_mflix.users](https://www.mongodb.com/docs/manual/sample-data/sample-mflix.md#std-label-sample-mflix) collection. The index definition example indexes only the `email` field as the `autocomplete` type to support search-as-you-type queries against that field using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. The index definition specifies the following:

- Use the [keyword](https://www.mongodb.com/docs/search/indexes/analyzers/keyword.md#std-label-ref-keyword-analyzer) analyzer to accept a string or array of strings as a parameter and index them as a single term (token).

- Use the [nGram](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-nGram-tokenizer-ref) tokenizer to tokenize text into chunks, or "n-grams", of given sizes.

- Index a minimum of `3` characters per indexed sequence.

- Index a maximum of `15` characters per indexed sequence.

- Include diacritic marks in the index and query text.

You can also use the `uaxUrlEmail` tokenizer to tokenizes URL (Uniform Resource Locator)s and email addresses. To learn more, see [uaxUrlEmail.](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-uaxUrlEmail-tokenizer-ref)

```csharp
using MongoDB.Bson;
using MongoDB.Driver;

// connect to your Atlas deployment
var uri = "<connection-string>";

var client = new MongoClient(uri);

var db = client.GetDatabase("sample_mflix");
var collection = db.GetCollection<BsonDocument>("users");

// define your MongoDB Search index
var index =  new CreateSearchIndexModel(
  "default", new BsonDocument
  {
    { "mappings", new BsonDocument
      {
        { "dynamic", true },
        { "fields", new BsonDocument
          {
            { "email", new BsonDocument
              {
                { "type", "autocomplete" },
                { "analyzer", "lucene.keyword" },
                { "tokenization", "nGram" },
                { "minGrams", 3 },
                { "maxGrams", 15 },
                { "foldDiacritics", false }
              }
            }
          }
        }
      }
    }
  });

var result = collection.SearchIndexes.CreateOne(index);
Console.WriteLine($"New index name: {result}");
```

### Try an Example for the `autocomplete` Type

The following index definition examples use collections in the [sample data](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets). After you [load the sample data](https://www.mongodb.com/docs/atlas/import/load-sample-data.md#std-label-load-sample-data), you can use these examples to index fields as the `autocomplete` type.

To learn how to set up and run the following example code, see [Define the Index for the token Type](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-define-index-token-admin-api).

#### Basic Example

##### Index specific field using static mappings as autocomplete type.

The following index definition example uses the `sample_mflix.movies` collection. The index definition indexes only the `title` field as the `autocomplete` type to support search-as-you-type queries against that field using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. The index definition also specifies the following:

- Use the [standard](https://www.mongodb.com/docs/search/indexes/analyzers/standard.md#std-label-ref-standard-analyzer) analyzer to divide text values into terms based on word boundaries.

- Use the `edgeGram` tokenization strategy to index characters starting at the left side of the words .

- Index a minimum of `3` characters per indexed sequence.

- Index a maximum of `5` characters per indexed sequence.

- Include diacritic marks in the index and query text.

- Use the `stableTfl` [similarity algorithm](https://www.mongodb.com/docs/search/query/score/get-details.md#std-label-fts-similarity-algorithms) to ensure consistent document scoring across all search nodes and replica set members.

```cpp
#include <iostream>

#include <bsoncxx/builder/basic/document.hpp>
#include <bsoncxx/json.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/uri.hpp>

using bsoncxx::builder::basic::kvp;
using bsoncxx::builder::basic::make_document;

int main(){

    mongocxx::instance instance;
    mongocxx::uri uri("<connection-string>");
    mongocxx::client client(uri);

    auto db = client["sample_mflix"];
    auto collection = db["movies"];

    // instantiate a ``mongocxx::search_index_view`` on your collection
    auto siv = collection.search_indexes();

    {
        auto name = "default";
        auto definition = make_document(
            kvp("mappings", make_document(
                kvp("dynamic", false),
                kvp("fields", make_document(
                    kvp("title", make_document(
                        kvp("type", "autocomplete"),
                        kvp("analyzer", "lucene.standard"),
                        kvp("tokenization", "edgeGram"),
                        kvp("minGrams", 3),
                        kvp("maxGrams", 5),
                        kvp("foldDiacritics", false),
                        kvp("similarity", make_document(kvp("type", "stableTfl")))
                    ))
                ))
            ))
        );

        auto model = mongocxx::search_index_model(name, definition.view());

        // Create the search index
        auto result = siv.create_one(model);
        std::cout << "New index name: " << result << std::endl;
    }
}

```

#### Dynamic Index Example

##### Dynamically index string fields as the autocomplete type.

The following index definition for the `sample_mflix.movies` collection in the [sample dataset](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets) indexes all string fields at the root-level in the documents in the collection as the `autocomplete` type with default settings. It also excludes string fields like `poster`, `languages`, `rated`, `lastupdated`, `fullplot`, and `awards` from being indexed.

```cpp
#include <iostream>

#include <bsoncxx/builder/basic/document.hpp>
#include <bsoncxx/json.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/uri.hpp>

using bsoncxx::builder::basic::kvp;
using bsoncxx::builder::basic::make_document;

int main(){

    mongocxx::instance instance;
    mongocxx::uri uri("<connection-string>");
    mongocxx::client client(uri);

    auto db = client["sample_mflix"];
    auto collection = db["movies"];

    // instantiate a ``mongocxx::search_index_view`` on your collection
    auto siv = collection.search_indexes();

    {
        auto name = "default";
        auto definition = make_document(
            kvp("mappings", make_document(
                kvp("dynamic", make_document(
                    kvp("typeSet", "moviesStringIndex")
                )),
                kvp("fields", make_document(
                    kvp("poster", bsoncxx::builder::basic::array{}),
                    kvp("languages", bsoncxx::builder::basic::array{}),
                    kvp("rated", bsoncxx::builder::basic::array{}),
                    kvp("lastupdated", bsoncxx::builder::basic::array{}),
                    kvp("fullplot", bsoncxx::builder::basic::array{}),
                    kvp("awards", bsoncxx::builder::basic::array{})
                ))
            )),
            kvp("typeSets", []{
                auto arr = bsoncxx::builder::basic::array{};
                arr.append(make_document(
                    kvp("name", "moviesStringIndex"),
                    kvp("types", []{
                        auto types_arr = bsoncxx::builder::basic::array{};
                        types_arr.append(make_document(
                            kvp("type", "autocomplete")
                        ));
                        return types_arr;
                    }())
                ));
                return arr;
            }())
        );

        auto model = mongocxx::search_index_model(name, definition.view());

        // Create the search index
        auto result = siv.create_one(model);
        std::cout << "New index name: " << result << std::endl;
    }
}

```

#### Multiple Types Example

##### Index specific field as autocomplete and string types.

The following index definition example uses the `sample_mflix.movies` collection to index a field as multiple types. The following index definition indexes the `title` field as the following types:

- `autocomplete` type to support autocompletion for queries using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator.

- `string` type to support text search using operators such [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref), [phrase](https://www.mongodb.com/docs/search/query/operators-collectors/phrase.md#std-label-phrase-ref), and so on.

```cpp
#include <iostream>

#include <bsoncxx/builder/basic/document.hpp>
#include <bsoncxx/json.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/uri.hpp>

using bsoncxx::builder::basic::kvp;
using bsoncxx::builder::basic::make_document;

int main(){

    mongocxx::instance instance;
    mongocxx::uri uri("<connection-string>");
    mongocxx::client client(uri);

    auto db = client["sample_mflix"];
    auto collection = db["movies"];

    // instantiate a ``mongocxx::search_index_view`` on your collection
    auto siv = collection.search_indexes();

    {
        auto name = "default";
        auto definition = make_document(
            kvp("mappings", make_document(
                kvp("dynamic", false),
                kvp("fields", make_document(
                    kvp("title", make_document(
                        kvp("type", "autocomplete"),
                        kvp("analyzer", "lucene.standard"),
                        kvp("tokenization", "edgeGram"),
                        kvp("minGrams", 2),
                        kvp("maxGrams", 15),
                        kvp("foldDiacritics", false)
                    )),
                    kvp("plot", make_document(
                        kvp("type", "string")
                    ))
                ))
            ))
        );

        auto model = mongocxx::search_index_model(name, definition.view());

        // Create the search index
        auto result = siv.create_one(model);
        std::cout << "New index name: " << result << std::endl;
    }
}

```

#### Email Example

##### Index email address as the autocomplete type.

The following index definition example uses the [sample\_mflix.users](https://www.mongodb.com/docs/manual/sample-data/sample-mflix.md#std-label-sample-mflix) collection. The index definition example indexes only the `email` field as the `autocomplete` type to support search-as-you-type queries against that field using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. The index definition specifies the following:

- Use the [keyword](https://www.mongodb.com/docs/search/indexes/analyzers/keyword.md#std-label-ref-keyword-analyzer) analyzer to accept a string or array of strings as a parameter and index them as a single term (token).

- Use the [nGram](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-nGram-tokenizer-ref) tokenizer to tokenize text into chunks, or "n-grams", of given sizes.

- Index a minimum of `3` characters per indexed sequence.

- Index a maximum of `15` characters per indexed sequence.

- Include diacritic marks in the index and query text.

You can also use the `uaxUrlEmail` tokenizer to tokenizes URL (Uniform Resource Locator)s and email addresses. To learn more, see [uaxUrlEmail.](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-uaxUrlEmail-tokenizer-ref)

```cpp
#include <iostream>

#include <bsoncxx/builder/basic/document.hpp>
#include <bsoncxx/json.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/uri.hpp>
#include <mongocxx/search_index.hpp>

using bsoncxx::builder::basic::kvp;
using bsoncxx::builder::basic::make_document;

int main(){

    mongocxx::instance instance;
    mongocxx::uri uri("<connection-string>");
    mongocxx::client client(uri);

    auto db = client["sample_mflix"];
    auto collection = db["users"];

    // instantiate a ``mongocxx::search_index_view`` on your collection
    auto siv = collection.search_indexes();

    {
        auto name = "default";
        auto definition = make_document(
            kvp("mappings", make_document(
                kvp("dynamic", true),
                kvp("fields", make_document(
                    kvp("email", make_document(
                        kvp("type", "autocomplete"),
                        kvp("analyzer", "lucene.keyword"),
                        kvp("tokenization", "nGram"),
                        kvp("minGrams", 3),
                        kvp("maxGrams", 15),
                        kvp("foldDiacritics", false)
                    ))
                ))
            ))
        );

        auto model = mongocxx::search_index_model(name, definition.view());
        // Create the search index
        auto result = siv.create_one(model);
        if (result) {
            std::cout << "New index name: " << *result << std::endl;
        } else {
            std::cout << "Failed to create search index." << std::endl;
        }
    }
}
}

```

### Try an Example for the `autocomplete` Type

The following index definition examples use collections in the [sample data](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets). After you [load the sample data](https://www.mongodb.com/docs/atlas/import/load-sample-data.md#std-label-load-sample-data), you can use these examples to index fields as the `autocomplete` type.

To learn how to set up and run the following example code, see [Define the Index for the token Type](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-define-index-token-admin-api).

#### Basic Example

##### Index specific field using static mappings as autocomplete type.

The following index definition example uses the `sample_mflix.movies` collection. The index definition indexes only the `title` field as the `autocomplete` type to support search-as-you-type queries against that field using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. The index definition also specifies the following:

- Use the [standard](https://www.mongodb.com/docs/search/indexes/analyzers/standard.md#std-label-ref-standard-analyzer) analyzer to divide text values into terms based on word boundaries.

- Use the `edgeGram` tokenization strategy to index characters starting at the left side of the words .

- Index a minimum of `3` characters per indexed sequence.

- Index a maximum of `5` characters per indexed sequence.

- Include diacritic marks in the index and query text.

- Use the `stableTfl` [similarity algorithm](https://www.mongodb.com/docs/search/query/score/get-details.md#std-label-fts-similarity-algorithms) to ensure consistent document scoring across all search nodes and replica set members.

```go
package main

import (
	"context"
	"fmt"
	"log"

	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
)

func main() {
	ctx := context.Background()
	uri := "<connection-string>"
	client, err := mongo.Connect(options.Client().
		ApplyURI(uri))
	if err != nil {
		panic(err)
	}

	defer func() {
		if err := client.Disconnect(context.TODO()); err != nil {
			panic(err)
		}
	}()

	coll := client.Database("sample_mflix").Collection("movies")
	const indexName = "default"
	opts := options.SearchIndexes().SetName(indexName).SetType("search")

	// Define the MongoDB Search index for the autocomplete field type
	searchIndexModel := mongo.SearchIndexModel{
		Definition: bson.D{
			{"mappings", bson.D{
				{"dynamic", false},
				{"fields", bson.D{
					{"title", bson.D{
						{"type", "autocomplete"},
						{"analyzer", "lucene.standard"},
						{"tokenization", "edgeGram"},
						{"minGrams", 3},
						{"maxGrams", 5},
						{"foldDiacritics", false},
						{"similarity", bson.D{{"type", "stableTfl"}}},
					}},
				}},
			}},
		},
		Options: opts,
	}

	// Create the index
	searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, searchIndexModel)
	if err != nil {
		log.Fatalf("Failed to create the Atlas Search index: %v", err)
	}

	fmt.Println("Name of index created: " + searchIndexName)
}

```

#### Dynamic Index Example

##### Dynamically index string fields as the autocomplete type.

The following index definition for the `sample_mflix.movies` collection in the [sample dataset](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets) indexes all string fields at the root-level in the documents in the collection as the `autocomplete` type with default settings. It also excludes string fields like `poster`, `languages`, `rated`, `lastupdated`, `fullplot`, and `awards` from being indexed.

```go
package main

import (
	"context"
	"fmt"
	"log"

	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
)

func main() {
	ctx := context.Background()
	uri := "<connection-string>"
	client, err := mongo.Connect(options.Client().
		ApplyURI(uri))
	if err != nil {
		panic(err)
	}

	defer func() {
		if err := client.Disconnect(context.TODO()); err != nil {
			panic(err)
		}
	}()

	coll := client.Database("sample_mflix").Collection("movies")
	const indexName = "default"
	opts := options.SearchIndexes().SetName(indexName).SetType("search")

	// Define the Atlas Search index for the autocomplete field type
	searchIndexModel := mongo.SearchIndexModel{
		Definition: bson.D{
			{"mappings", bson.D{
				{"dynamic", bson.D{
					{"typeSet", "moviesStringIndex"},
				}},
				{"fields", bson.D{
					{"poster", bson.A{}},
					{"languages", bson.A{}},
					{"rated", bson.A{}},
					{"lastupdated", bson.A{}},
					{"fullplot", bson.A{}},
					{"awards", bson.A{}},
				}},
			}},
			{"typeSets", bson.A{
				bson.D{
					{"name", "moviesStringIndex"},
					{"types", bson.A{
						bson.D{
							{"type", "autocomplete"},
						},
					}},
				},
			}},
		},
		Options: opts,
	}

	// Create the index
	searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, searchIndexModel)
	if err != nil {
		log.Fatalf("Failed to create the Atlas Search index: %v", err)
	}

	fmt.Println("Name of index created: " + searchIndexName)
}
```

#### Multiple Types Example

##### Index specific field as autocomplete and string types.

The following index definition example uses the `sample_mflix.movies` collection to index a field as multiple types. The following index definition indexes the `title` field as the following types:

- `autocomplete` type to support autocompletion for queries using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator.

- `string` type to support text search using operators such [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref), [phrase](https://www.mongodb.com/docs/search/query/operators-collectors/phrase.md#std-label-phrase-ref), and so on.

```go
package main

import (
	"context"
	"fmt"
	"log"

	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
)

func main() {
	ctx := context.Background()
	uri := "<connection-string>"
	client, err := mongo.Connect(options.Client().
		ApplyURI(uri))
	if err != nil {
		panic(err)
	}

	defer func() {
		if err := client.Disconnect(context.TODO()); err != nil {
			panic(err)
		}
	}()

	coll := client.Database("sample_mflix").Collection("movies")
	const indexName = "default"
	opts := options.SearchIndexes().SetName(indexName).SetType("search")

	// Define the MongoDB Search index for the autocomplete field
	searchIndexModel := mongo.SearchIndexModel{
		Definition: bson.D{
			{"mappings", bson.D{
				{"dynamic", false},
				{"fields", bson.D{
					{"title", bson.A{
						bson.D{
							{"type", "autocomplete"},
							{"analyzer", "lucene.standard"},
							{"tokenization", "edgeGram"},
							{"minGrams", 2},
							{"maxGrams", 15},
							{"foldDiacritics", false},
						},
						bson.D{{"type", "string"}},
					}},
				}},
			}},
		},
		Options: opts,
	}

	// Create the index
	searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, searchIndexModel)
	if err != nil {
		log.Fatalf("Failed to create the Atlas Search index: %v", err)
	}

	fmt.Println("Name of index created: " + searchIndexName)
}

```

#### Email Example

##### Index email address as the autocomplete type.

The following index definition example uses the [sample\_mflix.users](https://www.mongodb.com/docs/manual/sample-data/sample-mflix.md#std-label-sample-mflix) collection. The index definition example indexes only the `email` field as the `autocomplete` type to support search-as-you-type queries against that field using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. The index definition specifies the following:

- Use the [keyword](https://www.mongodb.com/docs/search/indexes/analyzers/keyword.md#std-label-ref-keyword-analyzer) analyzer to accept a string or array of strings as a parameter and index them as a single term (token).

- Use the [nGram](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-nGram-tokenizer-ref) tokenizer to tokenize text into chunks, or "n-grams", of given sizes.

- Index a minimum of `3` characters per indexed sequence.

- Index a maximum of `15` characters per indexed sequence.

- Include diacritic marks in the index and query text.

You can also use the `uaxUrlEmail` tokenizer to tokenizes URL (Uniform Resource Locator)s and email addresses. To learn more, see [uaxUrlEmail.](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-uaxUrlEmail-tokenizer-ref)

```go
package main

import (
	"context"
	"fmt"
	"log"

	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
)

func main() {
	ctx := context.Background()
	uri := "<connection-string>"
	client, err := mongo.Connect(options.Client().
		ApplyURI(uri))
	if err != nil {
		panic(err)
	}

	defer func() {
		if err := client.Disconnect(context.TODO()); err != nil {
			panic(err)
		}
	}()

	coll := client.Database("sample_mflix").Collection("users")
	const indexName = "default"
	opts := options.SearchIndexes().SetName(indexName).SetType("search")

	// Define the MongoDB Search index for the autocomplete field type
	searchIndexModel := mongo.SearchIndexModel{
		Definition: bson.D{
			{"mappings", bson.D{
				{"dynamic", true},
				{"fields", bson.D{
					{"email", bson.D{
						{"type", "autocomplete"},
						{"analyzer", "lucene.keyword"},
						{"tokenization", "edgeGram"},
						{"minGrams", 3},
						{"maxGrams", 15},
						{"foldDiacritics", false},
					}},
				}},
			}},
		},
		Options: opts,
	}

	// Create the index
	searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, searchIndexModel)
	if err != nil {
		log.Fatalf("Failed to create the Atlas Search index: %v", err)
	}

	fmt.Println("Name of index created: " + searchIndexName)
}

```

### Try an Example for the `autocomplete` Type

The following index definition examples use collections in the [sample data](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets). After you [load the sample data](https://www.mongodb.com/docs/atlas/import/load-sample-data.md#std-label-load-sample-data), you can use these examples to index fields as the `autocomplete` type.

To learn how to set up and run the following example code, see [Define the Index for the token Type](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-define-index-token-admin-api).

#### Basic Example

##### Index specific field using static mappings as autocomplete type.

The following index definition example uses the `sample_mflix.movies` collection. The index definition indexes only the `title` field as the `autocomplete` type to support search-as-you-type queries against that field using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. The index definition also specifies the following:

- Use the [standard](https://www.mongodb.com/docs/search/indexes/analyzers/standard.md#std-label-ref-standard-analyzer) analyzer to divide text values into terms based on word boundaries.

- Use the `edgeGram` tokenization strategy to index characters starting at the left side of the words .

- Index a minimum of `3` characters per indexed sequence.

- Index a maximum of `5` characters per indexed sequence.

- Include diacritic marks in the index and query text.

- Use the `stableTfl` [similarity algorithm](https://www.mongodb.com/docs/search/query/score/get-details.md#std-label-fts-similarity-algorithms) to ensure consistent document scoring across all search nodes and replica set members.

```java
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("sample_mflix");
            MongoCollection<Document> collection = database.getCollection("movies");
            String indexName = "default";

            Document searchIdx = new Document("mappings",
                    new Document("dynamic", false)
                        .append("fields", new Document("title", 
                                              new Document("type", "autocomplete")
                                                  .append("analyzer", "lucene.standard")
                                                  .append("tokenization", "edgeGram")
                                                  .append("minGrams", 3)
                                                  .append("maxGrams", 5)
                                                  .append("foldDiacritics", false)
                                                  .append("similarity", new Document("type", "stableTfl"))
                                                  )));

            collection.createSearchIndex(indexName, searchIdx);
            System.out.println("New index name: " + indexName);
        } catch (Exception e) {
            System.err.println("Error creating Atlas Search index: " + e.getMessage());
        }
    }
}
```

#### Multiple Types Example

##### Index specific field as autocomplete and string types.

The following index definition example uses the `sample_mflix.movies` collection to index a field as multiple types. The following index definition indexes the `title` field as the following types:

- `autocomplete` type to support autocompletion for queries using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator.

- `string` type to support text search using operators such [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref), [phrase](https://www.mongodb.com/docs/search/query/operators-collectors/phrase.md#std-label-phrase-ref), and so on.

```java
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("sample_mflix");
            MongoCollection<Document> collection = database.getCollection("movies");
            String indexName = "default";

            Document searchIdx = new Document("mappings",
                    new Document("dynamic", false)
                        .append("fields", new Document("title", 
                            java.util.Arrays.asList(
                                new Document("type", "autocomplete")
                                    .append("analyzer", "lucene.standard")
                                    .append("tokenization", "edgeGram")
                                    .append("minGrams", 2)
                                    .append("maxGrams", 15)
                                    .append("foldDiacritics", false),
                                new Document("type", "string")
                            )
                        ))
            );

            collection.createSearchIndex(indexName, searchIdx);
            System.out.println("New index name: " + indexName);
        } catch (Exception e) {
            System.err.println("Error creating Atlas Search index: " + e.getMessage());
        }
    }
}
```

#### Email Example

##### Index email address as the autocomplete type.

The following index definition example uses the [sample\_mflix.users](https://www.mongodb.com/docs/manual/sample-data/sample-mflix.md#std-label-sample-mflix) collection. The index definition example indexes only the `email` field as the `autocomplete` type to support search-as-you-type queries against that field using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. The index definition specifies the following:

- Use the [keyword](https://www.mongodb.com/docs/search/indexes/analyzers/keyword.md#std-label-ref-keyword-analyzer) analyzer to accept a string or array of strings as a parameter and index them as a single term (token).

- Use the [nGram](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-nGram-tokenizer-ref) tokenizer to tokenize text into chunks, or "n-grams", of given sizes.

- Index a minimum of `3` characters per indexed sequence.

- Index a maximum of `15` characters per indexed sequence.

- Include diacritic marks in the index and query text.

You can also use the `uaxUrlEmail` tokenizer to tokenizes URL (Uniform Resource Locator)s and email addresses. To learn more, see [uaxUrlEmail.](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-uaxUrlEmail-tokenizer-ref)

```java
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("sample_mflix");
            MongoCollection<Document> collection = database.getCollection("users");
            String indexName = "default";

            Document searchIdx = new Document("mappings",
                    new Document("dynamic", true)
                        .append("fields", new Document("email", 
                                              new Document("type", "autocomplete")
                                                  .append("analyzer", "lucene.keyword")
                                                  .append("tokenization", "nGram")
                                                  .append("minGrams", 3)
                                                  .append("maxGrams", 15)
                                                  .append("foldDiacritics", false)
                                                  )));

            collection.createSearchIndex(indexName, searchIdx);
            System.out.println("New index name: " + indexName);
        } catch (Exception e) {
            System.err.println("Error creating Atlas Search index: " + e.getMessage());
        }
    }
}
```

### Try an Example for the `autocomplete` Type

The following index definition examples use collections in the [sample data](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets). After you [load the sample data](https://www.mongodb.com/docs/atlas/import/load-sample-data.md#std-label-load-sample-data), you can use these examples to index fields as the `autocomplete` type.

To learn how to set up and run the following example code, see [Define the Index for the token Type](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-define-index-token-admin-api).

#### Basic Example

##### Index specific field using static mappings as autocomplete type.

The following index definition example uses the `sample_mflix.movies` collection. The index definition indexes only the `title` field as the `autocomplete` type to support search-as-you-type queries against that field using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. The index definition also specifies the following:

- Use the [standard](https://www.mongodb.com/docs/search/indexes/analyzers/standard.md#std-label-ref-standard-analyzer) analyzer to divide text values into terms based on word boundaries.

- Use the `edgeGram` tokenization strategy to index characters starting at the left side of the words .

- Index a minimum of `3` characters per indexed sequence.

- Index a maximum of `5` characters per indexed sequence.

- Include diacritic marks in the index and query text.

- Use the `stableTfl` [similarity algorithm](https://www.mongodb.com/docs/search/query/score/get-details.md#std-label-fts-similarity-algorithms) to ensure consistent document scoring across all search nodes and replica set members.

```javascript
const { MongoClient } = require("mongodb");

// connect to your Atlas deployment
const uri =  "<connection-string>";

const client = new MongoClient(uri);

async function run() {
  try {

    // set namespace
    const database = client.db("sample_mflix");
    const collection = database.collection("movies");

    // define your MongoDB Search index
    const index = {
      name: "default",
      definition: {
        /* search index definition fields */
        "mappings": {
          "dynamic": false,
          "fields": {
            "title": {
              "type": "autocomplete",
              "analyzer": "lucene.standard",
              "tokenization": "edgeGram",
              "minGrams": 3,
              "maxGrams": 5,
              "foldDiacritics": false,
              "similarity": { "type": "stableTfl" }
            }
          }
        }
      }
    }

    // run the helper method
    const result = await collection.createSearchIndex(index);
    console.log("New index name: " + result);
  } finally {
    await client.close();
  }
}

run().catch(console.dir);
```

#### Dynamic Index Example

##### Dynamically index string fields as the autocomplete type.

The following index definition for the `sample_mflix.movies` collection in the [sample dataset](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets) indexes all string fields at the root-level in the documents in the collection as the `autocomplete` type with default settings. It also excludes string fields like `poster`, `languages`, `rated`, `lastupdated`, `fullplot`, and `awards` from being indexed.

```javascript
const { MongoClient } = require("mongodb");

// connect to your Atlas deployment
const uri =  "<connection-string>";

const client = new MongoClient(uri);

async function run() {
  try {

    // set namespace
    const database = client.db("sample_mflix");
    const collection = database.collection("movies");

    // define your Atlas Search index
    const index = {
      name: "default",
      definition: {
        "mappings": {
          "dynamic": {
            "typeSet": "moviesStringIndex"
          },
          "fields": {
            "poster": [],
            "languages": [],
            "rated": [],
            "lastupdated": [],
            "fullplot": [],
            "awards": []
          }
        },
        "typeSets": [
          {
            "name": "moviesStringIndex",
            "types": [
              {
                "type": "autocomplete"
              }
            ]
          }
        ]
      }
    }

    // run the helper method
    const result = await collection.createSearchIndex(index);
    console.log("New index name: " + result);
  } finally {
    await client.close();
  }
}

run().catch(console.dir);
```

#### Multiple Types Example

##### Index specific field as autocomplete and string types.

The following index definition example uses the `sample_mflix.movies` collection to index a field as multiple types. The following index definition indexes the `title` field as the following types:

- `autocomplete` type to support autocompletion for queries using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator.

- `string` type to support text search using operators such [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref), [phrase](https://www.mongodb.com/docs/search/query/operators-collectors/phrase.md#std-label-phrase-ref), and so on.

```javascript
const { MongoClient } = require("mongodb");

// connect to your Atlas deployment
const uri =  "<connection-string>";

const client = new MongoClient(uri);

async function run() {
  try {

    // set namespace
    const database = client.db("sample_mflix");
    const collection = database.collection("movies");

    // define your MongoDB Search index
    const index = {
      name: "default",
      definition: {
        /* search index definition fields */
        "mappings": {
          "dynamic": false,
          "fields": {
            "title": [{
              "type": "autocomplete",
              "analyzer": "lucene.standard",
              "tokenization": "edgeGram",
              "minGrams": 2,
              "maxGrams": 15,
              "foldDiacritics": false
            },
            {
              "type": "string",
            }]
          }
        }
      }
    }

    // run the helper method
    const result = await collection.createSearchIndex(index);
    console.log("New index name: " + result);
  } finally {
    await client.close();
  }
}

run().catch(console.dir);
```

#### Email Example

##### Index email address as the autocomplete type.

The following index definition example uses the [sample\_mflix.users](https://www.mongodb.com/docs/manual/sample-data/sample-mflix.md#std-label-sample-mflix) collection. The index definition example indexes only the `email` field as the `autocomplete` type to support search-as-you-type queries against that field using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. The index definition specifies the following:

- Use the [keyword](https://www.mongodb.com/docs/search/indexes/analyzers/keyword.md#std-label-ref-keyword-analyzer) analyzer to accept a string or array of strings as a parameter and index them as a single term (token).

- Use the [nGram](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-nGram-tokenizer-ref) tokenizer to tokenize text into chunks, or "n-grams", of given sizes.

- Index a minimum of `3` characters per indexed sequence.

- Index a maximum of `15` characters per indexed sequence.

- Include diacritic marks in the index and query text.

You can also use the `uaxUrlEmail` tokenizer to tokenizes URL (Uniform Resource Locator)s and email addresses. To learn more, see [uaxUrlEmail.](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-uaxUrlEmail-tokenizer-ref)

```javascript
const { MongoClient } = require("mongodb");

// connect to your Atlas deployment
const uri =  "<connection-string>";

const client = new MongoClient(uri);

async function run() {
  try {

    // set namespace
    const database = client.db("sample_mflix");
    const collection = database.collection("users");

    // define your MongoDB Search index
    const index = {
      name: "default",
      definition: {
        /* search index definition fields */
        "mappings": {
          "dynamic": true,
          "fields": {
            "email": {
              "type": "autocomplete",
              "analyzer": "lucene.keyword",
              "tokenization": "nGram",
              "minGrams": 2,
              "maxGrams": 15,
              "foldDiacritics": false
            }
          }
        }
      }
    }

    // run the helper method
    const result = await collection.createSearchIndex(index);
    console.log("New index name: " + result);
  } finally {
    await client.close();
  }
}

run().catch(console.dir);
```

### Try an Example for the `autocomplete` Type

The following index definition examples use collections in the [sample data](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets). After you [load the sample data](https://www.mongodb.com/docs/atlas/import/load-sample-data.md#std-label-load-sample-data), you can use these examples to index fields as the `autocomplete` type.

To learn how to set up and run the following example code, see [Define the Index for the token Type](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-define-index-token-admin-api).

#### Basic Example

##### Index specific field using static mappings as autocomplete type.

The following index definition example uses the `sample_mflix.movies` collection. The index definition indexes only the `title` field as the `autocomplete` type to support search-as-you-type queries against that field using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. The index definition also specifies the following:

- Use the [standard](https://www.mongodb.com/docs/search/indexes/analyzers/standard.md#std-label-ref-standard-analyzer) analyzer to divide text values into terms based on word boundaries.

- Use the `edgeGram` tokenization strategy to index characters starting at the left side of the words .

- Index a minimum of `3` characters per indexed sequence.

- Index a maximum of `5` characters per indexed sequence.

- Include diacritic marks in the index and query text.

- Use the `stableTfl` [similarity algorithm](https://www.mongodb.com/docs/search/query/score/get-details.md#std-label-fts-similarity-algorithms) to ensure consistent document scoring across all search nodes and replica set members.

```python
from pymongo import MongoClient
from pymongo.operations import SearchIndexModel

# connect to your Atlas deployment
uri = "<connection-string>"
client = MongoClient(uri)

# set namespace
database = client["sample_mflix"]
collection = database["movies"]

# define your MongoDB Search index
search_index_model = SearchIndexModel(
    definition={
        "mappings": {
            "dynamic": False,
            "fields": {
                "title":{
                   "type": "autocomplete",
                   "analyzer": "lucene.standard",
                   "tokenization": "edgeGram",
                   "minGrams": 3,
                   "maxGrams": 5,
                   "foldDiacritics": False,
                   "similarity": { "type": "stableTfl" }                
                }
            }
        },
    },
    name="default",
)

# create the index
result = collection.create_search_index(model=search_index_model)
print(f"New index name: {result}")

```

#### Dynamic Index Example

##### Dynamically index string fields as the autocomplete type.

The following index definition for the `sample_mflix.movies` collection in the [sample dataset](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets) indexes all string fields at the root-level in the documents in the collection as the `autocomplete` type with default settings. It also excludes string fields like `poster`, `languages`, `rated`, `lastupdated`, `fullplot`, and `awards` from being indexed.

```python
from pymongo import MongoClient
from pymongo.operations import SearchIndexModel

# connect to your Atlas deployment
uri = "<connection-string>"
client = MongoClient(uri)

# set namespace
database = client["sample_mflix"]
collection = database["movies"]

# define your Atlas Search index
search_index_model = SearchIndexModel(
    definition={
      "mappings": {
        "dynamic": {
          "typeSet": "moviesStringIndex"
        },
        "fields": {
          "poster": [],
          "languages": [],
          "rated": [],
          "lastupdated": [],
          "fullplot": [],
          "awards": []
        }
      },
      "typeSets": [
        {
          "name": "moviesStringIndex",
          "types": [
            {
              "type": "autocomplete"
            }
          ]
        }
      ]
    },
    name="default",
)

# create the index
result = collection.create_search_index(model=search_index_model)
print(f"New index name: {result}")

```

#### Multiple Types Example

##### Index specific field as autocomplete and string types.

The following index definition example uses the `sample_mflix.movies` collection to index a field as multiple types. The following index definition indexes the `title` field as the following types:

- `autocomplete` type to support autocompletion for queries using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator.

- `string` type to support text search using operators such [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref), [phrase](https://www.mongodb.com/docs/search/query/operators-collectors/phrase.md#std-label-phrase-ref), and so on.

```python
from pymongo import MongoClient
from pymongo.operations import SearchIndexModel

# connect to your Atlas deployment
uri = "<connection-string>"
client = MongoClient(uri)

# set namespace
database = client["sample_mflix"]
collection = database["movies"]

# define your MongoDB Search index
search_index_model = SearchIndexModel(
    definition={
        "mappings": {
            "dynamic": False,
            "fields": {
                "title":[{
                   "type": "autocomplete",
                   "analyzer": "lucene.standard",
                   "tokenization": "edgeGram",
                   "minGrams": 2,
                   "maxGrams": 15,
                   "foldDiacritics": False
                },
                {
                    "type": "string"
                }]
            }
        },
    },
    name="default",
)

# create the index
result = collection.create_search_index(model=search_index_model)
print(f"New index name: {result}")

```

#### Email Example

##### Index email address as the autocomplete type.

The following index definition example uses the [sample\_mflix.users](https://www.mongodb.com/docs/manual/sample-data/sample-mflix.md#std-label-sample-mflix) collection. The index definition example indexes only the `email` field as the `autocomplete` type to support search-as-you-type queries against that field using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. The index definition specifies the following:

- Use the [keyword](https://www.mongodb.com/docs/search/indexes/analyzers/keyword.md#std-label-ref-keyword-analyzer) analyzer to accept a string or array of strings as a parameter and index them as a single term (token).

- Use the [nGram](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-nGram-tokenizer-ref) tokenizer to tokenize text into chunks, or "n-grams", of given sizes.

- Index a minimum of `3` characters per indexed sequence.

- Index a maximum of `15` characters per indexed sequence.

- Include diacritic marks in the index and query text.

You can also use the `uaxUrlEmail` tokenizer to tokenizes URL (Uniform Resource Locator)s and email addresses. To learn more, see [uaxUrlEmail.](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-uaxUrlEmail-tokenizer-ref)

```python
from pymongo import MongoClient
from pymongo.operations import SearchIndexModel

# connect to your Atlas deployment
uri = "<connection-string>"
client = MongoClient(uri)

# set namespace
database = client["sample_mflix"]
collection = database["users"]

# define your MongoDB Search index
search_index_model = SearchIndexModel(
    definition={
        "mappings": {
            "dynamic": True,
            "fields": {
                "email":{
                   "type": "autocomplete",
                   "analyzer": "lucene.keyword",
                   "tokenization": "nGram",
                   "minGrams": 3,
                   "maxGrams": 15,
                   "foldDiacritics": False
                }
            }
        },
    },
    name="default",
)

# create the index
result = collection.create_search_index(model=search_index_model)
print(f"New index name: {result}")

```

To learn how to set up and run the following example code, see [Define the Index for the token Type](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-define-index-token-admin-api).

### Try an Example for the `autocomplete` Type

The following index definition examples use collections in the [sample data](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets). After you [load the sample data](https://www.mongodb.com/docs/atlas/import/load-sample-data.md#std-label-load-sample-data), you can use these examples to index fields as the `autocomplete` type.

To learn how to set up and run the following example code, see [Define the Index for the token Type](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-define-index-token-admin-api).

#### Basic Example

##### Index specific field using static mappings as autocomplete type.

The following index definition example uses the `sample_mflix.movies` collection. The index definition indexes only the `title` field as the `autocomplete` type to support search-as-you-type queries against that field using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. The index definition also specifies the following:

- Use the [standard](https://www.mongodb.com/docs/search/indexes/analyzers/standard.md#std-label-ref-standard-analyzer) analyzer to divide text values into terms based on word boundaries.

- Use the `edgeGram` tokenization strategy to index characters starting at the left side of the words .

- Index a minimum of `3` characters per indexed sequence.

- Index a maximum of `5` characters per indexed sequence.

- Include diacritic marks in the index and query text.

- Use the `stableTfl` [similarity algorithm](https://www.mongodb.com/docs/search/query/score/get-details.md#std-label-fts-similarity-algorithms) to ensure consistent document scoring across all search nodes and replica set members.

```bash
{
  "mappings": {
    "dynamic": false,
    "fields": {
      "title": {
        "type": "autocomplete",
        "analyzer": "lucene.standard",
        "tokenization": "edgeGram",
        "minGrams": 3,
        "maxGrams": 5,
        "foldDiacritics": false,
        "similarity": { "type": "stableTfl" }
    }
  }
}
```

#### Dynamic Index Example

##### Dynamically index string fields as the autocomplete type.

The following index definition for the `sample_mflix.movies` collection in the [sample dataset](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets) indexes all string fields at the root-level in the documents in the collection as the `autocomplete` type with default settings. It also excludes string fields like `poster`, `languages`, `rated`, `lastupdated`, `fullplot`, and `awards` from being indexed.

```bash
{
  "mappings": {
    "dynamic": {
      "typeSet": "moviesStringIndex"
    },
    "fields": {
      "poster": [],
      "languages": [],
      "rated": [],
      "lastupdated": [],
      "fullplot": [],
      "awards": []
    }
  },
  "typeSets": [
    {
      "name": "moviesStringIndex",
      "types": [
        {
          "type": "autocomplete"
        }
      ]
    }
  ]
}
```

#### Multiple Types Example

##### Index specific field as autocomplete and string types.

The following index definition example uses the `sample_mflix.movies` collection to index a field as multiple types. The following index definition indexes the `title` field as the following types:

- `autocomplete` type to support autocompletion for queries using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator.

- `string` type to support text search using operators such [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref), [phrase](https://www.mongodb.com/docs/search/query/operators-collectors/phrase.md#std-label-phrase-ref), and so on.

```bash
{
  "mappings": {
    "dynamic": true|false,
    "fields": {
      "title": [
        {
          "type": "autocomplete",
          "analyzer": "lucene.standard",
          "tokenization": "edgeGram",
          "minGrams": 2,
          "maxGrams": 15,
          "foldDiacritics": false
        },
        {
          "type": "string"
        }
      ]
    }
  }
}
```

#### Email Example

##### Index email address as the autocomplete type.

The following index definition example uses the [sample\_mflix.users](https://www.mongodb.com/docs/manual/sample-data/sample-mflix.md#std-label-sample-mflix) collection. The index definition example indexes only the `email` field as the `autocomplete` type to support search-as-you-type queries against that field using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. The index definition specifies the following:

- Use the [keyword](https://www.mongodb.com/docs/search/indexes/analyzers/keyword.md#std-label-ref-keyword-analyzer) analyzer to accept a string or array of strings as a parameter and index them as a single term (token).

- Use the [nGram](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-nGram-tokenizer-ref) tokenizer to tokenize text into chunks, or "n-grams", of given sizes.

- Index a minimum of `3` characters per indexed sequence.

- Index a maximum of `15` characters per indexed sequence.

- Include diacritic marks in the index and query text.

You can also use the `uaxUrlEmail` tokenizer to tokenizes URL (Uniform Resource Locator)s and email addresses. To learn more, see [uaxUrlEmail.](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-uaxUrlEmail-tokenizer-ref)

```bash
{
  "mappings": {
    "dynamic": true,
    "fields": {
      "email": {
        "type": "autocomplete",
        "analyzer": "lucene.keyword",
        "tokenization": "nGram",
        "minGrams": 3,
        "maxGrams": 15,
        "foldDiacritics": false
      }
    }
  }
}
```

### Try an Example for the `autocomplete` Type

The following index definition examples use collections in the [sample data](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets). After you [load the sample data](https://www.mongodb.com/docs/atlas/import/load-sample-data.md#std-label-load-sample-data), you can use these examples to index fields as the `autocomplete` type.

To learn how to set up and run the following example code, see [Define the Index for the token Type](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-define-index-token-admin-api).

#### Basic Example

##### Index specific field using static mappings as autocomplete type.

The following index definition example uses the `sample_mflix.movies` collection. The index definition indexes only the `title` field as the `autocomplete` type to support search-as-you-type queries against that field using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. The index definition also specifies the following:

- Use the [standard](https://www.mongodb.com/docs/search/indexes/analyzers/standard.md#std-label-ref-standard-analyzer) analyzer to divide text values into terms based on word boundaries.

- Use the `edgeGram` tokenization strategy to index characters starting at the left side of the words .

- Index a minimum of `3` characters per indexed sequence.

- Index a maximum of `5` characters per indexed sequence.

- Include diacritic marks in the index and query text.

- Use the `stableTfl` [similarity algorithm](https://www.mongodb.com/docs/search/query/score/get-details.md#std-label-fts-similarity-algorithms) to ensure consistent document scoring across all search nodes and replica set members.

```none
{
  "mappings": {
    "dynamic": false,
    "fields": {
      "title": {
        "type": "autocomplete",
        "analyzer": "lucene.standard",
        "tokenization": "edgeGram",
        "minGrams": 3,
        "maxGrams": 5,
        "foldDiacritics": false,
        "similarity": { "type": "stableTfl" }
    }
  }
}
```

#### Dynamic Index Example

##### Dynamically index string fields as the autocomplete type.

The following index definition for the `sample_mflix.movies` collection in the [sample dataset](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets) indexes all string fields at the root-level in the documents in the collection as the `autocomplete` type with default settings. It also excludes string fields like `poster`, `languages`, `rated`, `lastupdated`, `fullplot`, and `awards` from being indexed.

```none
{
  "mappings": {
    "dynamic": {
      "typeSet": "moviesStringIndex"
    },
    "fields": {
      "poster": [],
      "languages": [],
      "rated": [],
      "lastupdated": [],
      "fullplot": [],
      "awards": []
    }
  },
  "typeSets": [
    {
      "name": "moviesStringIndex",
      "types": [
        {
          "type": "autocomplete"
        }
      ]
    }
  ]
}
```

#### Multiple Types Example

##### Index specific field as autocomplete and string types.

The following index definition example uses the `sample_mflix.movies` collection to index a field as multiple types. The following index definition indexes the `title` field as the following types:

- `autocomplete` type to support autocompletion for queries using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator.

- `string` type to support text search using operators such [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref), [phrase](https://www.mongodb.com/docs/search/query/operators-collectors/phrase.md#std-label-phrase-ref), and so on.

```none
{
  "mappings": {
    "dynamic": true|false,
    "fields": {
      "title": [
        {
          "type": "autocomplete",
          "analyzer": "lucene.standard",
          "tokenization": "edgeGram",
          "minGrams": 2,
          "maxGrams": 15,
          "foldDiacritics": false
        },
        {
          "type": "string"
        }
      ]
    }
  }
}
```

#### Email Example

##### Index email address as the autocomplete type.

The following index definition example uses the [sample\_mflix.users](https://www.mongodb.com/docs/manual/sample-data/sample-mflix.md#std-label-sample-mflix) collection. The index definition example indexes only the `email` field as the `autocomplete` type to support search-as-you-type queries against that field using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. The index definition specifies the following:

- Use the [keyword](https://www.mongodb.com/docs/search/indexes/analyzers/keyword.md#std-label-ref-keyword-analyzer) analyzer to accept a string or array of strings as a parameter and index them as a single term (token).

- Use the [nGram](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-nGram-tokenizer-ref) tokenizer to tokenize text into chunks, or "n-grams", of given sizes.

- Index a minimum of `3` characters per indexed sequence.

- Index a maximum of `15` characters per indexed sequence.

- Include diacritic marks in the index and query text.

You can also use the `uaxUrlEmail` tokenizer to tokenizes URL (Uniform Resource Locator)s and email addresses. To learn more, see [uaxUrlEmail.](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-uaxUrlEmail-tokenizer-ref)

```none
{
  "mappings": {
    "dynamic": true,
    "fields": {
      "email": {
        "type": "autocomplete",
        "analyzer": "lucene.keyword",
        "tokenization": "nGram",
        "minGrams": 3,
        "maxGrams": 15,
        "foldDiacritics": false
      }
    }
  }
}
```

### Try an Example for the `autocomplete` Type

The following index definition examples use collections in the [sample data](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets). After you [load the sample data](https://www.mongodb.com/docs/atlas/import/load-sample-data.md#std-label-load-sample-data), you can use these examples to index fields as the `autocomplete` type.

To learn how to set up and run the following example code, see [Define the Index for the token Type](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-define-index-token-admin-api).

#### Basic Example

##### Index specific field using static mappings as autocomplete type.

The following index definition example uses the `sample_mflix.movies` collection. The index definition indexes only the `title` field as the `autocomplete` type to support search-as-you-type queries against that field using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. The index definition also specifies the following:

- Use the [standard](https://www.mongodb.com/docs/search/indexes/analyzers/standard.md#std-label-ref-standard-analyzer) analyzer to divide text values into terms based on word boundaries.

- Use the `edgeGram` tokenization strategy to index characters starting at the left side of the words .

- Index a minimum of `3` characters per indexed sequence.

- Index a maximum of `5` characters per indexed sequence.

- Include diacritic marks in the index and query text.

- Use the `stableTfl` [similarity algorithm](https://www.mongodb.com/docs/search/query/score/get-details.md#std-label-fts-similarity-algorithms) to ensure consistent document scoring across all search nodes and replica set members.

```javascript
db.movies.createSearchIndex(
  "default", 
  {
    "mappings": {
      "dynamic": false,
      "fields": {
        "title": {
          "type": "autocomplete",
          "analyzer": "lucene.standard",
          "tokenization": "edgeGram",
          "minGrams": 3,
          "maxGrams": 5,
          "foldDiacritics": false,
          "similarity": { "type": "stableTfl" }
        }
      }
    }
  }
)
```

#### Dynamic Index Example

##### Dynamically index string fields as the autocomplete type.

The following index definition for the `sample_mflix.movies` collection in the [sample dataset](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets) indexes all string fields at the root-level in the documents in the collection as the `autocomplete` type with default settings. It also excludes string fields like `poster`, `languages`, `rated`, `lastupdated`, `fullplot`, and `awards` from being indexed.

```javascript
db.users.createSearchIndex(
  "default", 
  {
    "mappings": {
      "dynamic": {
        "typeSet": "moviesStringIndex"
      },
      "fields": {
        "poster": [],
        "languages": [],
        "rated": [],
        "lastupdated": [],
        "fullplot": [],
        "awards": []
      }
    },
    "typeSets": [
      {
        "name": "moviesStringIndex",
        "types": [
          {
            "type": "autocomplete"
          }
        ]
      }
    ]
  }
)
```

#### Multiple Types Example

##### Index specific field as autocomplete and string types.

The following index definition example uses the `sample_mflix.movies` collection to index a field as multiple types. The following index definition indexes the `title` field as the following types:

- `autocomplete` type to support autocompletion for queries using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator.

- `string` type to support text search using operators such [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref), [phrase](https://www.mongodb.com/docs/search/query/operators-collectors/phrase.md#std-label-phrase-ref), and so on.

```javascript
db.movies.createSearchIndex(
  "default", 
  {
    "mappings": {
      "dynamic": false,
      "fields": {
        "title": [
          {
            "type": "autocomplete",
            "analyzer": "lucene.standard",
            "tokenization": "edgeGram",
            "minGrams": 2,
            "maxGrams": 15,
            "foldDiacritics": false
          },
          {
            "type": "string"
          }
        ]
      }
    }
  }
)
```

#### Email Example

##### Index email address as the autocomplete type.

The following index definition example uses the [sample\_mflix.users](https://www.mongodb.com/docs/manual/sample-data/sample-mflix.md#std-label-sample-mflix) collection. The index definition example indexes only the `email` field as the `autocomplete` type to support search-as-you-type queries against that field using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. The index definition specifies the following:

- Use the [keyword](https://www.mongodb.com/docs/search/indexes/analyzers/keyword.md#std-label-ref-keyword-analyzer) analyzer to accept a string or array of strings as a parameter and index them as a single term (token).

- Use the [nGram](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-nGram-tokenizer-ref) tokenizer to tokenize text into chunks, or "n-grams", of given sizes.

- Index a minimum of `3` characters per indexed sequence.

- Index a maximum of `15` characters per indexed sequence.

- Include diacritic marks in the index and query text.

You can also use the `uaxUrlEmail` tokenizer to tokenizes URL (Uniform Resource Locator)s and email addresses. To learn more, see [uaxUrlEmail.](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-uaxUrlEmail-tokenizer-ref)

```javascript
db.users.createSearchIndex(
  "default", 
  {
    "mappings": {
      "dynamic": true,
      "fields": {
        "email": {
          "type": "autocomplete",
          "analyzer": "lucene.keyword",
          "tokenization": "nGram",
          "minGrams": 3,
          "maxGrams": 15,
          "foldDiacritics": false
        }
      }
    }
  }
)
```

### Try an Example for the `autocomplete` Type

The following index definition examples use collections in the [sample data](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets). After you [load the sample data](https://www.mongodb.com/docs/atlas/import/load-sample-data.md#std-label-load-sample-data), you can use these examples to index fields as the `autocomplete` type.

To learn how to set up and run the following example code, see [Define the Index for the token Type](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-define-index-token-admin-api).

#### Basic Example

##### Index specific field using static mappings as autocomplete type.

The following index definition example uses the `sample_mflix.movies` collection. The index definition indexes only the `title` field as the `autocomplete` type to support search-as-you-type queries against that field using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. The index definition also specifies the following:

- Use the [standard](https://www.mongodb.com/docs/search/indexes/analyzers/standard.md#std-label-ref-standard-analyzer) analyzer to divide text values into terms based on word boundaries.

- Use the `edgeGram` tokenization strategy to index characters starting at the left side of the words .

- Index a minimum of `3` characters per indexed sequence.

- Index a maximum of `5` characters per indexed sequence.

- Include diacritic marks in the index and query text.

- Use the `stableTfl` [similarity algorithm](https://www.mongodb.com/docs/search/query/score/get-details.md#std-label-fts-similarity-algorithms) to ensure consistent document scoring across all search nodes and replica set members.

```c
#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, "sample_mflix");
    collection = mongoc_database_get_collection(database, "movies");

    // Specify the command and the new index
    const char *cmd_str = BSON_STR({
        "createSearchIndexes" : "movies",
        "indexes" : [ {
            "name" : "default",
            "definition" : {
              "mappings": {
                "dynamic": false,
                 "fields": {
                  "title": {
                    "type": "autocomplete",
                    "analyzer": "lucene.standard",
                    "tokenization": "edgeGram",
                    "minGrams": 3,
                    "maxGrams": 5,
                    "foldDiacritics": false,
                    "similarity": { "type": "stableTfl" }
                  }
                }
              }
            }
	    } ]
	});

    // 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 MongoDB 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;
}
```

#### Dynamic Index Example

##### Dynamically index string fields as the autocomplete type.

The following index definition for the `sample_mflix.movies` collection in the [sample dataset](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets) indexes all string fields at the root-level in the documents in the collection as the `autocomplete` type with default settings. It also excludes string fields like `poster`, `languages`, `rated`, `lastupdated`, `fullplot`, and `awards` from being indexed.

```c
#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, "sample_mflix");
    collection = mongoc_database_get_collection(database, "movies");

    // Specify the command and the new index
    const char *cmd_str = BSON_STR({
        "createSearchIndexes" : "movies",
        "indexes" : [ {
            "name" : "default",
            "definition" : {
              "mappings": {
                "dynamic": {
                  "typeSet": "moviesStringIndex"
                },
                "fields": {
                  "poster": [],
                  "languages": [],
                  "rated": [],
                  "lastupdated": [],
                  "fullplot": [],
                  "awards": []
                }
              },
              "typeSets": [
                {
                  "name": "moviesStringIndex",
                  "types": [
                    {
                      "type": "autocomplete"
                    }
                  ]
                }
              ]
            }
	    } ]
	});

    // 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;
}
```

#### Multiple Types Example

##### Index specific field as autocomplete and string types.

The following index definition example uses the `sample_mflix.movies` collection to index a field as multiple types. The following index definition indexes the `title` field as the following types:

- `autocomplete` type to support autocompletion for queries using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator.

- `string` type to support text search using operators such [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref), [phrase](https://www.mongodb.com/docs/search/query/operators-collectors/phrase.md#std-label-phrase-ref), and so on.

```c
#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, "sample_mflix");
    collection = mongoc_database_get_collection(database, "users");

    // Specify the command and the new index
    const char *cmd_str = BSON_STR({
        "createSearchIndexes" : "users",
        "indexes" : [ {
            "name" : "default",
            "definition" : {
              "mappings": {
                "dynamic": false,
                "fields": {
                  "title": [
                    {
                      "type": "autocomplete",
                      "analyzer": "lucene.standard",
                      "tokenization": "edgeGram",
                      "minGrams": 2,
                      "maxGrams": 15,
                      "foldDiacritics": false
                    },
                    {
                      "type": "string"
                    }
                  ]
                }
              }
            }
	    } ]
	});

    // 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 MongoDB 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;
}
```

#### Email Example

##### Index email address as the autocomplete type.

The following index definition example uses the [sample\_mflix.users](https://www.mongodb.com/docs/manual/sample-data/sample-mflix.md#std-label-sample-mflix) collection. The index definition example indexes only the `email` field as the `autocomplete` type to support search-as-you-type queries against that field using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. The index definition specifies the following:

- Use the [keyword](https://www.mongodb.com/docs/search/indexes/analyzers/keyword.md#std-label-ref-keyword-analyzer) analyzer to accept a string or array of strings as a parameter and index them as a single term (token).

- Use the [nGram](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-nGram-tokenizer-ref) tokenizer to tokenize text into chunks, or "n-grams", of given sizes.

- Index a minimum of `3` characters per indexed sequence.

- Index a maximum of `15` characters per indexed sequence.

- Include diacritic marks in the index and query text.

You can also use the `uaxUrlEmail` tokenizer to tokenizes URL (Uniform Resource Locator)s and email addresses. To learn more, see [uaxUrlEmail.](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-uaxUrlEmail-tokenizer-ref)

```c
#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, "sample_mflix");
    collection = mongoc_database_get_collection(database, "users");

    // Specify the command and the new index
    const char *cmd_str = BSON_STR({
        "createSearchIndexes" : "users",
        "indexes" : [ {
            "name" : "default",
            "definition" : {
              "mappings": {
                "dynamic": true,
                 "fields": {
                  "email": {
                    "type": "autocomplete",
                    "analyzer": "lucene.keyword",
                    "tokenization": "nGram",
                    "minGrams": 3,
                    "maxGrams": 15,
                    "foldDiacritics": false
                  }
                }
              }
            }
	    } ]
	});

    // 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 MongoDB 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;
}
```

### Try an Example for the `autocomplete` Type

The following index definition examples use collections in the [sample data](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets). After you [load the sample data](https://www.mongodb.com/docs/atlas/import/load-sample-data.md#std-label-load-sample-data), you can use these examples to index fields as the `autocomplete` type.

To learn how to set up and run the following example code, see [Define the Index for the token Type](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-define-index-token-admin-api).

#### Basic Example

##### Index specific field using static mappings as autocomplete type.

The following index definition example uses the `sample_mflix.movies` collection. The index definition indexes only the `title` field as the `autocomplete` type to support search-as-you-type queries against that field using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. The index definition also specifies the following:

- Use the [standard](https://www.mongodb.com/docs/search/indexes/analyzers/standard.md#std-label-ref-standard-analyzer) analyzer to divide text values into terms based on word boundaries.

- Use the `edgeGram` tokenization strategy to index characters starting at the left side of the words .

- Index a minimum of `3` characters per indexed sequence.

- Index a maximum of `5` characters per indexed sequence.

- Include diacritic marks in the index and query text.

- Use the `stableTfl` [similarity algorithm](https://www.mongodb.com/docs/search/query/score/get-details.md#std-label-fts-similarity-algorithms) to ensure consistent document scoring across all search nodes and replica set members.

```csharp
using MongoDB.Bson;
using MongoDB.Driver;

// connect to your Atlas deployment
var uri = "<connection-string>";

var client = new MongoClient(uri);

var db = client.GetDatabase("sample_mflix");
var collection = db.GetCollection<BsonDocument>("movies");

// define your MongoDB Search index
var index =  new CreateSearchIndexModel(
  "default", new BsonDocument
  {
    { "mappings", new BsonDocument
      {
        { "dynamic", false },
        { "fields", new BsonDocument
          {
            { "title", new BsonDocument
              {
                { "type", "autocomplete" },
                { "analyzer", "lucene.standard" },
                { "tokenization", "edgeGram" },
                { "minGrams", 3 },
                { "maxGrams", 5 },
                { "foldDiacritics", false },
                { "similarity", new BsonDocument { { "type", "stableTfl" } } }
              }
            }
          }
        }
      }
    }
  });

var result = collection.SearchIndexes.CreateOne(index);
Console.WriteLine($"New index name: {result}");
```

#### Multiple Types Example

##### Index specific field as autocomplete and string types.

The following index definition example uses the `sample_mflix.movies` collection to index a field as multiple types. The following index definition indexes the `title` field as the following types:

- `autocomplete` type to support autocompletion for queries using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator.

- `string` type to support text search using operators such [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref), [phrase](https://www.mongodb.com/docs/search/query/operators-collectors/phrase.md#std-label-phrase-ref), and so on.

```csharp
using MongoDB.Bson;  
using MongoDB.Driver;  
  
// connect to your Atlas deployment  
var uri = "<connection-string>";  
  
var client = new MongoClient(uri);  
  
var db = client.GetDatabase("sample_mflix");  
var collection = db.GetCollection<BsonDocument>("movies");  
  
// define your MongoDB Search index  
var index = new CreateSearchIndexModel(  
  "default", new BsonDocument  
  {  
    { "mappings", new BsonDocument  
      {  
        { "dynamic", false },  
        { "fields", new BsonDocument  
          {  
            { "title", new BsonArray  
              {  
                new BsonDocument  
                {  
                  { "type", "autocomplete" },  
                  { "analyzer", "lucene.standard" },  
                  { "tokenization", "edgeGram" },  
                  { "minGrams", 2 },  
                  { "maxGrams", 15 },  
                  { "foldDiacritics", false }  
                },  
                new BsonDocument  
                {  
                  { "type", "string" }  
                }  
              }  
            }  
          }  
        }  
      }  
    }  
  });  
  
var result = collection.SearchIndexes.CreateOne(index);  
Console.WriteLine($"New index name: {result}");  

```

#### Email Example

##### Index email address as the autocomplete type.

The following index definition example uses the [sample\_mflix.users](https://www.mongodb.com/docs/manual/sample-data/sample-mflix.md#std-label-sample-mflix) collection. The index definition example indexes only the `email` field as the `autocomplete` type to support search-as-you-type queries against that field using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. The index definition specifies the following:

- Use the [keyword](https://www.mongodb.com/docs/search/indexes/analyzers/keyword.md#std-label-ref-keyword-analyzer) analyzer to accept a string or array of strings as a parameter and index them as a single term (token).

- Use the [nGram](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-nGram-tokenizer-ref) tokenizer to tokenize text into chunks, or "n-grams", of given sizes.

- Index a minimum of `3` characters per indexed sequence.

- Index a maximum of `15` characters per indexed sequence.

- Include diacritic marks in the index and query text.

You can also use the `uaxUrlEmail` tokenizer to tokenizes URL (Uniform Resource Locator)s and email addresses. To learn more, see [uaxUrlEmail.](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-uaxUrlEmail-tokenizer-ref)

```csharp
using MongoDB.Bson;
using MongoDB.Driver;

// connect to your Atlas deployment
var uri = "<connection-string>";

var client = new MongoClient(uri);

var db = client.GetDatabase("sample_mflix");
var collection = db.GetCollection<BsonDocument>("users");

// define your MongoDB Search index
var index =  new CreateSearchIndexModel(
  "default", new BsonDocument
  {
    { "mappings", new BsonDocument
      {
        { "dynamic", true },
        { "fields", new BsonDocument
          {
            { "email", new BsonDocument
              {
                { "type", "autocomplete" },
                { "analyzer", "lucene.keyword" },
                { "tokenization", "nGram" },
                { "minGrams", 3 },
                { "maxGrams", 15 },
                { "foldDiacritics", false }
              }
            }
          }
        }
      }
    }
  });

var result = collection.SearchIndexes.CreateOne(index);
Console.WriteLine($"New index name: {result}");
```

### Try an Example for the `autocomplete` Type

The following index definition examples use collections in the [sample data](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets). After you [load the sample data](https://www.mongodb.com/docs/atlas/import/load-sample-data.md#std-label-load-sample-data), you can use these examples to index fields as the `autocomplete` type.

To learn how to set up and run the following example code, see [Define the Index for the token Type](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-define-index-token-admin-api).

#### Basic Example

##### Index specific field using static mappings as autocomplete type.

The following index definition example uses the `sample_mflix.movies` collection. The index definition indexes only the `title` field as the `autocomplete` type to support search-as-you-type queries against that field using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. The index definition also specifies the following:

- Use the [standard](https://www.mongodb.com/docs/search/indexes/analyzers/standard.md#std-label-ref-standard-analyzer) analyzer to divide text values into terms based on word boundaries.

- Use the `edgeGram` tokenization strategy to index characters starting at the left side of the words .

- Index a minimum of `3` characters per indexed sequence.

- Index a maximum of `5` characters per indexed sequence.

- Include diacritic marks in the index and query text.

- Use the `stableTfl` [similarity algorithm](https://www.mongodb.com/docs/search/query/score/get-details.md#std-label-fts-similarity-algorithms) to ensure consistent document scoring across all search nodes and replica set members.

```cpp
#include <iostream>

#include <bsoncxx/builder/basic/document.hpp>
#include <bsoncxx/json.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/uri.hpp>

using bsoncxx::builder::basic::kvp;
using bsoncxx::builder::basic::make_document;

int main(){

    mongocxx::instance instance;
    mongocxx::uri uri("<connection-string>");
    mongocxx::client client(uri);

    auto db = client["sample_mflix"];
    auto collection = db["movies"];

    // instantiate a ``mongocxx::search_index_view`` on your collection
    auto siv = collection.search_indexes();

    {
        auto name = "default";
        auto definition = make_document(
            kvp("mappings", make_document(
                kvp("dynamic", false),
                kvp("fields", make_document(
                    kvp("title", make_document(
                        kvp("type", "autocomplete"),
                        kvp("analyzer", "lucene.standard"),
                        kvp("tokenization", "edgeGram"),
                        kvp("minGrams", 3),
                        kvp("maxGrams", 5),
                        kvp("foldDiacritics", false),
                        kvp("similarity", make_document(kvp("type", "stableTfl")))
                    ))
                ))
            ))
        );

        auto model = mongocxx::search_index_model(name, definition.view());

        // Create the search index
        auto result = siv.create_one(model);
        std::cout << "New index name: " << result << std::endl;
    }
}

```

#### Dynamic Index Example

##### Dynamically index string fields as the autocomplete type.

The following index definition for the `sample_mflix.movies` collection in the [sample dataset](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets) indexes all string fields at the root-level in the documents in the collection as the `autocomplete` type with default settings. It also excludes string fields like `poster`, `languages`, `rated`, `lastupdated`, `fullplot`, and `awards` from being indexed.

```cpp
#include <iostream>

#include <bsoncxx/builder/basic/document.hpp>
#include <bsoncxx/json.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/uri.hpp>

using bsoncxx::builder::basic::kvp;
using bsoncxx::builder::basic::make_document;

int main(){

    mongocxx::instance instance;
    mongocxx::uri uri("<connection-string>");
    mongocxx::client client(uri);

    auto db = client["sample_mflix"];
    auto collection = db["movies"];

    // instantiate a ``mongocxx::search_index_view`` on your collection
    auto siv = collection.search_indexes();

    {
        auto name = "default";
        auto definition = make_document(
            kvp("mappings", make_document(
                kvp("dynamic", make_document(
                    kvp("typeSet", "moviesStringIndex")
                )),
                kvp("fields", make_document(
                    kvp("poster", bsoncxx::builder::basic::array{}),
                    kvp("languages", bsoncxx::builder::basic::array{}),
                    kvp("rated", bsoncxx::builder::basic::array{}),
                    kvp("lastupdated", bsoncxx::builder::basic::array{}),
                    kvp("fullplot", bsoncxx::builder::basic::array{}),
                    kvp("awards", bsoncxx::builder::basic::array{})
                ))
            )),
            kvp("typeSets", []{
                auto arr = bsoncxx::builder::basic::array{};
                arr.append(make_document(
                    kvp("name", "moviesStringIndex"),
                    kvp("types", []{
                        auto types_arr = bsoncxx::builder::basic::array{};
                        types_arr.append(make_document(
                            kvp("type", "autocomplete")
                        ));
                        return types_arr;
                    }())
                ));
                return arr;
            }())
        );

        auto model = mongocxx::search_index_model(name, definition.view());

        // Create the search index
        auto result = siv.create_one(model);
        std::cout << "New index name: " << result << std::endl;
    }
}

```

#### Multiple Types Example

##### Index specific field as autocomplete and string types.

The following index definition example uses the `sample_mflix.movies` collection to index a field as multiple types. The following index definition indexes the `title` field as the following types:

- `autocomplete` type to support autocompletion for queries using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator.

- `string` type to support text search using operators such [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref), [phrase](https://www.mongodb.com/docs/search/query/operators-collectors/phrase.md#std-label-phrase-ref), and so on.

```cpp
#include <iostream>

#include <bsoncxx/builder/basic/document.hpp>
#include <bsoncxx/json.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/uri.hpp>

using bsoncxx::builder::basic::kvp;
using bsoncxx::builder::basic::make_document;

int main(){

    mongocxx::instance instance;
    mongocxx::uri uri("<connection-string>");
    mongocxx::client client(uri);

    auto db = client["sample_mflix"];
    auto collection = db["movies"];

    // instantiate a ``mongocxx::search_index_view`` on your collection
    auto siv = collection.search_indexes();

    {
        auto name = "default";
        auto definition = make_document(
            kvp("mappings", make_document(
                kvp("dynamic", false),
                kvp("fields", make_document(
                    kvp("title", make_document(
                        kvp("type", "autocomplete"),
                        kvp("analyzer", "lucene.standard"),
                        kvp("tokenization", "edgeGram"),
                        kvp("minGrams", 2),
                        kvp("maxGrams", 15),
                        kvp("foldDiacritics", false)
                    )),
                    kvp("plot", make_document(
                        kvp("type", "string")
                    ))
                ))
            ))
        );

        auto model = mongocxx::search_index_model(name, definition.view());

        // Create the search index
        auto result = siv.create_one(model);
        std::cout << "New index name: " << result << std::endl;
    }
}

```

#### Email Example

##### Index email address as the autocomplete type.

The following index definition example uses the [sample\_mflix.users](https://www.mongodb.com/docs/manual/sample-data/sample-mflix.md#std-label-sample-mflix) collection. The index definition example indexes only the `email` field as the `autocomplete` type to support search-as-you-type queries against that field using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. The index definition specifies the following:

- Use the [keyword](https://www.mongodb.com/docs/search/indexes/analyzers/keyword.md#std-label-ref-keyword-analyzer) analyzer to accept a string or array of strings as a parameter and index them as a single term (token).

- Use the [nGram](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-nGram-tokenizer-ref) tokenizer to tokenize text into chunks, or "n-grams", of given sizes.

- Index a minimum of `3` characters per indexed sequence.

- Index a maximum of `15` characters per indexed sequence.

- Include diacritic marks in the index and query text.

You can also use the `uaxUrlEmail` tokenizer to tokenizes URL (Uniform Resource Locator)s and email addresses. To learn more, see [uaxUrlEmail.](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-uaxUrlEmail-tokenizer-ref)

```cpp
#include <iostream>

#include <bsoncxx/builder/basic/document.hpp>
#include <bsoncxx/json.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/uri.hpp>
#include <mongocxx/search_index.hpp>

using bsoncxx::builder::basic::kvp;
using bsoncxx::builder::basic::make_document;

int main(){

    mongocxx::instance instance;
    mongocxx::uri uri("<connection-string>");
    mongocxx::client client(uri);

    auto db = client["sample_mflix"];
    auto collection = db["users"];

    // instantiate a ``mongocxx::search_index_view`` on your collection
    auto siv = collection.search_indexes();

    {
        auto name = "default";
        auto definition = make_document(
            kvp("mappings", make_document(
                kvp("dynamic", true),
                kvp("fields", make_document(
                    kvp("email", make_document(
                        kvp("type", "autocomplete"),
                        kvp("analyzer", "lucene.keyword"),
                        kvp("tokenization", "nGram"),
                        kvp("minGrams", 3),
                        kvp("maxGrams", 15),
                        kvp("foldDiacritics", false)
                    ))
                ))
            ))
        );

        auto model = mongocxx::search_index_model(name, definition.view());
        // Create the search index
        auto result = siv.create_one(model);
        if (result) {
            std::cout << "New index name: " << *result << std::endl;
        } else {
            std::cout << "Failed to create search index." << std::endl;
        }
    }
}
}

```

### Try an Example for the `autocomplete` Type

The following index definition examples use collections in the [sample data](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets). After you [load the sample data](https://www.mongodb.com/docs/atlas/import/load-sample-data.md#std-label-load-sample-data), you can use these examples to index fields as the `autocomplete` type.

To learn how to set up and run the following example code, see [Define the Index for the token Type](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-define-index-token-admin-api).

#### Basic Example

##### Index specific field using static mappings as autocomplete type.

The following index definition example uses the `sample_mflix.movies` collection. The index definition indexes only the `title` field as the `autocomplete` type to support search-as-you-type queries against that field using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. The index definition also specifies the following:

- Use the [standard](https://www.mongodb.com/docs/search/indexes/analyzers/standard.md#std-label-ref-standard-analyzer) analyzer to divide text values into terms based on word boundaries.

- Use the `edgeGram` tokenization strategy to index characters starting at the left side of the words .

- Index a minimum of `3` characters per indexed sequence.

- Index a maximum of `5` characters per indexed sequence.

- Include diacritic marks in the index and query text.

- Use the `stableTfl` [similarity algorithm](https://www.mongodb.com/docs/search/query/score/get-details.md#std-label-fts-similarity-algorithms) to ensure consistent document scoring across all search nodes and replica set members.

```go
package main

import (
	"context"
	"fmt"
	"log"

	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
)

func main() {
	ctx := context.Background()
	uri := "<connection-string>"
	client, err := mongo.Connect(options.Client().
		ApplyURI(uri))
	if err != nil {
		panic(err)
	}

	defer func() {
		if err := client.Disconnect(context.TODO()); err != nil {
			panic(err)
		}
	}()

	coll := client.Database("sample_mflix").Collection("movies")
	const indexName = "default"
	opts := options.SearchIndexes().SetName(indexName).SetType("search")

	// Define the MongoDB Search index for the autocomplete field type
	searchIndexModel := mongo.SearchIndexModel{
		Definition: bson.D{
			{"mappings", bson.D{
				{"dynamic", false},
				{"fields", bson.D{
					{"title", bson.D{
						{"type", "autocomplete"},
						{"analyzer", "lucene.standard"},
						{"tokenization", "edgeGram"},
						{"minGrams", 3},
						{"maxGrams", 5},
						{"foldDiacritics", false},
						{"similarity", bson.D{{"type", "stableTfl"}}},
					}},
				}},
			}},
		},
		Options: opts,
	}

	// Create the index
	searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, searchIndexModel)
	if err != nil {
		log.Fatalf("Failed to create the Atlas Search index: %v", err)
	}

	fmt.Println("Name of index created: " + searchIndexName)
}

```

#### Dynamic Index Example

##### Dynamically index string fields as the autocomplete type.

The following index definition for the `sample_mflix.movies` collection in the [sample dataset](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets) indexes all string fields at the root-level in the documents in the collection as the `autocomplete` type with default settings. It also excludes string fields like `poster`, `languages`, `rated`, `lastupdated`, `fullplot`, and `awards` from being indexed.

```go
package main

import (
	"context"
	"fmt"
	"log"

	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
)

func main() {
	ctx := context.Background()
	uri := "<connection-string>"
	client, err := mongo.Connect(options.Client().
		ApplyURI(uri))
	if err != nil {
		panic(err)
	}

	defer func() {
		if err := client.Disconnect(context.TODO()); err != nil {
			panic(err)
		}
	}()

	coll := client.Database("sample_mflix").Collection("movies")
	const indexName = "default"
	opts := options.SearchIndexes().SetName(indexName).SetType("search")

	// Define the Atlas Search index for the autocomplete field type
	searchIndexModel := mongo.SearchIndexModel{
		Definition: bson.D{
			{"mappings", bson.D{
				{"dynamic", bson.D{
					{"typeSet", "moviesStringIndex"},
				}},
				{"fields", bson.D{
					{"poster", bson.A{}},
					{"languages", bson.A{}},
					{"rated", bson.A{}},
					{"lastupdated", bson.A{}},
					{"fullplot", bson.A{}},
					{"awards", bson.A{}},
				}},
			}},
			{"typeSets", bson.A{
				bson.D{
					{"name", "moviesStringIndex"},
					{"types", bson.A{
						bson.D{
							{"type", "autocomplete"},
						},
					}},
				},
			}},
		},
		Options: opts,
	}

	// Create the index
	searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, searchIndexModel)
	if err != nil {
		log.Fatalf("Failed to create the Atlas Search index: %v", err)
	}

	fmt.Println("Name of index created: " + searchIndexName)
}
```

#### Multiple Types Example

##### Index specific field as autocomplete and string types.

The following index definition example uses the `sample_mflix.movies` collection to index a field as multiple types. The following index definition indexes the `title` field as the following types:

- `autocomplete` type to support autocompletion for queries using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator.

- `string` type to support text search using operators such [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref), [phrase](https://www.mongodb.com/docs/search/query/operators-collectors/phrase.md#std-label-phrase-ref), and so on.

```go
package main

import (
	"context"
	"fmt"
	"log"

	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
)

func main() {
	ctx := context.Background()
	uri := "<connection-string>"
	client, err := mongo.Connect(options.Client().
		ApplyURI(uri))
	if err != nil {
		panic(err)
	}

	defer func() {
		if err := client.Disconnect(context.TODO()); err != nil {
			panic(err)
		}
	}()

	coll := client.Database("sample_mflix").Collection("movies")
	const indexName = "default"
	opts := options.SearchIndexes().SetName(indexName).SetType("search")

	// Define the MongoDB Search index for the autocomplete field
	searchIndexModel := mongo.SearchIndexModel{
		Definition: bson.D{
			{"mappings", bson.D{
				{"dynamic", false},
				{"fields", bson.D{
					{"title", bson.A{
						bson.D{
							{"type", "autocomplete"},
							{"analyzer", "lucene.standard"},
							{"tokenization", "edgeGram"},
							{"minGrams", 2},
							{"maxGrams", 15},
							{"foldDiacritics", false},
						},
						bson.D{{"type", "string"}},
					}},
				}},
			}},
		},
		Options: opts,
	}

	// Create the index
	searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, searchIndexModel)
	if err != nil {
		log.Fatalf("Failed to create the Atlas Search index: %v", err)
	}

	fmt.Println("Name of index created: " + searchIndexName)
}

```

#### Email Example

##### Index email address as the autocomplete type.

The following index definition example uses the [sample\_mflix.users](https://www.mongodb.com/docs/manual/sample-data/sample-mflix.md#std-label-sample-mflix) collection. The index definition example indexes only the `email` field as the `autocomplete` type to support search-as-you-type queries against that field using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. The index definition specifies the following:

- Use the [keyword](https://www.mongodb.com/docs/search/indexes/analyzers/keyword.md#std-label-ref-keyword-analyzer) analyzer to accept a string or array of strings as a parameter and index them as a single term (token).

- Use the [nGram](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-nGram-tokenizer-ref) tokenizer to tokenize text into chunks, or "n-grams", of given sizes.

- Index a minimum of `3` characters per indexed sequence.

- Index a maximum of `15` characters per indexed sequence.

- Include diacritic marks in the index and query text.

You can also use the `uaxUrlEmail` tokenizer to tokenizes URL (Uniform Resource Locator)s and email addresses. To learn more, see [uaxUrlEmail.](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-uaxUrlEmail-tokenizer-ref)

```go
package main

import (
	"context"
	"fmt"
	"log"

	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
)

func main() {
	ctx := context.Background()
	uri := "<connection-string>"
	client, err := mongo.Connect(options.Client().
		ApplyURI(uri))
	if err != nil {
		panic(err)
	}

	defer func() {
		if err := client.Disconnect(context.TODO()); err != nil {
			panic(err)
		}
	}()

	coll := client.Database("sample_mflix").Collection("users")
	const indexName = "default"
	opts := options.SearchIndexes().SetName(indexName).SetType("search")

	// Define the MongoDB Search index for the autocomplete field type
	searchIndexModel := mongo.SearchIndexModel{
		Definition: bson.D{
			{"mappings", bson.D{
				{"dynamic", true},
				{"fields", bson.D{
					{"email", bson.D{
						{"type", "autocomplete"},
						{"analyzer", "lucene.keyword"},
						{"tokenization", "edgeGram"},
						{"minGrams", 3},
						{"maxGrams", 15},
						{"foldDiacritics", false},
					}},
				}},
			}},
		},
		Options: opts,
	}

	// Create the index
	searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, searchIndexModel)
	if err != nil {
		log.Fatalf("Failed to create the Atlas Search index: %v", err)
	}

	fmt.Println("Name of index created: " + searchIndexName)
}

```

### Try an Example for the `autocomplete` Type

The following index definition examples use collections in the [sample data](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets). After you [load the sample data](https://www.mongodb.com/docs/atlas/import/load-sample-data.md#std-label-load-sample-data), you can use these examples to index fields as the `autocomplete` type.

To learn how to set up and run the following example code, see [Define the Index for the token Type](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-define-index-token-admin-api).

#### Basic Example

##### Index specific field using static mappings as autocomplete type.

The following index definition example uses the `sample_mflix.movies` collection. The index definition indexes only the `title` field as the `autocomplete` type to support search-as-you-type queries against that field using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. The index definition also specifies the following:

- Use the [standard](https://www.mongodb.com/docs/search/indexes/analyzers/standard.md#std-label-ref-standard-analyzer) analyzer to divide text values into terms based on word boundaries.

- Use the `edgeGram` tokenization strategy to index characters starting at the left side of the words .

- Index a minimum of `3` characters per indexed sequence.

- Index a maximum of `5` characters per indexed sequence.

- Include diacritic marks in the index and query text.

- Use the `stableTfl` [similarity algorithm](https://www.mongodb.com/docs/search/query/score/get-details.md#std-label-fts-similarity-algorithms) to ensure consistent document scoring across all search nodes and replica set members.

```java
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("sample_mflix");
            MongoCollection<Document> collection = database.getCollection("movies");
            String indexName = "default";

            Document searchIdx = new Document("mappings",
                    new Document("dynamic", false)
                        .append("fields", new Document("title", 
                                              new Document("type", "autocomplete")
                                                  .append("analyzer", "lucene.standard")
                                                  .append("tokenization", "edgeGram")
                                                  .append("minGrams", 3)
                                                  .append("maxGrams", 5)
                                                  .append("foldDiacritics", false)
                                                  .append("similarity", new Document("type", "stableTfl"))
                                                  )));

            collection.createSearchIndex(indexName, searchIdx);
            System.out.println("New index name: " + indexName);
        } catch (Exception e) {
            System.err.println("Error creating Atlas Search index: " + e.getMessage());
        }
    }
}
```

#### Multiple Types Example

##### Index specific field as autocomplete and string types.

The following index definition example uses the `sample_mflix.movies` collection to index a field as multiple types. The following index definition indexes the `title` field as the following types:

- `autocomplete` type to support autocompletion for queries using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator.

- `string` type to support text search using operators such [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref), [phrase](https://www.mongodb.com/docs/search/query/operators-collectors/phrase.md#std-label-phrase-ref), and so on.

```java
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("sample_mflix");
            MongoCollection<Document> collection = database.getCollection("movies");
            String indexName = "default";

            Document searchIdx = new Document("mappings",
                    new Document("dynamic", false)
                        .append("fields", new Document("title", 
                            java.util.Arrays.asList(
                                new Document("type", "autocomplete")
                                    .append("analyzer", "lucene.standard")
                                    .append("tokenization", "edgeGram")
                                    .append("minGrams", 2)
                                    .append("maxGrams", 15)
                                    .append("foldDiacritics", false),
                                new Document("type", "string")
                            )
                        ))
            );

            collection.createSearchIndex(indexName, searchIdx);
            System.out.println("New index name: " + indexName);
        } catch (Exception e) {
            System.err.println("Error creating Atlas Search index: " + e.getMessage());
        }
    }
}
```

#### Email Example

##### Index email address as the autocomplete type.

The following index definition example uses the [sample\_mflix.users](https://www.mongodb.com/docs/manual/sample-data/sample-mflix.md#std-label-sample-mflix) collection. The index definition example indexes only the `email` field as the `autocomplete` type to support search-as-you-type queries against that field using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. The index definition specifies the following:

- Use the [keyword](https://www.mongodb.com/docs/search/indexes/analyzers/keyword.md#std-label-ref-keyword-analyzer) analyzer to accept a string or array of strings as a parameter and index them as a single term (token).

- Use the [nGram](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-nGram-tokenizer-ref) tokenizer to tokenize text into chunks, or "n-grams", of given sizes.

- Index a minimum of `3` characters per indexed sequence.

- Index a maximum of `15` characters per indexed sequence.

- Include diacritic marks in the index and query text.

You can also use the `uaxUrlEmail` tokenizer to tokenizes URL (Uniform Resource Locator)s and email addresses. To learn more, see [uaxUrlEmail.](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-uaxUrlEmail-tokenizer-ref)

```java
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("sample_mflix");
            MongoCollection<Document> collection = database.getCollection("users");
            String indexName = "default";

            Document searchIdx = new Document("mappings",
                    new Document("dynamic", true)
                        .append("fields", new Document("email", 
                                              new Document("type", "autocomplete")
                                                  .append("analyzer", "lucene.keyword")
                                                  .append("tokenization", "nGram")
                                                  .append("minGrams", 3)
                                                  .append("maxGrams", 15)
                                                  .append("foldDiacritics", false)
                                                  )));

            collection.createSearchIndex(indexName, searchIdx);
            System.out.println("New index name: " + indexName);
        } catch (Exception e) {
            System.err.println("Error creating Atlas Search index: " + e.getMessage());
        }
    }
}
```

### Try an Example for the `autocomplete` Type

The following index definition examples use collections in the [sample data](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets). After you [load the sample data](https://www.mongodb.com/docs/atlas/import/load-sample-data.md#std-label-load-sample-data), you can use these examples to index fields as the `autocomplete` type.

To learn how to set up and run the following example code, see [Define the Index for the token Type](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-define-index-token-admin-api).

#### Basic Example

##### Index specific field using static mappings as autocomplete type.

The following index definition example uses the `sample_mflix.movies` collection. The index definition indexes only the `title` field as the `autocomplete` type to support search-as-you-type queries against that field using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. The index definition also specifies the following:

- Use the [standard](https://www.mongodb.com/docs/search/indexes/analyzers/standard.md#std-label-ref-standard-analyzer) analyzer to divide text values into terms based on word boundaries.

- Use the `edgeGram` tokenization strategy to index characters starting at the left side of the words .

- Index a minimum of `3` characters per indexed sequence.

- Index a maximum of `5` characters per indexed sequence.

- Include diacritic marks in the index and query text.

- Use the `stableTfl` [similarity algorithm](https://www.mongodb.com/docs/search/query/score/get-details.md#std-label-fts-similarity-algorithms) to ensure consistent document scoring across all search nodes and replica set members.

```javascript
const { MongoClient } = require("mongodb");

// connect to your Atlas deployment
const uri =  "<connection-string>";

const client = new MongoClient(uri);

async function run() {
  try {

    // set namespace
    const database = client.db("sample_mflix");
    const collection = database.collection("movies");

    // define your MongoDB Search index
    const index = {
      name: "default",
      definition: {
        /* search index definition fields */
        "mappings": {
          "dynamic": false,
          "fields": {
            "title": {
              "type": "autocomplete",
              "analyzer": "lucene.standard",
              "tokenization": "edgeGram",
              "minGrams": 3,
              "maxGrams": 5,
              "foldDiacritics": false,
              "similarity": { "type": "stableTfl" }
            }
          }
        }
      }
    }

    // run the helper method
    const result = await collection.createSearchIndex(index);
    console.log("New index name: " + result);
  } finally {
    await client.close();
  }
}

run().catch(console.dir);
```

#### Dynamic Index Example

##### Dynamically index string fields as the autocomplete type.

The following index definition for the `sample_mflix.movies` collection in the [sample dataset](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets) indexes all string fields at the root-level in the documents in the collection as the `autocomplete` type with default settings. It also excludes string fields like `poster`, `languages`, `rated`, `lastupdated`, `fullplot`, and `awards` from being indexed.

```javascript
const { MongoClient } = require("mongodb");

// connect to your Atlas deployment
const uri =  "<connection-string>";

const client = new MongoClient(uri);

async function run() {
  try {

    // set namespace
    const database = client.db("sample_mflix");
    const collection = database.collection("movies");

    // define your Atlas Search index
    const index = {
      name: "default",
      definition: {
        "mappings": {
          "dynamic": {
            "typeSet": "moviesStringIndex"
          },
          "fields": {
            "poster": [],
            "languages": [],
            "rated": [],
            "lastupdated": [],
            "fullplot": [],
            "awards": []
          }
        },
        "typeSets": [
          {
            "name": "moviesStringIndex",
            "types": [
              {
                "type": "autocomplete"
              }
            ]
          }
        ]
      }
    }

    // run the helper method
    const result = await collection.createSearchIndex(index);
    console.log("New index name: " + result);
  } finally {
    await client.close();
  }
}

run().catch(console.dir);
```

#### Multiple Types Example

##### Index specific field as autocomplete and string types.

The following index definition example uses the `sample_mflix.movies` collection to index a field as multiple types. The following index definition indexes the `title` field as the following types:

- `autocomplete` type to support autocompletion for queries using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator.

- `string` type to support text search using operators such [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref), [phrase](https://www.mongodb.com/docs/search/query/operators-collectors/phrase.md#std-label-phrase-ref), and so on.

```javascript
const { MongoClient } = require("mongodb");

// connect to your Atlas deployment
const uri =  "<connection-string>";

const client = new MongoClient(uri);

async function run() {
  try {

    // set namespace
    const database = client.db("sample_mflix");
    const collection = database.collection("movies");

    // define your MongoDB Search index
    const index = {
      name: "default",
      definition: {
        /* search index definition fields */
        "mappings": {
          "dynamic": false,
          "fields": {
            "title": [{
              "type": "autocomplete",
              "analyzer": "lucene.standard",
              "tokenization": "edgeGram",
              "minGrams": 2,
              "maxGrams": 15,
              "foldDiacritics": false
            },
            {
              "type": "string",
            }]
          }
        }
      }
    }

    // run the helper method
    const result = await collection.createSearchIndex(index);
    console.log("New index name: " + result);
  } finally {
    await client.close();
  }
}

run().catch(console.dir);
```

#### Email Example

##### Index email address as the autocomplete type.

The following index definition example uses the [sample\_mflix.users](https://www.mongodb.com/docs/manual/sample-data/sample-mflix.md#std-label-sample-mflix) collection. The index definition example indexes only the `email` field as the `autocomplete` type to support search-as-you-type queries against that field using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. The index definition specifies the following:

- Use the [keyword](https://www.mongodb.com/docs/search/indexes/analyzers/keyword.md#std-label-ref-keyword-analyzer) analyzer to accept a string or array of strings as a parameter and index them as a single term (token).

- Use the [nGram](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-nGram-tokenizer-ref) tokenizer to tokenize text into chunks, or "n-grams", of given sizes.

- Index a minimum of `3` characters per indexed sequence.

- Index a maximum of `15` characters per indexed sequence.

- Include diacritic marks in the index and query text.

You can also use the `uaxUrlEmail` tokenizer to tokenizes URL (Uniform Resource Locator)s and email addresses. To learn more, see [uaxUrlEmail.](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-uaxUrlEmail-tokenizer-ref)

```javascript
const { MongoClient } = require("mongodb");

// connect to your Atlas deployment
const uri =  "<connection-string>";

const client = new MongoClient(uri);

async function run() {
  try {

    // set namespace
    const database = client.db("sample_mflix");
    const collection = database.collection("users");

    // define your MongoDB Search index
    const index = {
      name: "default",
      definition: {
        /* search index definition fields */
        "mappings": {
          "dynamic": true,
          "fields": {
            "email": {
              "type": "autocomplete",
              "analyzer": "lucene.keyword",
              "tokenization": "nGram",
              "minGrams": 2,
              "maxGrams": 15,
              "foldDiacritics": false
            }
          }
        }
      }
    }

    // run the helper method
    const result = await collection.createSearchIndex(index);
    console.log("New index name: " + result);
  } finally {
    await client.close();
  }
}

run().catch(console.dir);
```

### Try an Example for the `autocomplete` Type

The following index definition examples use collections in the [sample data](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets). After you [load the sample data](https://www.mongodb.com/docs/atlas/import/load-sample-data.md#std-label-load-sample-data), you can use these examples to index fields as the `autocomplete` type.

To learn how to set up and run the following example code, see [Define the Index for the token Type](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-define-index-token-admin-api).

#### Basic Example

##### Index specific field using static mappings as autocomplete type.

The following index definition example uses the `sample_mflix.movies` collection. The index definition indexes only the `title` field as the `autocomplete` type to support search-as-you-type queries against that field using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. The index definition also specifies the following:

- Use the [standard](https://www.mongodb.com/docs/search/indexes/analyzers/standard.md#std-label-ref-standard-analyzer) analyzer to divide text values into terms based on word boundaries.

- Use the `edgeGram` tokenization strategy to index characters starting at the left side of the words .

- Index a minimum of `3` characters per indexed sequence.

- Index a maximum of `5` characters per indexed sequence.

- Include diacritic marks in the index and query text.

- Use the `stableTfl` [similarity algorithm](https://www.mongodb.com/docs/search/query/score/get-details.md#std-label-fts-similarity-algorithms) to ensure consistent document scoring across all search nodes and replica set members.

```python
from pymongo import MongoClient
from pymongo.operations import SearchIndexModel

# connect to your Atlas deployment
uri = "<connection-string>"
client = MongoClient(uri)

# set namespace
database = client["sample_mflix"]
collection = database["movies"]

# define your MongoDB Search index
search_index_model = SearchIndexModel(
    definition={
        "mappings": {
            "dynamic": False,
            "fields": {
                "title":{
                   "type": "autocomplete",
                   "analyzer": "lucene.standard",
                   "tokenization": "edgeGram",
                   "minGrams": 3,
                   "maxGrams": 5,
                   "foldDiacritics": False,
                   "similarity": { "type": "stableTfl" }                
                }
            }
        },
    },
    name="default",
)

# create the index
result = collection.create_search_index(model=search_index_model)
print(f"New index name: {result}")

```

#### Dynamic Index Example

##### Dynamically index string fields as the autocomplete type.

The following index definition for the `sample_mflix.movies` collection in the [sample dataset](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets) indexes all string fields at the root-level in the documents in the collection as the `autocomplete` type with default settings. It also excludes string fields like `poster`, `languages`, `rated`, `lastupdated`, `fullplot`, and `awards` from being indexed.

```python
from pymongo import MongoClient
from pymongo.operations import SearchIndexModel

# connect to your Atlas deployment
uri = "<connection-string>"
client = MongoClient(uri)

# set namespace
database = client["sample_mflix"]
collection = database["movies"]

# define your Atlas Search index
search_index_model = SearchIndexModel(
    definition={
      "mappings": {
        "dynamic": {
          "typeSet": "moviesStringIndex"
        },
        "fields": {
          "poster": [],
          "languages": [],
          "rated": [],
          "lastupdated": [],
          "fullplot": [],
          "awards": []
        }
      },
      "typeSets": [
        {
          "name": "moviesStringIndex",
          "types": [
            {
              "type": "autocomplete"
            }
          ]
        }
      ]
    },
    name="default",
)

# create the index
result = collection.create_search_index(model=search_index_model)
print(f"New index name: {result}")

```

#### Multiple Types Example

##### Index specific field as autocomplete and string types.

The following index definition example uses the `sample_mflix.movies` collection to index a field as multiple types. The following index definition indexes the `title` field as the following types:

- `autocomplete` type to support autocompletion for queries using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator.

- `string` type to support text search using operators such [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref), [phrase](https://www.mongodb.com/docs/search/query/operators-collectors/phrase.md#std-label-phrase-ref), and so on.

```python
from pymongo import MongoClient
from pymongo.operations import SearchIndexModel

# connect to your Atlas deployment
uri = "<connection-string>"
client = MongoClient(uri)

# set namespace
database = client["sample_mflix"]
collection = database["movies"]

# define your MongoDB Search index
search_index_model = SearchIndexModel(
    definition={
        "mappings": {
            "dynamic": False,
            "fields": {
                "title":[{
                   "type": "autocomplete",
                   "analyzer": "lucene.standard",
                   "tokenization": "edgeGram",
                   "minGrams": 2,
                   "maxGrams": 15,
                   "foldDiacritics": False
                },
                {
                    "type": "string"
                }]
            }
        },
    },
    name="default",
)

# create the index
result = collection.create_search_index(model=search_index_model)
print(f"New index name: {result}")

```

#### Email Example

##### Index email address as the autocomplete type.

The following index definition example uses the [sample\_mflix.users](https://www.mongodb.com/docs/manual/sample-data/sample-mflix.md#std-label-sample-mflix) collection. The index definition example indexes only the `email` field as the `autocomplete` type to support search-as-you-type queries against that field using the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator. The index definition specifies the following:

- Use the [keyword](https://www.mongodb.com/docs/search/indexes/analyzers/keyword.md#std-label-ref-keyword-analyzer) analyzer to accept a string or array of strings as a parameter and index them as a single term (token).

- Use the [nGram](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-nGram-tokenizer-ref) tokenizer to tokenize text into chunks, or "n-grams", of given sizes.

- Index a minimum of `3` characters per indexed sequence.

- Index a maximum of `15` characters per indexed sequence.

- Include diacritic marks in the index and query text.

You can also use the `uaxUrlEmail` tokenizer to tokenizes URL (Uniform Resource Locator)s and email addresses. To learn more, see [uaxUrlEmail.](https://www.mongodb.com/docs/search/indexes/analyzers/tokenizers.md#std-label-uaxUrlEmail-tokenizer-ref)

```python
from pymongo import MongoClient
from pymongo.operations import SearchIndexModel

# connect to your Atlas deployment
uri = "<connection-string>"
client = MongoClient(uri)

# set namespace
database = client["sample_mflix"]
collection = database["users"]

# define your MongoDB Search index
search_index_model = SearchIndexModel(
    definition={
        "mappings": {
            "dynamic": True,
            "fields": {
                "email":{
                   "type": "autocomplete",
                   "analyzer": "lucene.keyword",
                   "tokenization": "nGram",
                   "minGrams": 3,
                   "maxGrams": 15,
                   "foldDiacritics": False
                }
            }
        },
    },
    name="default",
)

# create the index
result = collection.create_search_index(model=search_index_model)
print(f"New index name: {result}")

```

## Considerations

### `maxGrams` Configuration

The `maxGrams` option specifies the maximum length of substrings generated during indexing. Increasing `maxGrams` improves matching for longer queries by generating more substrings. Setting it beyond what you need can increase index size and affect indexing performance.

Consider the following best practices when you configure `maxGrams`:

- **Default to no more than 15.** Set `maxGrams` to no more than `15` when possible to avoid unnecessary index growth.

- **Align with query length.** Set `maxGrams` based on the typical length of user queries, rather than indexing for worst-case scenarios.

- **Avoid over-indexing.** If your queries are shorter than your current `maxGrams` value, you may be indexing more data than necessary.

- **Use an alternative for longer queries.** If your queries regularly exceed 15 characters, use a [custom analyzer](https://www.mongodb.com/docs/search/performance/query-performance.md#std-label-regex-to-search) for `prefix`, `contains`, and `suffix` patterns.

### Tokenization Performance

Indexing a field for autocomplete with an `edgeGram`, `rightEdgeGram`, or `nGram` tokenization strategy requires more computation and index storage than indexing a string field.

For the specified tokenization strategy, MongoDB Search concatenates sequential tokens before emitting them ("shingling"). MongoDB Search emits tokens between `minGrams` and `maxGrams` characters in length:

- Keeps tokens less than `minGrams`.

- Joins tokens greater than `minGrams` but less than `maxGrams` to the next tokens to create tokens up to the specified maximum number of characters in length.

### Dynamic Mappings

The default field types that MongoDB Search uses for [dynamic mappings](https://www.mongodb.com/docs/search/indexes/define-field-mappings.md#std-label-fts-dynamic-mappings) do not include the `autocomplete` type. Using the `autocomplete` type in dynamic mappings can increase index size and resource usage, and produce unexpected scoring results. Use `autocomplete` in static mappings.

However, if you need to include `autocomplete` in dynamic mappings, you can add it to a custom `typeSet` definition. To learn more about `autocomplete` and custom `typeSet` configurations, see [Index Size and Configuration.](https://www.mongodb.com/docs/search/performance/index-performance.md#std-label-index-perf)

### Index Build Time

If your dataset has many documents or a wide data range, building this index for the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator can take some time. To reduce the impact on other indexes and queries while the new index builds, create a separate index with only the `autocomplete` type.

For index performance considerations, see [Index Performance Considerations.](https://www.mongodb.com/docs/search/performance/index-performance.md#std-label-index-size-and-config)

## Learn More

To learn more about the `autocomplete` operator and see example queries, see [autocomplete.](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref)

For examples that demonstrate how to run *case-insensitive*, *prefix*, *starts with*, and *contains* queries using regex expressions, see [Use `$search` Instead of `$text` or `$regex`.](https://www.mongodb.com/docs/search/performance/query-performance.md#std-label-regex-to-search)
