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

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

使用 React InstantSearch 实现推广搜索结果

了解如何使用 React InstantSearch Hooks 和 Meilisearch 显示推广结果。

2023年7月20日2分钟阅读
Laurent Cazanove
Laurent Cazanove开发者体验工程师@StriftCodes
Implementing promoted search results with React InstantSearch
分享文章

今天我们将学习如何通过将给定文档置顶于搜索结果的方式来推广结果。这可以在电子商务中用于增加特色产品的曝光度,或在应用内搜索中优先显示用户特定的内容。我们将使用 Node.js 和 React 来实现推广文档。

在 Meilisearch 引擎中需要推广文档吗?提供您的反馈

本教程将使用一个电影样本数据集。我们的目标是当输入“funny”、“children”或“fish”时,让“海底总动员”显示在结果顶部。

文件夹结构

在本指南中,我们将前端代码与用于配置 Meilisearch 的后端代码分开。

我们将使用以下文件夹结构来组织我们的项目

my-app/
├─ node_modules/
├─ data/ <-- Backend code goes there
│  ├─ setup.js
│  ├─ movies.json
│  ├─ promoted-movies.json
├─ src/ <-- React code will go there
│  ├─ App.jsx
│  ├─ main.js
│  ├─ ...
├─ package.json

首先,为我们的应用程序创建一个目录(例如 my-app)或使用现有目录。在我们的应用程序目录中,让我们为后端代码创建一个 data 文件夹。

下载 JSON 数据集并将其存储到新的 data 文件夹中。在此处下载数据集:

电影(“下载”)

推广电影(“下载”)

好的。开始编码!

Meilisearch 设置

首先,我们需要启动一个 Meilisearch 实例。您可以按照本地安装指南中的说明进行操作,或在Meilisearch Cloud上创建帐户。我们将编写一个设置脚本来配置我们的 Meilisearch 实例并填充数据。

此设置脚本使用 JavaScript SDK,但您可以使用Meilisearch SDKs中的任何一个。

在本教程中,我们使用 Node 18。让我们安装 JavaScript SDK:

npm install meilisearch

然后,让我们创建一个 setup.js 文件:

// data/setup.js

import { MeiliSearch } from 'meilisearch'

// Load the datasets
import movies from './movies.json' assert { type: 'json' }
import promotedMovies from './promoted_movies.json' assert { type: 'json' }

// Load credentials from environment
const credentials = {
  host: 'your Meilisearch host',
  apiKey: 'your Meilisearch Admin API key' 
}

// Configuration
const INDEX_NAME = 'movies'
const PROMOTED_INDEX_NAME = `promoted-${INDEX_NAME}`

const searchableAttributes = ['title', 'overview', 'genre', 'release_date']
const displayedAttributes = ['id', 'title', 'overview', 'genre', 'poster', 'release_date']

const setup = async () => {
	console.log('🚀 Seeding your Meilisearch instance')
	
	const client = new MeiliSearch(credentials)
	
	// Adding searchable attributes to movies index
client.index(INDEX_NAME).updateSearchableAttributes(searchableAttributes)
	// In the promoted movies index, only `keywords` is searchable
client.index(PROMOTED_INDEX_NAME).updateSearchableAttributes(['keywords'])
	
	// Both indexes have the same visible attributes
	// `keywords` is hidden in the promoted movies index
	client
		.index(INDEX_NAME)
		.updateDisplayedAttributes(displayedAttributes)
	client
		.index(PROMOTED_INDEX_NAME)
		.updateDisplayedAttributes(displayedAttributes)
	
	// Adding documents
	await client.index(INDEX_NAME).addDocuments(movies)
	await client.index(PROMOTED_INDEX_NAME).addDocuments(promotedMovies)
	
	// Wait for tasks completion
	await watchTasks(client, INDEX_NAME)
	await watchTasks(client, PROMOTED_INDEX_NAME)
}

// Helper to watch tasks
const watchTasks = (client, uid) {
	console.log(`Watching tasks on index ${uid}`)
	const tasks = await client.index(uid).getTasks()
	console.log(`${uid} index: waiting for tasks`)
	await client.index(uid).waitForTasks(tasks)
	console.log(`${uid} index: tasks finished`)
}

await setup()

此脚本创建了我们的两个索引。让我们回顾一下它的作用:

  • 它为 moviespromoted-movies 都设置了相同的显示属性
  • 它设置了可搜索属性;在 promoted-movies 索引中,只有 keywords 是可搜索的。
  • 它向我们的 Meilisearch 索引添加文档。

为了[优化索引速度](/blog/best-practices-for-faster-indexing/),请务必在配置设置*之后*添加文档。

我们现在可以使用 Node.js 运行脚本:

node setup.js

我们的 Meilisearch 实例现已配置并填充数据。🥳 是时候使用 React 实现推广结果了!

显示推广结果

首先,我们将导航回应用程序的根目录(例如 my-app)。我们将使用 Vite 在此文件夹中创建 React 应用程序。

npm create vite@latest . --template react

如果 CLI 要求删除当前目录中的现有文件,请回答“否”。

然后,让我们安装用于将 InstantSearch 与 Meilisearch 集成的其他依赖项。

npm install @meilisearch/instant-meilisearch react-instantsearch-hooks-web

让我们编辑 App 组件以显示搜索结果。我们希望推广结果显示在其余结果之前。让我们用我们自己的代码替换 App.jsx 样板代码:

// src/App.jsx

import { instantMeiliSearch } from '@meilisearch/instant-meilisearch'
import { InstantSearch, SearchBox, Hits, Index } from 'react-instantsearch-hooks-web';
   
const MEILI_HOST = 'your Meilisearch host'
const MEILI_SEARCH_KEY = 'your Meilisearch Search API key'

const meilisearchClient = instantMeiliSearch(MEILI_HOST, MEILI_SEARCH_KEY)

const App = () => (
	<div>
		<h1>Hello React</h1>
		<InstantSearch searchClient={meilisearchClient}>
			<SearchBox />
			<h2>Results</h2>
			<Index indexName='promoted-movies'>
				<Hits />
			</Index>
			<h2>More results</h2>
			<Index indexName='movies'>
				<Hits />
			</Index>
		</InstantSearch>
	</div>
);

export default App;

我们现在可以使用 npm run dev 运行开发服务器。在浏览器中,我们的应用程序应显示如下内容:

HTML output of the code above

将推广结果显示在其他结果之前

恭喜。我们已成功将推广结果显示在其余结果之前。🎉

遇到问题了吗?请随时在我们的 Discord 社区中寻求帮助。

进一步学习

本教程探讨了一种实现推广结果的方法。另一种技术是在后端实现文档置顶——使用Meilisearch SDKs之一。这种方法的好处是允许将结果合并在一个响应中(就好像它们来自一个索引一样)。

这两种技术都可以实现类似的结果。我们还计划将推广文档集成到 Meilisearch 引擎中。请在上面的链接中提供您的反馈,以帮助我们确定其优先级。

要了解更多关于 Meilisearch 的信息,您可以订阅我们的新闻通讯。您可以通过查看路线图并参与我们的产品讨论来了解更多关于我们的产品。

如有其他问题,请加入我们开发者社区的 Discord

到时候见。

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.