mongodb/mongoid

View on GitHub
docs/reference/text-search.txt

Summary

Maintainability
Test Coverage
.. _text-search:

***********
Text Search
***********

.. default-domain:: mongodb

.. contents:: On this page
   :local:
   :backlinks: none
   :depth: 2
   :class: singlecol


MongoDB provides :manual:`text indexes </core/index-text/>`
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 <https://docs.atlas.mongodb.com/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 :ref:`indexes
<indexes>` page. Text search indexes are described in detail
under `text indexes <https://mongodb.com/docs/manual/core/index-text/>`_
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 <https://mongodb.com/docs/manual/reference/operator/query/text/#op._S_text>`_:

.. code-block:: ruby

  Band.where('$text' => {'$search' => 'ounces'}).to_a
  # => [#<Band _id: 5d5341b3ce4ef35d5016746d, name: "foo", description: "ounce">]

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.