Create a search index
Create a search index¶
Before you can run full-text search queries, create a search index on the collection.
Use the db.collection.createSearchIndex() method to create a search index.
Follow these steps:
-
Create a search index.
db.<collection>.createSearchIndex( "<name>", "<type>", { <definition> } )createSearchIndex()accepts the following parameters:Field Type Required Description namestringNo Name of the index. Defaults to defaultif omitted.typestringNo Index type. Specify searchorvectorSearch. The default issearch.definitiondocumentYes Defines the index configuration. Example: Create a search index
db.docs.createSearchIndex({ name: "search_idx", definition: { mappings: { dynamic: true } } })Output
search_idx -
Verify that the index is ready.
db.docs.getSearchIndexes()Index creation runs asynchronously. Wait until the index status is
READYbefore running search queries.Output
[ { name: "search_idx", status: "READY", queryable: true, ... } ] -
Run a full-text search.
Search the collection
db.docs.aggregate([ { $search: { index: "search_idx", text: { query: "future", path: "text" } } } ])Output
[ { text: "Vector search is the future" } ]