UNPKG

@aiquants/fuzzy-search

Version:

Advanced fuzzy search library with Levenshtein distance, n-gram indexing, and Web Worker support

267 lines (203 loc) 8.74 kB
# @aiquants/fuzzy-search Advanced fuzzy search library with Levenshtein distance, n-gram indexing, and Web Worker support. レーベンシュタイン距離、n-gram インデックス、Web Worker サポートを備えた高度なあいまい検索ライブラリ。 ## Features / 機能 - **Advanced Fuzzy Search**: Levenshtein distance-based fuzzy matching / レーベンシュタイン距離によるあいまい一致 - **Performance Optimized**: Web Worker support for non-blocking search / ノンブロッキング検索のための Web Worker サポート - **Multiple Index Types**: N-gram, word, and phonetic indexing / N-gram、単語、音素インデックス - **Learning Capabilities**: Adapts based on user search patterns / ユーザーの検索パターンに基づく学習機能 - **React Integration**: Ready-to-use hooks and components / すぐに使える React フックとコンポーネント - **Voice Search**: Web Speech API integration / Web Speech API 統合 - **TypeScript First**: Full type safety and IntelliSense support / 完全な型安全性と IntelliSense サポート - **Highly Configurable**: Extensive options for customization / 豊富なカスタマイズオプション ## Installation / インストール ```bash # Using pnpm (recommended) / pnpm を使用(推奨) pnpm add @aiquants/fuzzy-search # Using npm npm install @aiquants/fuzzy-search # Using yarn yarn add @aiquants/fuzzy-search ``` **Note**: This package is optimized for pnpm. The package manager is specified as `pnpm@9.0.0` for better dependency management. **注意**: このパッケージは pnpm 用に最適化されています。より良い依存関係管理のため、パッケージマネージャーは `pnpm@9.0.0` として指定されています。 ## Quick Start / クイックスタート ### Basic Usage / 基本的な使用方法 ```typescript import { quickSearch } from '@aiquants/fuzzy-search' const items = [ { name: 'Apple', category: 'Fruit' }, { name: 'Banana', category: 'Fruit' }, { name: 'Carrot', category: 'Vegetable' }, ] // Simple search const results = await quickSearch('aple', items, ['name'], { threshold: 0.4, maxResults: 10 }) console.log(results) // [{ name: 'Apple', category: 'Fruit' }] ``` ### Advanced Usage / 高度な使用方法 ```typescript import { FuzzySearchManager } from '@aiquants/fuzzy-search' const searchManager = new FuzzySearchManager({ threshold: 0.4, maxResults: 50, enableNgramIndex: true, enablePhonetic: true, learningWeight: 1.2, debounceMs: 300, enableHighlighting: true, }) // Perform search const results = await searchManager.search('query', items, ['name', 'description']) // Handle results results.forEach(result => { console.log(`Item: ${result.item.name}, Score: ${result.score}`) if (result.highlighted) { console.log(`Highlighted: ${result.highlighted.name}`) } }) // Clean up searchManager.dispose() ``` ## React Integration / React 統合 ### Hooks / フック ```typescript import { useFuzzySearch } from '@aiquants/fuzzy-search/react' function SearchComponent() { const { searchTerm, setSearchTerm, filteredItems, isLoading, highlightText, stats } = useFuzzySearch(items, ['name', 'email'], { threshold: 0.4, debounceMs: 300, enableHighlighting: true, }) return ( <div> <input value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} placeholder="Search..." /> {isLoading ? ( <div>Searching...</div> ) : ( <ul> {filteredItems.map((item, index) => ( <li key={index}> <div dangerouslySetInnerHTML={{ __html: highlightText(item.name) }} /> </li> ))} </ul> )} <div>Found {stats.totalResults} results in {stats.executionTime}ms</div> </div> ) } ``` ### Voice Search / 音声検索 ```typescript import { useVoiceSearch } from '@aiquants/fuzzy-search/react' function VoiceSearchComponent() { const { isListening, transcript, startListening, stopListening, isSupported } = useVoiceSearch({ onResult: (text) => console.log('Speech result:', text), continuous: false, interimResults: true, }) if (!isSupported) { return <div>Voice search not supported</div> } return ( <div> <button onClick={isListening ? stopListening : startListening}> {isListening ? 'Stop' : 'Start'} Voice Search </button> <div>Transcript: {transcript}</div> </div> ) } ``` ## Configuration Options / 設定オプション ```typescript interface FuzzySearchOptions { // Basic options / 基本オプション threshold: number // Similarity threshold (0-1) / 類似度閾値 maxResults: number // Maximum number of results / 最大結果数 caseSensitive: boolean // Case-sensitive matching / 大文字小文字を区別 // Performance options / パフォーマンスオプション enableNgramIndex: boolean // Enable n-gram indexing / n-gram インデックスを有効 enablePhonetic: boolean // Enable phonetic matching / 音素マッチングを有効 ngramSize: number // N-gram size / N-gram サイズ minNgramOverlap: number // Minimum n-gram overlap / 最小 n-gram オーバーラップ // Learning options / 学習オプション learningWeight: number // Weight for learning adjustments / 学習調整の重み // UI options / UI オプション debounceMs: number // Debounce delay in milliseconds / ミリ秒単位のデバウンス遅延 enableHighlighting: boolean // Enable result highlighting / 結果ハイライトを有効 // Custom weights / カスタム重み customWeights: Record<string, number> // Field-specific weights / フィールド固有の重み } ``` ## Web Worker Support / Web Worker サポート For large datasets, the search can be performed in a Web Worker to avoid blocking the main thread: 大きなデータセットの場合、メインスレッドをブロックしないよう Web Worker で検索を実行できます: ```typescript import { FuzzySearchManager } from '@aiquants/fuzzy-search' const searchManager = new FuzzySearchManager({ useWebWorker: true, // Enable Web Worker threshold: 0.4, }) // Search will automatically use Web Worker for large datasets const results = await searchManager.search('query', largeItems, ['name']) ``` ## Performance Tips / パフォーマンスのヒント 1. **Enable n-gram indexing** for large datasets (>1000 items) / 大きなデータセット(1000 項目以上)では n-gram インデックスを有効にする 2. **Use Web Workers** for datasets with >5000 items / 5000 項目以上のデータセットでは Web Worker を使用する 3. **Adjust threshold** based on your use case (lower = more results) / 用途に応じて閾値を調整する(低い = より多くの結果) 4. **Use debouncing** to reduce search frequency / デバウンスを使用して検索頻度を減らす 5. **Configure custom weights** for field importance / フィールドの重要度に応じてカスタム重みを設定する ## API Reference / API リファレンス ### Core Classes / コアクラス - `FuzzySearchManager`: Main search management class / メイン検索管理クラス - `SearchIndexer`: Advanced indexing system / 高度なインデックスシステム ### React Hooks / React フック - `useFuzzySearch`: Main search hook / メイン検索フック - `useVoiceSearch`: Voice search hook / 音声検索フック - `useSearchHistory`: Search history management / 検索履歴管理 ### Utility Functions / ユーティリティ関数 - `quickSearch`: Simple search function / 簡単な検索関数 - `levenshteinDistance`: Distance calculation / 距離計算 - `highlightText`: Text highlighting / テキストハイライト ## Browser Support / ブラウザサポート - Chrome / Chromium 60+ - Firefox 55+ - Safari 11+ - Edge 79+ ## License / ライセンス MIT License ## Contributing / 貢献 Contributions are welcome! Please feel free to submit a Pull Request. 貢献を歓迎します!プルリクエストをお気軽に提出してください。 ## Changelog / 変更履歴 ### v1.0.0 - Initial release / 初回リリース - Full fuzzy search implementation / 完全なあいまい検索実装 - React hooks and components / React フックとコンポーネント - Web Worker support / Web Worker サポート - Voice search integration / 音声検索統合 - Learning capabilities / 学習機能 - TypeScript support / TypeScript サポート