Docs Menu

Docs HomeDevelop ApplicationsPython DriversPyMongo

Text Indexes

On this page

  • Overview
  • Sample Data
  • Text Index on a Single Field
  • Text Index on Multiple Fields

Text indexes support text search queries on string content. These indexes can include any field whose value is a string or an array of string elements. MongoDB supports text search for various languages. You can specify the default language as an option when creating the index.

Tip

MongoDB offers an improved full-text search solution, Atlas Search. To learn more about Atlas Search indexes and how to use them, see the Atlas Search Indexes guide.

The examples in this guide use the sample_mflix.movies collection from the Atlas sample datasets. To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the Get Started with PyMongo.

The following example creates a text index on the plot field:

movies.create_index(
[( "plot", "text" )]
)

The following is an example of a query that uses the index created in the preceding code example:

query = { "$text": { "$search": "a time-traveling DeLorean" } }
cursor = movies.find(query)

A collection can contain only one text index. If you want to create a text index for multiple text fields, create a compound index. A text search runs on all the text fields within the compound index.

The following example creates a compound text index for the title and genre fields:

result = myColl.create_index(
[("title", "text"), ("genre", "text")],
default_language="english",
weights={ "title": 10, "genre": 3 }
)

For more information, see Compound Text Index Restrictions and Text Indexes in the MongoDB Server manual.

← Atlas Search Indexes