使用 React InstantSearch 實作置頂搜尋結果
了解如何使用 React InstantSearch Hooks 和 Meilisearch 顯示置頂結果。

今天我們將學習如何透過將特定文件釘選在搜尋結果的頂部來置頂結果。這可以用於電子商務中,以提高精選產品的能見度,或在應用程式內搜尋中優先顯示使用者特定的內容。我們將使用 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 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()
此腳本會建立我們的兩個索引。讓我們回顧一下它的作用
- 它為
movies
和promoted-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
執行開發伺服器。在瀏覽器中,我們的應用程式應顯示如下內容
在其他結果之前顯示置頂結果
恭喜。我們已成功在其他結果之前顯示置頂結果。🎉
遇到困難嗎?請隨時在我們的 Discord 社群中尋求協助。
更進一步
本教學探討了一種實作置頂結果的方法。另一種方法是在後端實作文件釘選—使用其中一個Meilisearch SDK。此方法的優點是允許在單一回應中合併結果(彷彿它們來自單一索引)。
這兩種技術都可以達到類似的結果。我們也計劃在 Meilisearch 引擎中整合置頂文件。請在先前的連結中提供您的意見,以協助我們確定其優先順序。
如需更多 Meilisearch 相關資訊,您可以訂閱我們的電子報。您可以查看路線圖並參與我們的產品討論,以了解更多關於我們產品的資訊。
如有其他任何問題,請加入我們在 Discord 上的開發者社群。
在那裡見。