FlexSearch
高速で軽量なドキュメント検索
セットアップ
npm install flexsearchnpm install @types/flexsearch -Dソースから作成する
ソースオブジェクトからサーバーを作成します。
import { source } from '@/lib/source';
import { flexsearchFromSource } from 'fumadocs-core/search/flexsearch';
export const { GET } = flexsearchFromSource(source);検索インデックスから
検索インデックスからサーバーを作成します。各インデックスには structuredData フィールドが必要です。
通常、これはコンテンツソース(例: Fumadocs MDX)から提供されます。Remark Structure プラグインを使って、Markdown/MDX ドキュメントから抽出することもできます。
flexsearchFromSource() の代わりに、これを検索ルートから配信します:
import { source } from '@/lib/source';
import { flexsearch } from 'fumadocs-core/search/flexsearch';
const server = flexsearch({
indexes: source.getPages().map((page) => ({
title: page.data.title!,
description: page.data.description,
url: page.url,
id: page.url,
structuredData: page.data.structuredData,
})),
});ドキュメントの検索
ドキュメントは次の方法で検索できます。
- Fumadocs UI: 標準でサポートされています。詳しくは検索 UIを参照してください。
- 検索クライアント:
import { } from 'fumadocs-core/search/client';
const { , , , } = ();プロパティ
型
設定
タグフィルター
タグで検索結果を絞り込めます。このドキュメントのような複数ドキュメント構成を実装する際に便利です。
import { source } from '@/lib/source';
import { flexsearchFromSource } from 'fumadocs-core/search/flexsearch';
const server = flexsearchFromSource(source, {
buildIndex(page) {
return {
title: page.data.title!,
description: page.data.description,
url: page.url,
id: page.url,
structuredData: page.data.structuredData,
// page.slugs[0] など、任意の値を指定します
tag: '<value>',
};
},
});次に、検索クライアントを更新します。
- Fumadocs UI: 検索 UI でタグフィルターを設定します。
- 検索クライアント:
useFetchSearch()にタグを渡します。
import { useFetchSearch } from 'fumadocs-core/search/client';
const { search, onSearchChange, isLoading, data } = useFetchSearch({
tag: '<value>',
});静的モード
静的サイトに対応するには、検索サーバーの staticGET を使用し、ルートを静的ルートにするか、事前レンダリングするようにしてください。
import { source } from '@/lib/source';
import { flexsearchFromSource } from 'fumadocs-core/search/flexsearch';
// 静的にキャッシュ
export const revalidate = false;
export const { staticGET: GET } = flexsearchFromSource(source);staticGET は flexsearch() でも利用できます。
続いて、検索クライアントを更新します。
-
Fumadocs UI: 検索 UI で静的クライアントを使用します。
-
検索クライアント: クライアントのアダプターを変更します。
import { useFlexsearchStatic } from 'fumadocs-core/search/client/flexsearch-static'; const { search, onSearchChange, isLoading, data } = useFlexsearchStatic({ // 任意: tag と locale を渡す tag, });プロパティ
型
注意
静的検索では、クライアントがエクスポートされた検索インデックスをダウンロードする必要があります。 大規模なドキュメントサイトでは、その負荷が大きくなる場合があります。
そのような場合は、Orama Cloud や Algolia などのクラウドソリューションの利用をおすすめします。
国際化
Flexsearch は、英語以外の言語でも特別な設定なしで動作しますが、ロケールごとに Flexsearch のオプションを指定すると、検索結果の精度を高められます。
import { source } from '@/lib/source';
import { flexsearchFromSource } from 'fumadocs-core/search/flexsearch';
import { Charset } from 'flexsearch';
const server = flexsearchFromSource(source, {
localeMap: {
// [locale]: Flexsearch のオプション
jp: { encoder: Charset.CJK },
},
});How is this guide?
最終更新日
