.. _text-search:
***********
Text Search
***********
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol
MongoDB provides :manual:`text indexes `
to support text search queries on string content. Text indexes
can include any field whose value is a string or an array of
string elements.
.. note::
MongoDB Atlas also provides
`Atlas Search `_
which is a more powerful and flexible text search solution.
The rest of this section discusses text indexes and not Atlas Search.
To perform text search with Mongoid, follow these steps:
1. Define a text index on a model.
2. Create the text index on the server.
3. Build a text search query.
Defining Text Search Index
--------------------------
Index definition through Mongoid is described in detail on the `indexes
`_ page. Text search indexes are described in detail
under `text indexes `_
in the MongoDB manual. Below is an example definition of a Band model with
a text index utilizing the description field:
.. code-block:: ruby
class Band
include Mongoid::Document
field :name, type: String
field :description, type: String
index description: 'text'
end
Note that the index type (``text``) must be given as a string, not as a symbol.
Creating Text Index
-------------------
To create the index, invoke the ``db:mongoid:create_indexes`` Rake task:
.. code-block:: ruby
bundle exec rake db:mongoid:create_indexes
Querying Using Text Index
-------------------------
To find bands whose description contains "ounces" or its variations, use the
`$text operator `_:
.. code-block:: ruby
Band.where('$text' => {'$search' => 'ounces'}).to_a
# => [#]
Note that the description contains the word "ounce" even though the search
query was "ounces".
Note also that when performing text search, the name of the field is not
explicitly specified - ``$text`` operator searches all fields indexed with
the text index.