Overview
在本教程中,您可以学习;了解如何将 MongoDB Search(一种高级全文搜索功能)集成到Ruby on Rails应用中。
完成本教程后,您的 Rails 应用程序中将嵌入一个功能齐全的搜索功能,使您能够高效地查找信息。
先决条件
本教程基于一个模板应用,您可以从 mongodb-atlas-with-ruby-on-rails-example GitHub 存储库 下载该应用,方法是运行以下命令:
git clone https://github.com/mongodb-developer/mongodb-atlas-with-ruby-on-rails-example.git
然后,执行以下设置操作:
创建 MongoDB Atlas 集群。要了解如何创建集群,请参阅 Rails 快速入门指南中的创建 MongoDB 部署 - Ruby on Rails 步骤。
更新应用的
config/mongoid.yml文件,使用您自己的连接字符串,并将默认数据库设置为inspiration,如下示例配置所示:development: clients: default: uri: mongodb+srv://<username>:<password>@<host>/inspiration 通过运行
rails server命令启动 Rails 应用程序,然后填写 New Idea 表单,将一些示例数据插入到inspiration.ideas集合。提示
样本数据
要实现本教程后面演示的搜索功能,请在
name或description字段中插入包含一些重叠术语的示例文档。在Compass或Atlas用户界面中使用动态(默认)映射创建名为 的MongoDB搜索索引。要学习;了解有关创建MongoDB搜索索引的更多信息,请参阅
inspiration索引指南的MongoDB搜索索引部分。
步骤
在 Mongoid 模型中配置MongoDB搜索功能。
首先,通过在模型中定义 search 方法更新Idea 模型,以处理对 ideas集合的MongoDB Search 查询。 self.search(query) 方法定义了一个名为 search 的类方法,该方法接受单个参数 query 并返回搜索结果。
打开 app/models/idea.rb 文件,并将其内容替换为以下代码:
class Idea include Mongoid::Document include Mongoid::Timestamps field :name, type: String field :description, type: String field :picture, type: String def self.search(query) aggregation_pipeline = [ { "$search": { "index": "inspiration", "text": { "query": query, "path": ['name', 'description'] }, "sort": { "score": { "$meta": "searchScore" } } } }, { "$limit": 20 } ] results = collection.aggregate(aggregation_pipeline) search_results = results.to_a search_results.map do |result| Idea.new( id: result["_id"], name: result["name"], description: result["description"], picture: result["picture"] ) end end end
当您调用 idea.search("<example query>") 时,Mongoid 执行以下操作:
使用
inspiration索引进行全文搜索。在
name和description字段中运行查询。按相关性分数对结果进行排序。
将结果数量限制为
20以提高对大型集合的查询性能。
然后,search_results 变量将 MongoDB 的原始结果转换为哈希数组,这些数组可以映射到 Idea 模型实例并在视图文件中呈现。
在控制器中添加搜索操作。
既然您在 Idea 模型中定义了搜索查询功能,您必须添加一个操作来启动查询。
打开 app/controllers/ideas_controller.rb 文件,将以下操作添加到 IdeasController 中的 private 声明之前:
def search @query = params[:query] @ideas = @query.present? ? Idea.search(@query) : Idea.all render :display_results end
现在,当您提交搜索查询时,Mongoid 会在 Idea 模型中运行 search 方法。然后,结果会在您的视图文件中呈现。
生成搜索控制器。
运行以下命令以生成 SearchesController 和 display_results 视图文件,分别处理 search 请求并显示结果:
rails generate controller Searches display_results
打开新创建的 searches_controller.rb 文件,并将内容替换为以下代码:
class SearchesController < ApplicationController def display_results query = params[:query] @results = Idea.search(query) end end
打开 app/views/searches/display_results.html.erb 文件,并将内容替换为以下代码,以显示搜索结果:
<div class="search-results"> <h1>Search Results for "<%= params[:query] %>"</h1> <% if @results.empty? %> <p>No ideas found.</p> <% else %> <div class="idea-container"> <% @results.each do |result| %> <div class="idea"> <h2><%= result.name %></h2> <p><%= truncate(result.description, length: 150) %></p> <img src="<%= result.picture %>" alt="<%= result.name %>" /> <p><%= link_to "View", idea_path(result.id) %></p> </div> <% end %> </div> <% end %> </div> <%= link_to "Back", ideas_path %>
然后,将以下代码添加到您的 app/assets/stylesheets/application.css 文件中,以包含搜索结果的基本样式:
.search-results { width: 80%; margin: 0 auto; } .idea-container { display: flex; flex-direction: column; } .idea { padding: 20px; border-bottom: 2px solid #ccc; border-radius: 10px 10px 0 0; margin-bottom: 10px; } .idea h2 { margin: 0; } .idea p { margin: 0; } .idea img { width: 100px; height: auto; display: block; } ul { list-style-type: none; padding: 0; }
创建搜索表单。
要在您的应用程序中直接启用搜索查询,请打开 app/views/ideas/index.html.erb 文件并添加以下代码:
<%= form_tag(search_results_path, method: :get, class: "form-inline") do %> <div class="input-group mb-3"> <%= text_field_tag :query, params[:query], placeholder: "Search Ideas...", class: "form-control" %> <div class="input-group-append"> <%= submit_tag "Search", class: "btn btn-primary text-white" %> </div> </div> <% end %>
将以下搜索栏样式添加到 application.css 文件中:
.input-group { width: 100%; } .btn-primary { background-color: #007bff; border-color: #007bff; color: white; } .btn-primary:hover { background-color: #0056b3; border-color: #004085; }
启动您的应用程序并运行搜索查询。
在您的项目目录中,运行以下命令以启动您的应用程序:
rails server
导航至 http://127.0.0.1:3000/ 以查看登录页面。
要提交查询,请在搜索栏中输入一个术语或短语,然后单击 Search 按钮。下图显示了术语 "outdoor" 的搜索结果:

搜索结果取决于数据库中的文档。随着数据复杂性的增加,您可能需要执行更高级的查询来缩小结果范围。要学习;了解有关不同MongoDB搜索查询和查看示例的更多信息,请参阅Atlas文档中的查询参考。
结论
在本教程中,您学习了如何将MongoDB搜索功能集成到 Rails应用程序中。这种集成增强了可用性和功能性,同时提高了用户互动。
要了解有关在 Mongoid 中执行查询的更多信息,请参阅与数据交互指南。