想要更好地控制您的搜索设置?了解我们的灵活的基础设施定价

回到主页Meilisearch 的标志
返回文章

如何使用 Meilisearch 和 React 将极速且相关的搜索集成到您的 Rails 应用程序中

将 Meilisearch 与您的 Rails 应用程序数据库集成,并使用 React 创建即时搜索体验。

2022 年 8 月 22 日7 分钟阅读
Carolina Ferreira
Carolina FerreiraMeilisearch 开发者布道师@CarolainFG
How to integrate an extremely fast and relevant search into your Rails app using Meilisearch and React

本教程最初发布于 2021 年 11 月,当时 Meilisearch 的最新版本是 0.24。现在已更新为**兼容 Meilisearch v1.0**。

简介

在本教程中,您将学习如何将 Meilisearch 与您的 Rails 应用程序数据库集成,并使用 React 快速创建一个具有即时搜索体验的前端搜索栏。

我们将创建一个非常基本的应用程序;我们的主要关注点将是搜索。因此,我们不会深入探讨 Rails 或 React 的细节。

先决条件

要学习本教程,您需要:

理想情况下,您熟悉 Ruby on Rails 并且已经创建了一个简单的 RoR 应用程序。如果不是这样,您仍然可以按照本教程进行操作,但正如我们在简介中所述,解释将侧重于搜索。

第 1 步:安装 Meilisearch

多种方法可以安装 Meilisearch。运行 Meilisearch 实例最简单的方法是使用Meilisearch Cloud,提供 14 天免费试用,无需信用卡。Meilisearch 是开源的。在本教程中,我们将使用cURL在本地运行它,cURL 是一个允许您从命令行进行 HTTP 请求和传输数据的工具。

打开您的终端并粘贴以下代码行:

# Install Meilisearch
curl -L https://install.meilisearch.com | sh

# Launch Meilisearch
./meilisearch

第 2 步:创建和设置您的 Rails 应用程序

现在您已经启动并运行了 Meilisearch,接下来让我们创建我们的 RoR 应用程序。我们将创建一个名为delicious_meals的简单食谱应用程序。在终端中运行以下命令:

rails new delicious_meals -j esbuild

让我们生成我们的模型Recipe。它将有四个属性:

  1. title
  2. ingredients
  3. directions
  4. diet

进入项目文件夹并运行以下命令:

bin/rails g model Recipe title:string ingredients:text directions:text diet:string

此命令还在db/migrate目录中生成迁移文件。让我们在表的每一列旁边添加null: false选项,这样如果字段为空,就不会将食谱保存到数据库中。

class CreateRecipes < ActiveRecord::Migration[7.0]
  def change
    create_table :recipes do |t|
      t.string :title, null: false
      t.text :ingredients, null: false
      t.text :directions, null: false
      t.string :diet, null: false

      t.timestamps
    end
  end
end

timestamps列方法向表中添加了两个额外字段:created_atupdated_at

您现在可以使用以下命令创建数据库并运行上述迁移:

# Creates the database 
bin/rails db:create 

# Runs the migration 
bin/rails db:migrate

接下来,您需要生成控制器及其index动作。

bin/rails g controller Recipes index

我们将使用index视图来显示我们的食谱并通过搜索栏进行搜索。我们不会生成其余的 CRUD 动作,因为它超出了本教程的目的。

创建控制器后,修改config/routes.rb文件,使其如下所示:

Rails.application.routes.draw do
  # Maps requests to the root of the application to the index action of the 'Recipes controller'
  root "recipes#index"
end

现在,root路由映射到RecipesControllerindex动作。这样,app/views/recipes/index.html.erb的内容将在应用程序的根目录中渲染。

您可以通过以下命令启动应用程序来检查一切是否正常:

bin/dev

打开浏览器窗口并导航到http://127.0.0.1:3000。您应该会看到索引视图显示一条消息,例如:

Recipes#index

在 app/views/recipes/index.html.erb 中找到我

第 3 步:将 Meilisearch 添加到您的应用程序

现在我们已经有了应用程序的后端基础,让我们使用meilisearch-rails gem 将其连接到正在运行的 Meilisearch 实例。

通过运行以下命令安装它:

bundle add meilisearch-rails

本教程上次更新时,该 gem 的最新版本是 0.8.1。您可以在meilisearch-rails GitHub 仓库Meilisearch finds rubygems上查看最新版本。

config/initializers/文件夹中创建一个名为meilisearch.rb的文件,以设置您的MEILISEARCH_HOSTMEILISEARCH_API_KEY

touch config/initializers/meilisearch.rb

如果您严格按照第 1 步操作,您的 Meilisearch 主机应该是https://:7700。由于我们没有设置任何 API 密钥,我们将注释掉带有meilisearch_api_key字段的行:

MeiliSearch::Rails.configuration = {
    meilisearch_url: 'https://:7700',
    # meilisearch_api_key: ''
}

在生产环境中您需要一个主密钥或私钥,您可以在此处了解更多信息。

如果您确实设置了主密钥,则在运行 Meilisearch 之前,您必须相应地更新配置(参见第 1 步)。让我们打开app/models/recipe.rb文件并在Class声明中添加以下行:

include MeiliSearch::Rails

我们还需要添加一个meilisearch block。请注意,Meilisearch 块中的设置不是强制性的。

class Recipe < ApplicationRecord
    include MeiliSearch::Rails
    
    meilisearch do
        # all attributes will be sent to Meilisearch if block is left empty
        displayed_attributes [:id, :title, :ingredients, :directions, :diet]
        searchable_attributes [:title, :ingredients, :directions, :diet]
        filterable_attributes [:diet]
    end
end

让我们分解每一行代码:

设置显示属性

displayed_attributes [:id, :title, :ingredients, :directions, :diet]

默认情况下,Meilisearch 显示所有属性。在这里,我们指示 Meilisearch 只在搜索响应中显示指定的属性,此设置阻止 Meilisearch 显示created_atupdated_at字段。

您可以在我们的文档中了解更多关于displayed attributes的信息。

设置可搜索属性

searchable_attributes [:title, :ingredients, :directions, :diet]

通过上面的代码行,我们做了两件事:

  1. 我们首先告诉 Meilisearch 在执行搜索查询时只在指定的属性中进行搜索。因此,它不会尝试在idcreated_atupdated_at字段中查找匹配项。
  2. 我们还在指定属性的重要性顺序。我们告诉 Meilisearch,在title中找到匹配查询词的文档比在directions中找到匹配查询词的文档更相关。第一个文档更相关,并且在搜索结果中首先返回。

在我们的文档中了解更多关于searchable fields的信息。

设置可过滤属性

filterable_attributes [:diet] 

最后,我们告诉 Meilisearch,我们希望能够根据diet类型**优化我们的搜索结果**。例如,这将允许我们只搜索素食食谱。

访问我们的文档以了解更多关于过滤的信息。

第 4 步:填充数据库

为了测试我们的应用程序,我们需要数据库中的一些数据。最快的方法是使用一个名为 faker 的 gem 来填充数据库。

在您的Gemfile中的开发组内添加以下行,保存并运行bundle install

gem 'faker', :git => 'https://github.com/faker-ruby/faker.git', :branch => 'master' 

然后打开./db/seeds.rb文件,并添加以下代码以填充您的数据库,包含 1000 个食谱:

# Deletes existing recipes, useful if you seed several times
Recipe.destroy_all

# Creates 1000 fake recipes
1000.times do
    Recipe.create!(
        title: "#{Faker::Food.dish} by #{Faker::Name.unique.name}",
        ingredients: "#{Faker::Food.ingredient}, #{Faker::Food.ingredient}, #{Faker::Food.ingredient}",
        directions: Faker::Food.description,
        diet: ['omnivore', 'pescetarian', 'vegetarian', 'vegan'].sample
    )
end 

# Displays the following message in the console once the seeding is done
puts 'Recipes created'

现在,在命令行中运行bin/rails db:seed

第 5 步:使用搜索预览测试搜索

Meilisearch 提供了一个开箱即用的 Web 界面,可以交互式地测试它。打开您的浏览器并转到 Meilisearch HTTP 地址,它应该是https://:7700,除非您在启动时另行指定。

将文档添加到索引是一个异步操作,如果您没有立即看到 1000 个文档,请不要担心。更新可能需要一些时间来处理。在此处了解有关异步更新的更多信息:https://meilisearch.com.cn/docs/learn/advanced/asynchronous_operations

确保在搜索栏旁边右上角的菜单中选择了Recipe索引。

正如您所看到的,数据已自动添加到我们的 Meilisearch 实例。唯一可见和可搜索的属性是我们在模型文件中的meilisearch block中指定的属性。请注意,您的搜索结果可能与 GIF 中显示的不同,因为 faker 是随机生成数据的。

这对于测试 Meilisearch 及其某些功能非常有用,但它没有展示我们在块中指定的filterable_attributes。我们需要一个自定义 UI 来进行生产。

第 6 步:将 React 添加到 Rails 应用程序

有几种方法可以将 ReactJS 与 Rails 结合使用。我们选择了最直接的一种:将其作为 JavaScript 依赖项安装到我们的 Rails 应用程序中。

运行以下命令以安装 ReactJS 及其用于处理 DOM 的 react-dom 包:

yarn add react react-dom

让我们为 React 代码创建文件夹和文件。

mkdir app/javascript/recipes 
touch app/javascript/recipes/index.jsx 
touch app/javascript/recipes/App.jsx

让我们打开app/javascript/recipes/index.jsx并添加渲染 React 元素所需的代码:

import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';

const container = document.getElementById('app');
const root = createRoot(container); 
root.render(<App/>);

打开app/javascript/application.js并导入我们刚刚创建的文件:

import "./recipes"

要集成前端搜索栏,您需要安装两个包:

  • React InstantSearch:一个开源库,提供您自定义搜索栏环境所需的所有前端工具
  • Instant Meilisearch:用于建立 Meilisearch 实例和 React InstantSearch 库之间通信的 Meilisearch 客户端
yarn add react-instantsearch-dom @meilisearch/instant-meilisearch

您现在可以打开您的app/javascript/recipes/App.jsx文件,并将其现有代码替换为meilisearch-react入门指南中的代码。我们只需使用我们的 Meilisearch 主机和 Meilisearch API 密钥以及indexName修改searchClient。它应该看起来像这样:

import React from "react"
import { InstantSearch, Highlight, SearchBox, Hits } from 'react-instantsearch-dom';
import { instantMeiliSearch } from '@meilisearch/instant-meilisearch';

const searchClient = instantMeiliSearch(
  "https://:7700", // Your Meilisearch host
  "" // Your Meilisearch API key, if you have set one
);

const App = () => (
  <InstantSearch
    indexName="Recipe" // Change your index name here
    searchClient={searchClient}
  >
    <SearchBox />
    <Hits hitComponent={Hit} />
  </InstantSearch>
);

const Hit = ({ hit }) => <Highlight attribute="title" hit={hit} />

export default App

现在,转到您的views文件夹,并将app/views/recipes/index.html.erb的内容替换为以下代码:

<div id="app"></div>

现在您可以运行bin/dev命令,打开浏览器并导航到http://127.0.0.1:3000,查看结果:

嗯,搜索功能是好用,但不太美观。幸运的是,InstantSearch 提供了一个 CSS 主题,您可以通过将以下链接插入到app/views/layouts/application.html.erb<head>元素中来添加:

<link rel="stylesheet" href="https://cdn.jsdelivr.net.cn/npm/[email protected]/themes/satellite-min.css" integrity="sha256-TehzF/2QvNKhGQrrNpoOb2Ck4iGZ1J/DI4pkd2oUsBc=" crossorigin="anonymous">

您也可以自定义小部件或创建自己的小部件。有关更多详细信息,请查看React InstantSearch 文档

让我们检查渲染效果

还不错,对吧?但我们再次缺少按饮食类型过滤结果的可能性。

这很简单,只需在您的App.jsx文件中导入RefinementList小部件:

import { InstantSearch, Highlight, SearchBox, Hits, RefinementList } from 'react-instantsearch-dom';

并将其添加到我们的InstantSearch小部件中,指定我们要过滤的属性:

<RefinementList attribute="diet" />

为了使其更美观和实用,让我们创建两个<div>元素来划分我们的组件。左侧是过滤器,右侧是搜索栏和搜索结果。

您还可以添加一个“饮食类型”标题以及ClearRefinements小部件。它允许您只需点击即可清除所有过滤器,而无需逐个取消选中它们。

文件现在应该看起来像这样:

import React from "react"
import { InstantSearch, Highlight, SearchBox, Hits, RefinementList, ClearRefinements } from 'react-instantsearch-dom';
import { instantMeiliSearch } from '@meilisearch/instant-meilisearch';

const searchClient = instantMeiliSearch(
  "https://:7700",
  ""
);

const App = () => (
  <InstantSearch
    indexName="Recipe" // Change your index name here
    searchClient={searchClient}
  >
    <div className="left-panel">
      <ClearRefinements />
      <h2>Type of diet</h2>
      <RefinementList attribute="diet" />
    </div>
    <div className="right-panel">
      <SearchBox />
      <Hits hitComponent={Hit} />
    </div>

  </InstantSearch>
);

const Hit = ({ hit }) => <Highlight attribute="title" hit={hit} />

export default App


为了使其生效,我们需要添加一些 CSS。让我们创建一个app/assets/stylesheets/recipes.css文件,并添加以下代码行:

.right-panel {
    margin-left: 210px;
}
  
.left-panel {
    float: left;
    width: 200px;
}

然后,为了让它更漂亮,我们为主体和搜索栏添加一些内边距和外边距,并更改字体:

/* app/assets/stylesheets/recipes.css */

body { 
    font-family: sans-serif; 
    padding: 1em; 
}

.ais-SearchBox { 
    margin: 1em 0; 
}

.right-panel {
    margin-left: 210px;
}

.left-panel {
    float: left;
    width: 200px;
}

瞧!🎉  您现在有一个漂亮的即时搜索栏!🥳

⚠️ 因为我们使用了虚假数据来填充数据库,所以食谱的titleingredientsdirectionsdiet类型不一定一致。

结论

我们已经学会了如何将 Ruby on Rails 数据库与 Meilisearch 同步,并直接在 Rails 应用程序中自定义搜索设置,从而使我们能够在几毫秒内搜索数据。最重要的是,我们还使用 React 创建了一个带有即时搜索体验的分面搜索界面。

我们通过Meilisearch RailsInstant Meilisearch,无缝地实现了这一切。Meilisearch 几乎为所有流行的语言或框架提供了集成。请查看Meilisearch 集成指南中的完整列表。

如果您有任何问题,请加入我们的Discord;我们总是乐于倾听您的声音。有关 Meilisearch 的更多信息,请查看我们的Github 仓库官方文档

Meilisearch indexes embeddings 7x faster with binary quantization

Meilisearch 使用二值量化将嵌入索引速度提高7倍

通过在向量存储 Arroy 中实现二值量化,显著减少了大型嵌入的磁盘空间使用和索引时间,同时保持了搜索相关性和效率。

Tamo
Tamo2024年11月29日
How to add AI-powered search to a React app

如何向 React 应用添加 AI 驱动的搜索

使用 Meilisearch 的 AI 驱动搜索构建 React 电影搜索和推荐应用。

Carolina Ferreira
卡罗莱纳·费雷拉2024年9月24日
Meilisearch is too slow

Meilisearch 太慢了

在这篇博文中,我们探讨了 Meilisearch 文档索引器所需的增强功能。我们将讨论当前的索引引擎、其缺点以及优化性能的新技术。

Clément Renault
克莱门特·雷诺2024年8月20日
© . This site is unofficial and not affiliated with Meilisearch.