Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs 菜单
Docs 主页
/ / /
Mongoid
/

集成 Atlas Search

在本教程中,您可以学习;了解如何将 Atlas 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

然后,执行以下设置操作:

  1. 创建 MongoDB Atlas 集群。要了解如何创建集群,请参阅 Rails 快速入门指南中的创建 MongoDB 部署 - Ruby on Rails 步骤。

  2. 更新应用的 config/mongoid.yml 文件,使用您自己的连接字符串,并将默认数据库设置为 inspiration,如下示例配置所示:

    development:
    clients:
    default:
    uri: mongodb+srv://<username>:<password>@<host>/inspiration
  3. 通过运行 rails server 命令启动 Rails 应用程序,然后填写 New Idea 表单,将一些示例数据插入到 inspiration.ideas 集合。

    提示

    样本数据

    要实现本教程后面演示的搜索功能,请在 namedescription 字段中插入包含一些重叠术语的示例文档。

  4. 在 Compass 或 Atlas 用户界面中使用动态(默认)映射创建名为 inspiration 的 Atlas Search 索引。要了解有关创建 Atlas Search 索引的更多信息,请参阅索引指南的 Atlas Search 索引部分。

1

首先,在模型中定义 search 方法,更新 Idea 模型,处理对 ideas 集合的 Atlas 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 执行以下操作:

  1. 使用 inspiration 索引进行全文搜索。

  2. namedescription 字段中运行查询。

  3. 按相关性分数对结果进行排序。

  4. 将结果数量限制为 20 以提高对大型集合的查询性能。

然后,search_results 变量将 MongoDB 的原始结果转换为哈希数组,这些数组可以映射到 Idea 模型实例并在视图文件中呈现。

2

既然您在 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 方法。然后,结果会在您的视图文件中呈现。

3

运行以下命令以生成 SearchesControllerdisplay_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;
}
4

要在您的应用程序中直接启用搜索查询,请打开 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;
}
5

config/routes.rb 文件中的现有路由替换为以下路由以显示搜索结果:

Rails.application.routes.draw do
root to: "ideas#index"
resources :ideas
get '/search_results', to: 'searches#display_results', as: "search_results"
end
6

在您的项目目录中,运行以下命令以启动您的应用程序:

rails server

导航至 http://127.0.0.1:3000/ 以查看登录页面。

要提交查询,请在搜索栏中输入一个术语或短语,然后单击 Search 按钮。下图显示了术语 "outdoor" 的搜索结果:

已呈现的搜索结果

搜索结果取决于数据库中的文档。随着数据复杂性的增加,您可能需要执行更高级的查询来缩小结果范围。要了解有关不同 Atlas Search 查询的更多信息并查看示例,请参阅 Atlas 文档中的查询参考

在本教程中,您学习了如何将 Atlas Search 功能集成到 Rails 应用程序中。这种集成增强了可用性和功能,同时提高了用户交互。

要了解有关在 Mongoid 中执行查询的更多信息,请参阅与数据交互指南。

后退

嵌套属性

在此页面上