UNPKG

@aiquants/fuzzy-search

Version:

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

464 lines (460 loc) 19.8 kB
/** * @module types/index * @description Core types for the fuzzy search library. * @description あいまい検索ライブラリのコア型定義。 */ /** * @interface FuzzySearchOptions * @description Configuration options for fuzzy search functionality. * @description あいまい検索機能の設定オプション。 */ interface FuzzySearchOptions { /** * @property {number} threshold - Similarity threshold (0.0-1.0). * @description 類似度の閾値。この値以上のスコアを持つアイテムが結果に含まれます。 */ threshold: number; /** * @property {boolean} caseSensitive - Whether to perform case-sensitive search. * @description 大文字小文字を区別するかどうか。true の場合、区別して検索します。 */ caseSensitive: boolean; /** * @property {number} learningWeight - Learning weight for user behavior (0.0-2.0). * @description ユーザーの選択行動に基づく学習による重み付け。1.0より大きいと学習効果が強まります。 */ learningWeight: number; /** * @property {number} debounceMs - Debounce time in milliseconds. * @description 検索入力のデバウンス時間(ミリ秒)。連続入力時の不要な検索処理を防ぎます。 */ debounceMs: number; /** * @property {'and' | 'or'} multiTermOperator - Logical operator applied to space-separated query terms. * @description スペース区切りのクエリ語に適用する論理演算子。 */ multiTermOperator: "and" | "or"; /** * @property {boolean} autoSearchOnIndexRebuild - Whether to trigger a search immediately after the index is rebuilt. * @description インデックス再構築直後に自動的に検索を実行するかどうか。 */ autoSearchOnIndexRebuild: boolean; /** * @property {Record<string, number>} customWeights - Custom field weights for scoring. * @description 特定のフィールドに対するカスタムの重み設定。スコアリングに影響します。 */ customWeights: Record<string, number>; /** * @property {number} ngramSize - N-gram size for indexing (default: 2). * @description インデックス作成に使用する N-gram のサイズ。通常は2または3が使われます。 */ ngramSize: number; /** * @property {number} minNgramOverlap - Minimum n-gram overlap for candidate filtering. * @description 候補フィルタリングのための最小 N-gram 重複数。 */ minNgramOverlap: number; /** * @property {'score' | 'relevance' | 'original'} sortBy - Sort results by field. * @description 検索結果のソート基準。'score' (類似度スコア)、'relevance' (関連性)、'original' (元の順序) から選択します。 */ sortBy: "score" | "relevance" | "original"; /** * @property {'asc' | 'desc'} sortOrder - Sort order (ascending or descending). * @description ソート順序 (昇順または降順)。 */ sortOrder: "asc" | "desc"; /** * @property {boolean} enableIndexFiltering - Enable index-based filtering stage. * @description インデックスベースのフィルタリングステージを有効にするかどうか。 */ enableIndexFiltering: boolean; /** * @property {boolean} enableLevenshtein - Enable Levenshtein distance calculation stage. * @description レーベンシュタイン距離計算ステージを有効にするかどうか。 */ enableLevenshtein: boolean; /** * @property {'index-first' | 'levenshtein-first' | 'balanced'} parallelSearchStrategy - Parallel search strategy. * @description 並列検索の戦略。'index-first' (インデックス優先)、'levenshtein-first' (レーベンシュタイン優先)、'balanced' (バランス) から選択します。 */ parallelSearchStrategy: "index-first" | "levenshtein-first" | "balanced"; /** * @property {object} [workerUrls] - Custom Worker URLs for external hosting. * @description 外部ホスティング用のカスタム Worker URL。 */ workerUrls?: { /** * @property {string} [indexWorker] - URL for the index worker. * @description Index Worker の URL。 */ indexWorker?: string; /** * @property {string} [levenshteinWorker] - URL for the levenshtein worker. * @description Levenshtein Worker の URL。 */ levenshteinWorker?: string; }; /** * @property {object} [indexWorkerOptions] - Index Worker specific parameters. * @description Index Worker 固有のパラメータ。 */ indexWorkerOptions?: { /** * @property {IndexStrategy} [strategy] - Index Worker search strategy ('fast' | 'accurate' | 'hybrid'). * @description Index Worker の検索戦略。 */ strategy?: IndexStrategy; /** * @property {number} [threshold] - Similarity threshold for Index Worker (0.0-1.0). * @description Index Worker 用の類似度閾値。 */ threshold?: number; /** * @property {number} [ngramOverlapThreshold] - N-gram overlap threshold ratio (0.0-1.0). * @description N-gram 重複閾値の比率。 */ ngramOverlapThreshold?: number; /** * @property {number} [minCandidatesRatio] - Minimum candidates ratio for fast search (0.0-1.0). * @description 高速検索用の最小候補比率。 */ minCandidatesRatio?: number; /** * @property {number} [maxCandidatesRatio] - Maximum candidates ratio to trigger filtering (0.0-1.0). * @description フィルタリングを発動するための最大候補比率。 */ maxCandidatesRatio?: number; /** * @property {number} [jaroWinklerPrefix] - Jaro-Winkler prefix scaling factor (0.0-0.25). * @description Jaro-Winkler アルゴリズムの接頭辞スケーリング係数。 */ jaroWinklerPrefix?: number; /** * @property {number} [maxResults] - Maximum number of results for Index Worker. * @description Index Worker 用の最大結果数。 */ maxResults?: number; /** * @property {number} [relevanceFieldWeight] - Weight for matched field count in relevance score (0.0-1.0). * @description relevance スコア計算時のマッチフィールド数の重み。 */ relevanceFieldWeight?: number; /** * @property {number} [relevancePerfectMatchBonus] - Bonus for perfect match in relevance score (0.0-1.0). * @description relevance スコア計算時の完全一致ボーナス。 */ relevancePerfectMatchBonus?: number; }; /** * @property {object} [levenshteinWorkerOptions] - Levenshtein Worker specific parameters. * @description Levenshtein Worker 固有のパラメータ。 */ levenshteinWorkerOptions?: { /** * @property {number} [threshold] - Similarity threshold for Levenshtein Worker (0.0-1.0). * @description Levenshtein Worker 用の類似度閾値。 */ threshold?: number; /** * @property {number} [lengthSimilarityThreshold] - Length-based similarity threshold for early rejection. * @description 長さベースの類似度閾値(早期リジェクション用)。 */ lengthSimilarityThreshold?: number; /** * @property {number} [partialMatchBonus] - Partial match bonus score. * @description 部分一致が検出された場合に加算されるボーナススコア。 */ partialMatchBonus?: number; /** * @property {number} [lengthDiffPenalty] - Length difference penalty ratio. * @description 文字列長の差によるペナルティの比率。 */ lengthDiffPenalty?: number; /** * @property {number} [maxResults] - Maximum number of results for Levenshtein Worker. * @description Levenshtein Worker 用の最大結果数。 */ maxResults?: number; /** * @property {number} [relevanceFieldWeight] - Weight for matched field count in relevance score (0.0-1.0). * @description relevance スコア計算時のマッチフィールド数の重み。 */ relevanceFieldWeight?: number; }; } /** * @type PartialFuzzySearchOptions * @description Partial options for initializing fuzzy search. Allows overriding a subset of the default options. * @description あいまい検索初期化用の部分オプション。デフォルトオプションの一部を上書きできます。 */ type PartialFuzzySearchOptions = Partial<FuzzySearchOptions>; /** * @interface SearchResultItem * @description Represents an individual search result item with metadata. * @description メタデータを含む個別の検索結果アイテムを表します。 * @template T - The type of the original item. */ interface SearchResultItem<T = unknown> { /** * @property {T} item - The original item from the search dataset. * @description 検索データセットの元のアイテム。 */ item: T; /** * @property {number} score - Final similarity score (0.0-1.0+). May exceed 1.0 in Relevance mode due to bonuses. * @description 最終的な類似度スコア (0.0-1.0+)。Relevance モードではボーナスにより 1.0 を超える場合があります。 */ score: number; /** * @property {number} baseScore - Base similarity score before any adjustments (0.0-1.0). * @description 調整前の基本類似度スコア (0.0-1.0)。Relevance モードの重み付け前の値です。 */ baseScore: number; /** * @property {string[]} matchedFields - Fields that matched the search query. * @description 検索クエリにマッチしたフィールドのリスト。 */ matchedFields: string[]; /** * @property {number} [originalIndex] - Original index in the source dataset. * @description 元のデータセットにおけるインデックス。 */ originalIndex?: number; /** * @property {Record<string, unknown>} [metadata] - Additional metadata for the result. * @description 結果に関連する追加のメタデータ。 */ metadata?: Record<string, unknown>; } /** * @type IndexStrategy * @description Enumeration of available index strategies. * @description 利用可能なインデックス戦略の列挙。 * - `fast`: N-gram index only for quick filtering. 高速なフィルタリングのためのN-gramインデックスのみ。 * - `accurate`: Word-based and phonetic indexes for higher accuracy. 高精度な単語ベースおよび音韻インデックス。 * - `hybrid`: A combination of fast and accurate strategies. 高速戦略と高精度戦略の組み合わせ。 */ type IndexStrategy = "fast" | "accurate" | "hybrid"; /** * @interface PerformanceInsights * @description Data providing insights into search performance. * @description 検索パフォーマンスに関する洞察を提供するデータ。 */ interface PerformanceInsights { recentAverageProcessingTime: number; recentAverageResultCount: number; throughputPerSecond: number; totalHistoryEntries: number; mostCommonQueryLength: number; bestPerformingField: string; similarityDistribution: { highSimilarity: number; mediumSimilarity: number; lowSimilarity: number; veryLowSimilarity: number; }; } /** * @interface PerformanceHistoryEntry * @description Individual performance history entry for tracking operation performance. * @description 操作パフォーマンスを追跡するための個別のパフォーマンス履歴エントリ。 */ interface PerformanceHistoryEntry { timestamp: number; queryLength: number; itemCount: number; processingTime: number; resultCount: number; operationType: string; additionalMetrics?: Record<string, unknown>; } /** * @interface FieldStatistic * @description Statistics for individual search fields across all operations. * @description 全操作における個別検索フィールドの統計。 */ interface FieldStatistic { matchCount: number; averageScore: number; totalScore: number; bestScore: number; worstScore: number; } /** * @interface UnifiedWorkerStats * @description Completely unified statistics interface for all worker types. * @description すべてのワーカータイプに対応する完全統一統計インターフェース。 */ interface UnifiedWorkerStats { /** * @property basic Basic statistics common to all workers. * @description 全ワーカー共通の基本統計。 */ basic: { totalSearches: number; totalProcessingTime: number; averageSearchTime: number; lastSearchTime: number; errorCount: number; timestamp: number; }; /** * @property workerSpecific Worker-type specific statistics. * @description ワーカータイプ固有の統計。 */ workerSpecific: { workerType: "index" | "levenshtein"; operationCount: number; operationDistribution: Record<string, number>; specificMetrics: Record<string, unknown>; }; /** * @property analysis Advanced analysis and insights. * @description 高度な分析とインサイト。 */ analysis: { fieldPerformance: Record<string, FieldStatistic>; performanceInsights: PerformanceInsights; recentHistory: PerformanceHistoryEntry[]; }; } /** * @interface SearchHistory * @description Represents a single entry in the search history for learning and analytics. * @description 学習と分析のための検索履歴の単一エントリを表します。 */ interface SearchHistory { /** * @property {string} query - The search query. * @description 検索クエリ。 */ query: string; /** * @property {number} timestamp - Timestamp of the search. * @description 検索が実行されたときのタイムスタンプ。 */ timestamp: number; /** * @property {number} resultCount - Number of results found. * @description 見つかった結果の数。 */ resultCount: number; /** * @property {number} processingTime - Processing time in milliseconds. * @description 処理にかかった時間(ミリ秒)。 */ processingTime: number; /** * @property {number} [searchTime] - Alias for processingTime. * @description processingTime のエイリアス。 */ searchTime?: number; /** * @property {number} [selectedIndex] - Index of the selected result, if any. * @description ユーザーが選択した結果のインデックス(存在する場合)。 */ selectedIndex?: number; /** * @property {string} [selectedItemId] - ID of the selected item, if any. * @description ユーザーが選択したアイテムのID(存在する場合)。 */ selectedItemId?: string; /** * @property {number} [satisfactionScore] - User satisfaction score (1-5). * @description ユーザー満足度スコア(1-5)。 */ satisfactionScore?: number; /** * @property {boolean} successful - Whether the search was considered successful. * @description 検索が成功したと見なされたかどうか。 */ successful: boolean; /** * @property {string} [context] - Context or source of the search. * @description 検索が実行されたコンテキストまたはソース。 */ context?: string; } /** * @type UseFuzzySearchOptions * @description Options type for the useFuzzySearch hook, extending PartialFuzzySearchOptions. * @description useFuzzySearch フック用のオプション型。PartialFuzzySearchOptions を拡張します。 */ type UseFuzzySearchOptions = PartialFuzzySearchOptions; /** * @interface SearchHistoryResult * @description The return type for a hook that manages search history. * @description 検索履歴を管理するフックの戻り値の型。 */ interface SearchHistoryResult { searchHistory: SearchHistory[]; addToHistory: (term: string) => void; clearHistory: () => void; } /** * @interface PerformanceMetrics * @description Data type for the performance metrics callback. * @description パフォーマンス指標コールバック用のデータ型。 */ interface PerformanceMetrics { totalSearches: number; averageSearchTime: number; itemCount: number; resultsCount: number; workerStats?: { index?: UnifiedWorkerStats; levenshtein?: UnifiedWorkerStats; }; } /** * @interface FuzzySearchResult * @description The return type for the simplified fuzzy search hook. * @description 簡易版のあいまい検索フックの戻り値の型。 * @template T - The type of the items being searched. */ interface FuzzySearchResult<T> { searchTerm: string; setSearchTerm: (term: string) => void; filteredItems: SearchResultItem<T>[]; isSearching: boolean; isIndexBuilding: boolean; error: string | null; searchHistory: SearchHistory[]; options: FuzzySearchOptions; selectItem: (item: T, index: number) => void; clearSearch: () => void; clearHistory: () => void; resetStats: () => Promise<void>; getSearchSuggestions: (query: string, limit?: number) => string[]; performanceMetrics: PerformanceMetrics; rebuildIndex: (customOptions?: UseFuzzySearchOptions) => Promise<void>; } /** * React hooks and utilities for fuzzy search functionality. * あいまい検索機能用のReactフックとユーティリティ。 * * Note: This module requires React as a peer dependency. * 注意:このモジュールはReactをピア依存関係として必要とします。 */ /** * A simplified fuzzy search hook with stable state management. * This hook provides an easy-to-use interface for performing fuzzy searches on a list of items. * 安定した状態管理を持つ簡易あいまい検索フック。 * このフックは、アイテムのリストに対してあいまい検索を実行するための使いやすいインターフェースを提供します。 * @param items The array of items to search through. * @param searchFields The fields in the items to search against. * @param initialOptions Optional initial configuration for the fuzzy search. * @returns An object containing the search state and functions. */ declare function useFuzzySearch<T>(items: T[], searchFields: Array<keyof T | string>, initialOptions?: UseFuzzySearchOptions): FuzzySearchResult<T>; /** * A hook for managing search term history. * This hook provides state and functions for adding to and clearing search history. * 検索語履歴を管理するためのフック。 * このフックは、検索履歴の追加とクリアのための状態と関数を提供します。 * @param maxHistory The maximum number of history items to store. * @returns An object containing the search history state and functions. */ declare function useSearchHistory(maxHistory?: number): SearchHistoryResult; export { type FuzzySearchResult, type PerformanceMetrics, type SearchHistoryResult, type UnifiedWorkerStats, type UseFuzzySearchOptions, useFuzzySearch, useSearchHistory };