今天我们将学习如何通过将给定的文档固定在搜索结果的顶部来推荐结果。 这可以用于电子商务,以提高推荐产品的可见度,或者在应用程序内搜索中优先考虑用户特定的内容。 我们将使用 Node.js 和 React 来实现推荐文档。

💬
需要在 Meilisearch 引擎中使用推荐文档? 分享您的反馈

本教程将使用示例电影数据集。 我们的目标是在键入“funny”、“children”或“fish”时将“Finding Nemo”放在结果的顶部。

文件夹结构

在本指南中,我们将分离用于配置 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 SDK

在本教程中,我们使用 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 设置了相同的 显示属性
  • 它设置了 可搜索属性; 只有 keywordspromoted-movies 索引中是可搜索的。
  • 它将文档添加到我们的 Meilisearch 索引中。
💡
为了 优化索引速度,请始终在配置设置之后添加文档。

现在,我们可以使用 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 SDK 之一。 这种方法的优点是允许在单个响应中合并结果(就像它们来自单个索引一样)。

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

有关 Meilisearch 的更多信息,你可以订阅我们的 新闻稿。 你可以通过查看 路线图 和参与我们的 产品讨论 来详细了解我们的产品。

有关其他任何内容,请加入我们的开发人员社区,加入 Discord

我们在那儿见。