Skip to content

Commit 70c1e7d

Browse files
committed
DOCSP-48887: docs+ atlas search tutorial
1 parent 0d860e5 commit 70c1e7d

File tree

4 files changed

+334
-1
lines changed

4 files changed

+334
-1
lines changed
451 KB
Loading

source/interact-data.txt

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ Interact with Data
2121
Search Text </interact-data/text-search>
2222
Transactions and Sessions </interact-data/transaction>
2323
Nested Attributes </interact-data/nested-attributes>
24+
Tutorial: Atlas Search </interact-data/atlas-search-tutorial>
2425

2526
In this section, you can learn how to use {+odm+} to interact with your
2627
MongoDB data.
@@ -44,4 +45,8 @@ MongoDB data.
4445
transactions to make atomic data changes.
4546

4647
- :ref:`mongoid-data-nested-attr`: Learn how to modify documents and
47-
their associations in a single operation.
48+
their associations in a single operation.
49+
50+
To learn how to integrate the Atlas Search feature into an application,
51+
see the :ref:`Integrate Atlas Search into a {+ror+} App Tutorial
52+
<mongoid-atlas-search-rails-tutorial>`.
Lines changed: 325 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,325 @@
1+
.. _mongoid-atlas-search-rails-tutorial:
2+
3+
=========================================================
4+
Tutorial: Integrate Atlas Search into a {+ror+} App
5+
=========================================================
6+
7+
.. facet::
8+
:name: genre
9+
:values: reference
10+
11+
.. meta::
12+
:keywords: code example, transform, pipeline
13+
14+
.. contents:: On this page
15+
:local:
16+
:backlinks: none
17+
:depth: 2
18+
:class: singlecol
19+
20+
Overview
21+
--------
22+
23+
In this tutorial, you can learn how to integrate :atlas:`Atlas Search
24+
</atlas-search/>`, an advanced text search feature, into a {+ror+} app.
25+
26+
After you complete this tutorial, you have a fully functional search
27+
feature embedded in your Rails app, allowing you to efficiently find
28+
information.
29+
30+
Prerequisites
31+
-------------
32+
33+
The tutorial builds on a template app that you can download from the
34+
:github:`mongodb-atlas-with-ruby-on-rails-example GitHub repository
35+
<mongodb-developer/mongodb-atlas-with-ruby-on-rails-example>` by running
36+
the following command:
37+
38+
.. code-block:: bash
39+
40+
git clone https://github.com/mongodb-developer/mongodb-atlas-with-ruby-on-rails-example.git
41+
42+
Before you can start this tutorial, you also need to set up the
43+
following components:
44+
45+
1. Create a MongoDB Atlas cluster. To learn how to create a cluster, see
46+
the :ref:`mongoid-quick-start-rails-create-deployment` step of the
47+
Rails Quick Start guide.
48+
49+
#. Update the app's ``config/mongoid.yml`` file with your own connection
50+
string and set the default database to ``inspiration``, as shown the
51+
following example configuration:
52+
53+
.. code-block:: yml
54+
55+
development:
56+
clients:
57+
default:
58+
uri: mongodb+srv://<username>:<password>@<host>/inspiration
59+
60+
#. Start the Rails app by running the ``rails server`` command, then
61+
complete the :guilabel:`New Idea` entry form to insert some sample
62+
data into the ``inspiration.ideas`` collection. You can also
63+
64+
#. Create an Atlas Search index in Compass or the Atlas UI called
65+
``inspiration`` with dynamic mappings. To learn more about creating
66+
Atlas Search indexes, see the :atlas:`Manage Atlas Search Indexes
67+
</atlas-search/manage-indexes/>` guide in the Atlas documentation.
68+
69+
Steps
70+
-----
71+
72+
.. procedure::
73+
:style: connected
74+
75+
.. step:: Configure the Atlas Search feature in your {+odm+} model.
76+
77+
First, update the ``Idea`` model to handle queries to our
78+
database by defining the ``search`` method in the model. The
79+
method ``self.search(query)`` defines a class method called
80+
``search`` that takes a single argument ``query`` and returns the
81+
results.
82+
83+
Open the ``app/models/idea.rb`` file and replace its contents with
84+
the following code:
85+
86+
.. code-block:: ruby
87+
88+
class Idea
89+
include Mongoid::Document
90+
include Mongoid::Timestamps
91+
field :name, type: String
92+
field :description, type: String
93+
field :picture, type: String
94+
95+
def self.search(query)
96+
aggregation_pipeline = [
97+
{
98+
"$search": {
99+
"index": "inspiration",
100+
"text": {
101+
"query": query,
102+
"path": ['name', 'description']
103+
},
104+
"sort": {
105+
"score": { "$meta": "searchScore" }
106+
}
107+
}
108+
},
109+
{
110+
"$limit": 20
111+
}
112+
]
113+
results = collection.aggregate(aggregation_pipeline)
114+
115+
search_results = results.to_a
116+
search_results.map do |result|
117+
Idea.new(
118+
id: result["_id"],
119+
name: result["name"],
120+
description: result["description"],
121+
picture: result["picture"]
122+
)
123+
end
124+
end
125+
end
126+
127+
When you call ``idea.search("<example query>")``, {+odm+} performs the
128+
following actions:
129+
130+
1. Performs a full-text search by using the ``inspiration`` index.
131+
#. Runs the query across the ``name`` and ``description`` fields.
132+
#. Sorts the results by their relevance scores.
133+
#. Limits the number of results to ``20`` to improve performance
134+
for queries on large collections.
135+
136+
The ``search_results`` variable then converts the raw results from
137+
MongoDB into an array of hashes that can be mapped to ``Idea``
138+
model instances and rendered in your view files.
139+
140+
.. step:: Add a Search action in your controller.
141+
142+
Now that you defined the Search query functionality in the
143+
``Idea`` model, you must add an action to initiate queries.
144+
145+
Open the ``app/controllers/ideas_controller.rb`` file and add the
146+
following action to your ``IdeasController`` before the ``private``
147+
declaration:
148+
149+
.. code-block:: ruby
150+
151+
def search
152+
@query = params[:query]
153+
@ideas = @query.present? ? Idea.search(@query) : Idea.all
154+
render :display_results
155+
end
156+
157+
Now, when you submit a Search query, {+odm+} runs the
158+
``search`` method in the ``Idea`` model. The
159+
results are then rendered in your view files.
160+
161+
.. step:: Generate the Search controller.
162+
163+
In this step, you create a ``SearchesController`` to handle Atlas Search
164+
requests and display results.
165+
166+
Run the following command to generate the ``SearchesController``
167+
and the ``display_results`` view file:
168+
169+
.. code-block:: bash
170+
171+
rails generate controller Searches display_results
172+
173+
Open the newly created ``searches_controller.rb`` file and replace
174+
the contents with the following code:
175+
176+
.. code-block:: ruby
177+
178+
class SearchesController < ApplicationController
179+
def display_results
180+
query = params[:query]
181+
@results = Idea.search(query)
182+
end
183+
end
184+
185+
Open the ``app/views/searches/display_results.html.erb`` file and
186+
replace the contents with the following code, which renders the search results:
187+
188+
.. code-block:: html
189+
190+
<div class="search-results">
191+
<h1>Search Results for "<%= params[:query] %>"</h1>
192+
193+
<% if @results.empty? %>
194+
<p>No ideas found.</p>
195+
<% else %>
196+
<div class="idea-container">
197+
<% @results.each do |result| %>
198+
<div class="idea">
199+
<h2><%= result.name %></h2>
200+
<p><%= truncate(result.description, length: 150) %></p>
201+
<img src="<%= result.picture %>" alt="<%= result.name %>" />
202+
203+
<p><%= link_to "View", idea_path(result.id) %></p>
204+
</div>
205+
<% end %>
206+
</div>
207+
<% end %>
208+
</div>
209+
210+
<%= link_to "Back", ideas_path %>
211+
212+
Then, add the following code to your ``app/assets/stylesheets/application.css`` file to include
213+
basic styling for the search results:
214+
215+
.. code-block:: css
216+
217+
.search-results {
218+
width: 80%;
219+
margin: 0 auto;
220+
}
221+
.idea-container {
222+
display: flex;
223+
flex-direction: column;
224+
}
225+
.idea {
226+
padding: 20px;
227+
border-bottom: 2px solid #ccc;
228+
border-radius: 10px 10px 0 0;
229+
margin-bottom: 10px;
230+
}
231+
.idea h2 {
232+
margin: 0;
233+
}
234+
.idea p {
235+
margin: 0;
236+
}
237+
.idea img {
238+
width: 100px;
239+
height: auto;
240+
display: block;
241+
}
242+
ul {
243+
list-style-type: none;
244+
padding: 0;
245+
}
246+
247+
.. step:: Create the Search form.
248+
249+
To enable Search queries directly in your application, open the
250+
``app/views/ideas/index.html.erb`` file and add the following
251+
code:
252+
253+
.. code-block:: html
254+
255+
<%= form_tag(search_results_path, method: :get, class: "form-inline") do %>
256+
<div class="input-group mb-3">
257+
<%= text_field_tag :query, params[:query], placeholder: "Search Ideas...", class: "form-control" %>
258+
<div class="input-group-append">
259+
<%= submit_tag "Search", class: "btn btn-primary text-white" %>
260+
</div>
261+
</div>
262+
<% end %>
263+
264+
Add the following styling for the search bar to your ``application.css`` file:
265+
266+
.. code-block:: css
267+
268+
.input-group {
269+
width: 100%;
270+
}
271+
.btn-primary {
272+
background-color: #007bff;
273+
border-color: #007bff;
274+
color: white;
275+
}
276+
.btn-primary:hover {
277+
background-color: #0056b3;
278+
border-color: #004085;
279+
}
280+
281+
.. step:: Update app routes for Search queries.
282+
283+
Replace the existing route in the ``config/routes.rb`` file with
284+
following route to display search results:
285+
286+
.. code-block:: ruby
287+
288+
Rails.application.routes.draw do
289+
root to: "ideas#index"
290+
resources :ideas
291+
get '/search_results', to: 'searches#display_results', as: "search_results"
292+
end
293+
294+
.. step:: Start your application and run Search queries.
295+
296+
Run the following command to start your application:
297+
298+
.. code-block:: bash
299+
300+
rails server
301+
302+
Navigate to http://127.0.0.1:3000/ to view the landing page.
303+
304+
To submit a query, add a term or phrase in the search bar then
305+
click the :guilabel:`Search` button.
306+
307+
.. figure:: /includes/figures/atlas-search-tutorial-render.png
308+
:alt: The rendered Search results
309+
310+
The search results depend on the documents in your
311+
database. As the complexity of your data increases, you might need
312+
to perform more advanced queries to narrow results. To learn more
313+
about different Atlas Search queries and view examples, see the
314+
:atlas:`Query Reference </atlas-search/query-ref/>` in the Atlas
315+
documentation.
316+
317+
Conclusion
318+
----------
319+
320+
In this tutorial, you learned how to integrate the Atlas Search feature
321+
into a Rails application. This integration enhances usability and
322+
functionality while improving user engagement.
323+
324+
To learn more about performing queries in {+odm+}, see the
325+
:ref:`mongoid-interact-data` guides.

source/quick-start-rails/next-steps.txt

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,3 +28,6 @@ Learn more about {+odm+} features from the following sections:
2828

2929
- :ref:`mongoid-interact-data`: Learn how to interact with your MongoDB
3030
data by using {+odm+} models.
31+
32+
- :ref:`mongoid-atlas-search-rails-tutorial`: Learn how to integrate the
33+
Atlas Search feature into your application.

0 commit comments

Comments
 (0)