### Fuse.js Quick Start Example Source: https://www.fusejs.io/getting-started.html A basic example demonstrating how to initialize Fuse.js with data and perform a search. Fuse.js searches specified keys and ranks results by relevance. ```js import Fuse from 'fuse.js' const books = [ { title: "Old Man's War", author: 'John Scalzi' }, { title: 'The Lock Artist', author: 'Steve Hamilton' } ] const fuse = new Fuse(books, { keys: ['title', 'author'] }) const results = fuse.search('jon') // [{ item: { title: "Old Man's War", author: "John Scalzi" }, refIndex: 0 }] ``` -------------------------------- ### Install Fuse.js using npm Source: https://www.fusejs.io/ Install the Fuse.js library using npm for use in your project. ```bash npm install fuse.js ``` -------------------------------- ### Install Fuse.js with bun Source: https://www.fusejs.io/getting-started.html Use this command to add Fuse.js to your project via bun. ```sh bun add fuse.js ``` -------------------------------- ### Install Fuse.js Beta Release Source: https://www.fusejs.io/web-workers.html Install the beta version of Fuse.js to use the Web Workers feature. ```bash npm install fuse.js@beta ``` -------------------------------- ### Bitap Algorithm: Example Scan Source: https://www.fusejs.io/articles/how-fuzzy-search-works.html Demonstrates the Bitap algorithm's step-by-step execution for searching the pattern 'test' in the text 'xtest'. Shows the state vector 'R' changes with each character read. ```javascript t e s t Start: R = 0 0 0 0 Read 'x': R = 0 0 0 0 ← 'x' isn't in the pattern, seed killed Read 't': R = 1 0 0 0 ← 't' matches position 0, partial match starts Read 'e': R = 0 1 0 0 ← 'e' matches position 1, match continues Read 's': R = 0 0 1 0 ← 's' matches position 2, still going Read 't': R = 1 0 0 1 ← 't' matches position 3 → full match! (also starts a new match at position 0) ``` -------------------------------- ### Install Fuse.js with pnpm Source: https://www.fusejs.io/getting-started.html Use this command to add Fuse.js to your project via pnpm. ```sh pnpm add fuse.js ``` -------------------------------- ### Install Fuse.js with yarn Source: https://www.fusejs.io/getting-started.html Use this command to add Fuse.js to your project via yarn. ```sh yarn add fuse.js ``` -------------------------------- ### Basic Fuse.js Search Example Source: https://www.fusejs.io/ Initialize Fuse.js with a list of objects and search keys, then perform a fuzzy search. The `includeScore` option provides a relevance score for each result. ```javascript import Fuse from 'fuse.js' const books = [ { title: "Old Man's War", author: 'John Scalzi' }, { title: 'The Lock Artist', author: 'Steve Hamilton' }, { title: 'JavaScript Patterns', author: 'Stoyan Stefanov' } ] const fuse = new Fuse(books, { keys: ['title', 'author'], includeScore: true }) fuse.search('jon') // [{ item: { title: "Old Man's War", author: "John Scalzi" }, refIndex: 0, score: 0.25 }] fuse.search('patterns') // [{ item: { title: "JavaScript Patterns", ... }, refIndex: 2, score: 0.0 }] ``` -------------------------------- ### Fuse.js Search Example Source: https://www.fusejs.io/articles/vs-semantic-search.html Use this for typo-tolerant, instant searches that run entirely in the browser. It's ideal for finding known items like product names or settings. ```javascript import Fuse from 'fuse.js' const products = [ { name: 'MacBook Pro 16"', sku: 'MBP16', category: 'Laptops' }, { name: 'Magic Keyboard', sku: 'MK', category: 'Accessories' }, { name: 'Mac Mini M4', sku: 'MM4', category: 'Desktops' }, // ... hundreds or thousands of items ] const fuse = new Fuse(products, { keys: ['name', 'sku', 'category'], threshold: 0.4 }) // Typo-tolerant, instant, runs in the browser fuse.search('mackbook') // [{ item: { name: 'MacBook Pro 16"', ... }, ... }] ``` -------------------------------- ### Fuse.js Extended Search Examples Source: https://www.fusejs.io/extended-search.html Demonstrates various combinations of extended search operators including prefix, inverse, suffix, and OR logic. ```javascript const books = [ { title: "Old Man's War", author: 'John Scalzi' }, { title: 'The Lock Artist', author: 'Steve Hamilton' }, { title: 'Artist for Life', author: 'Michelangelo' } ] const fuse = new Fuse(books, { useExtendedSearch: true, keys: ['title'] }) // Starts with "Old" AND fuzzy match "war" fuse.search('^Old war') // Does NOT include "Artist" AND starts with "Old" fuse.search('!Artist ^Old') // Ends with "Artist" OR includes "War" fuse.search("Artist$ | 'War") ``` -------------------------------- ### Bitap Algorithm Error Levels Example Source: https://www.fusejs.io/articles/how-fuzzy-search-works.html Illustrates how the Bitap algorithm progresses through error levels (R0, R1, R2) to find approximate matches for a pattern in a text, even with transpositions. ```text t e s t R0 (0 errors): 1 0 0 0 ← 't' matches, but 's' ≠ 'e' — exact match dies R1 (1 error): 1 1 0 0 ← the mismatch continues here as 1 error R2 (2 errors): 1 1 1 1 ← another mismatch, 2 errors — still matches! ``` -------------------------------- ### Nested Logical Queries Source: https://www.fusejs.io/logical-search.html Combine $and and $or operators arbitrarily for complex search criteria. This example nests an $or within an $and. ```javascript const result = fuse.search({ $and: [ { title: 'old war' }, { $or: [ { title: '^lock' }, { title: '!arts' } ] } ] }) ``` -------------------------------- ### Highlighting Search Matches in React Source: https://www.fusejs.io/articles/using-fuse-with-react.html Use `includeMatches` to get character-level match positions. The `highlightMatches` function then wraps these matched characters in `` tags for visual highlighting. Ensure the end index is inclusive when slicing. ```jsx import { useMemo, useState } from 'react' import Fuse from 'fuse.js' // Splits text into plain strings and elements based on match regions function highlightMatches(text, regions = []) { if (!regions.length) return text const chunks = [] let lastIndex = 0 // Fuse.js returns sorted, non-overlapping [start, end] pairs for (const [start, end] of regions) { // Add any unmatched text before this region if (start > lastIndex) { chunks.push(text.slice(lastIndex, start)) } // Wrap the matched range in a tag chunks.push({text.slice(start, end + 1)}) lastIndex = end + 1 } // Add any remaining text after the last match if (lastIndex < text.length) { chunks.push(text.slice(lastIndex)) } return chunks } function BookSearch({ books }) { const [query, setQuery] = useState('') const fuse = useMemo(() => { return new Fuse(books, { keys: ['title', 'author'], includeMatches: true, // return character-level match positions threshold: 0.4, }) }, [books]) const results = query ? fuse.search(query) : [] return (
setQuery(e.target.value)} />
    {results.map(({ item, matches }) => { // Find match data for each field we want to highlight const titleMatch = matches?.find((m) => m.key === 'title') const authorMatch = matches?.find((m) => m.key === 'author') return (
  • {highlightMatches(item.title, titleMatch?.indices)} — {highlightMatches(item.author, authorMatch?.indices)}
  • ) })}
) } ``` ```css mark { background-color: #fef08a; padding: 0; } ``` -------------------------------- ### React FuzzySearch Component Usage Source: https://www.fusejs.io/articles/using-fuse-with-react.html Example of how to use the `FuzzySearch` component in a React application. Pass your data array to the `items` prop, specify the keys to search within using the `keys` prop, and define a unique key for each item with `itemKey`. ```jsx ``` -------------------------------- ### Initialize Fuse Cloud Client and Search Source: https://www.fusejs.io/cloud.html Import FuseCloud, initialize a client with a public key and index name, and then perform a search query. The results format is identical to Fuse.js. ```javascript import { FuseCloud } from "@fusejs/cloud" const client = new FuseCloud({ publicKey: "pk_abc123", index: "products" }) const { results } = await client.search("iphone") // → [{ id: "1", score: 0.02, item: { title: "iPhone 16 Pro", ... } }] ``` -------------------------------- ### Initialize Fuse.js with Search Options Source: https://www.fusejs.io/demo.html Instantiate Fuse.js with a dataset and configuration including score, matches, and specific keys for searching. This is useful for setting up a searchable index. ```javascript const fuse = new Fuse(books, { includeScore: true, includeMatches: true, keys: ['title', 'author.firstName', 'author.lastName'] }) fuse.search('') ``` -------------------------------- ### Importing Fuse.js Basic Build Source: https://www.fusejs.io/getting-started.html Import the basic build of Fuse.js, which only includes fuzzy search. ```js // Basic build import Fuse from 'fuse.js/basic' ``` -------------------------------- ### Basic Fuse.js Initialization and Search Source: https://www.fusejs.io/articles/vs-semantic-search.html Initialize Fuse.js with your data and search options, then perform a search. Adjust the 'threshold' option to control the fuzziness of the search results. ```javascript import Fuse from 'fuse.js' const fuse = new Fuse(yourData, { keys: ['name', 'description'], threshold: 0.4 }) const results = fuse.search('query') ``` -------------------------------- ### Execute Benchmark Script with Node.js Source: https://www.fusejs.io/performance.html Run the benchmark script using Node.js with the `--input-type=module` flag to enable ES module support. ```bash node --input-type=module bench.mjs ``` -------------------------------- ### Bitap Algorithm: Exact Match Scan Source: https://www.fusejs.io/articles/how-fuzzy-search-works.html Illustrates the state vector 'R' progression during a Bitap algorithm scan for exact matching. Shows how matches are seeded, propagated, and killed based on text characters. ```javascript Initial state — all bits are `0` (no matches yet) R0000 t0e1s2t3 ``` -------------------------------- ### Initialize FuseWorker and Perform Search Source: https://www.fusejs.io/web-workers.html Import FuseWorker, initialize it with documents and options, perform a search, and terminate the workers when done. The search() method returns a Promise. ```javascript import { FuseWorker } from 'fuse.js/worker' const fuse = new FuseWorker(docs, { keys: ['title', 'author', 'description'], threshold: 0.4, includeScore: true }) const results = await fuse.search('javascript') // Clean up when done fuse.terminate() ``` -------------------------------- ### Initialize Fuse.js with Token Search Source: https://www.fusejs.io/token-search.html Enable token search by setting `useTokenSearch: true` in the Fuse.js options. This allows for multi-word queries to be split and matched independently. ```javascript const fuse = new Fuse(docs, { useTokenSearch: true, keys: ['title', 'author', 'description'] }) fuse.search('javascrpt paterns') // → [{ item: { title: 'JavaScript Patterns', ... }, score: 0.12 }] ``` -------------------------------- ### Importing Minified Fuse.js Builds Source: https://www.fusejs.io/getting-started.html Import minified versions of Fuse.js for reduced file size. ```js // Minified variants import Fuse from 'fuse.js/min' import Fuse from 'fuse.js/min-basic' ``` -------------------------------- ### Basic Fuzzy Search with Fuse.js Source: https://www.fusejs.io/fuzzy-search.html Initialize Fuse.js with a list of items and perform a fuzzy search. The `includeScore` option returns the relevance score for each match. ```javascript const fuse = new Fuse(['apple', 'banana', 'orange'], { includeScore: true }) fuse.search('aple') // [{ item: 'apple', refIndex: 0, score: 0.25 }] ``` -------------------------------- ### Run Fuse.js Benchmark Script Source: https://www.fusejs.io/performance.html Use this script to measure indexing and search times for Fuse.js with your own data. Configure list size, keys, query, and search runs. The script generates sample data, benchmarks indexing, and averages search times over multiple runs. ```javascript import Fuse from 'fuse.js' // -- Configure to match your use case -- const LIST_SIZE = 10_000 const KEYS = ['title', 'description', 'category', 'tags'] const QUERY = 'javascript' const OPTIONS = { keys: KEYS, threshold: 0.4 } const SEARCH_RUNS = 100 // -- Generate sample data -- const words = ['alpha', 'bravo', 'charlie', 'delta', 'echo', 'foxtrot', 'golf', 'hotel', 'india', 'juliet', 'kilo', 'lima', 'mike', 'november', 'oscar', 'papa', 'quebec', 'romeo', 'sierra', 'tango', 'uniform', 'victor', 'whiskey', 'xray', 'yankee', 'zulu', 'javascript', 'typescript', 'python', 'rust', 'golang', 'swift', 'kotlin', 'scala', 'elixir'] function randomSentence(len) { return Array.from({ length: len }, () => words[Math.floor(Math.random() * words.length)] ).join(' ') } const list = Array.from({ length: LIST_SIZE }, () => ({ title: randomSentence(4), description: randomSentence(12), category: randomSentence(2), tags: randomSentence(6) })) // -- Benchmark indexing -- const indexStart = performance.now() const fuse = new Fuse(list, OPTIONS) const indexTime = performance.now() - indexStart // -- Benchmark search (average over multiple runs) -- const searchStart = performance.now() for (let i = 0; i < SEARCH_RUNS; i++) { fuse.search(QUERY) } const searchTime = (performance.now() - searchStart) / SEARCH_RUNS // -- Results -- console.log(`List size: ${LIST_SIZE.toLocaleString()} items`) console.log(`Keys: ${KEYS.join(', ')}`) console.log(`Index time: ${indexTime.toFixed(2)}ms`) console.log(`Search time: ${searchTime.toFixed(2)}ms (avg over ${SEARCH_RUNS} runs)`) console.log(`Results: ${fuse.search(QUERY).length} matches`) ``` -------------------------------- ### Pre-build Fuse.js Index Source: https://www.fusejs.io/performance.html If indexing time is a concern for large datasets during page load, pre-build the index using Fuse.createIndex() and pass it to the Fuse constructor. ```javascript const index = Fuse.createIndex(keys, list) const fuse = new Fuse(list, options, index) ``` -------------------------------- ### Import Fuse.js using CommonJS Source: https://www.fusejs.io/getting-started.html Import the Fuse.js library for use in CommonJS environments. ```js const Fuse = require('fuse.js') ``` -------------------------------- ### Bitap Algorithm: Create Pattern Alphabet Source: https://www.fusejs.io/articles/how-fuzzy-search-works.html Generates bitmasks for each character in the pattern. Used in the Bitap algorithm for exact matching. ```javascript createPatternAlphabet() { const alphabet = {}; for (let i = 0; i < this.pattern.length; i++) { const char = this.pattern[i]; alphabet[char] = (alphabet[char] || 0) | (1 << i); } return alphabet; } ``` -------------------------------- ### Enable Extended Search in Fuse.js Source: https://www.fusejs.io/extended-search.html Initialize Fuse.js with the `useExtendedSearch` option set to true to enable extended search operators. ```javascript const fuse = new Fuse(list, { useExtendedSearch: true, keys: ['title', 'author'] }) ``` -------------------------------- ### search(query, options?) Source: https://www.fusejs.io/web-workers.html Performs a search query across all workers and returns the results as a Promise. Supports the same query types as the standard Fuse class. ```APIDOC ## `search(query, options?)` js``` const results = await fuse.search('query') const limited = await fuse.search('query', { limit: 10 }) ``` Returns `Promise`. Supports the same query types as `Fuse`: strings, and expression objects (logical search). ``` -------------------------------- ### Import Fuse.js in Deno Source: https://www.fusejs.io/getting-started.html Import the Fuse.js library for use in a Deno environment, including type definitions. ```typescript // @deno-types="https://deno.land/x/fuse@v7.3.0/dist/fuse.d.ts" import Fuse from 'https://deno.land/x/fuse@v7.3.0/dist/fuse.min.mjs' ``` -------------------------------- ### Virtualized Rendering with React-Window Source: https://www.fusejs.io/articles/using-fuse-with-react.html For displaying many results, pair Fuse.js with a virtualization library like `react-window`. This renders only the visible rows, keeping the DOM size constant regardless of the result count. ```bash npm install react-window ``` ```jsx import { FixedSizeList } from 'react-window' function SearchResults({ results }) { // Only the visible rows are rendered — the rest are virtualized const Row = ({ index, style }) => (
{results[index].item.title}
) return ( {Row} ) } ``` -------------------------------- ### Import Fuse.js from CDN as ES Module Source: https://www.fusejs.io/getting-started.html Import Fuse.js directly from a CDN as an ES Module in your web project. ```html ``` -------------------------------- ### Import Fuse.js using ES Modules Source: https://www.fusejs.io/getting-started.html Import the Fuse.js library for use in ES Module environments. ```js import Fuse from 'fuse.js' ``` -------------------------------- ### Fuse.js and Semantic Search for Documentation Chatbot Source: https://www.fusejs.io/articles/vs-semantic-search.html Combines Fuse.js for instant, typo-tolerant search of known pages with semantic search for answering user questions. Fuse.js handles the initial filtering, while semantic search provides deeper understanding. ```javascript import Fuse from 'fuse.js' // Layer 1: Instant search-as-you-type for known pages const fuse = new Fuse(docs, { keys: ['title', 'headings', 'slug'], threshold: 0.3 }) function handleSearchInput(query) { // Fast fuzzy search — instant results as the user types return fuse.search(query).slice(0, 5) } // Layer 2: Semantic search when the user asks a question async function handleQuestion(question) { const embedding = await embed(question) const chunks = await vectorDB.query({ vector: embedding, topK: 10 }) return await llm.answer(question, chunks) } ``` -------------------------------- ### Providing Worker URL Manually Source: https://www.fusejs.io/web-workers.html If automatic resolution fails or for specific deployment scenarios, you can manually provide the path to the worker script. Ensure the script is accessible at the specified URL. ```javascript const fuse = new FuseWorker(docs, options, { workerUrl: '/static/fuse.worker.mjs' }) ``` -------------------------------- ### Adding Extended Search to Fuse.js Basic Build Source: https://www.fusejs.io/extended-search.html If using the basic build of Fuse.js, you can import and use the ExtendedSearch module to enable extended search functionality. ```javascript import Fuse from 'fuse.js/basic' import { ExtendedSearch } from 'fuse.js' Fuse.use(ExtendedSearch) ``` -------------------------------- ### Include Fuse.js via CDN Source: https://www.fusejs.io/getting-started.html Include Fuse.js in your HTML using a script tag from a CDN for direct use. ```html ``` -------------------------------- ### setCollection(docs) Source: https://www.fusejs.io/web-workers.html Replaces the entire dataset with a new array of documents. This operation redistributes the data across workers and rebuilds indexes. It's recommended over using `remove()` followed by additions. ```APIDOC ## `setCollection(docs)` js``` await fuse.setCollection(newDocs) ``` Replaces the entire dataset. Redistributes across workers and rebuilds indexes. Use this instead of `remove()` — filter your array, then call `setCollection`. ``` -------------------------------- ### Over-engineered API Search vs. Simple Fuse.js Search Source: https://www.fusejs.io/articles/vs-semantic-search.html Compares calling an external API for search with using Fuse.js for in-browser search. Use Fuse.js for simple lookups on smaller datasets to avoid unnecessary API calls and latency. ```javascript const response = await fetch('/api/search', { method: 'POST', body: JSON.stringify({ query: userInput }) }) // Server: embeds query → queries Pinecone → returns results // Total time: 300ms, cost: ~$0.001 per query ``` ```javascript const fuse = new Fuse(items, { keys: ['name', 'description'] }) const results = fuse.search(userInput) ``` -------------------------------- ### Logical Queries with Extended Search Source: https://www.fusejs.io/logical-search.html Enable `useExtendedSearch` to parse string values in logical expressions as extended search patterns, allowing for fuzzy matching, exact inclusion, and prefix/suffix matching. ```javascript const fuse = new Fuse(books, { useExtendedSearch: true, keys: ['title', 'color'] }) const result = fuse.search({ $and: [ { title: 'old war' }, // fuzzy match "old war" { color: "'blue" }, // exact include "blue" { $or: [ { title: '^lock' }, // starts with "lock" { title: '!arts' } // does not contain "arts" ] } ] }) ``` -------------------------------- ### FuseWorker Constructor Source: https://www.fusejs.io/web-workers.html Initializes a new FuseWorker instance. It takes the dataset, Fuse.js options, and optional worker-specific options. ```APIDOC ## Constructor js``` const fuse = new FuseWorker(docs, options?, workerOptions?) ``` * **`docs`**— Array of documents to search (same as `Fuse`) * **`options`**— Fuse.js options (same as `Fuse` : `keys`, `threshold`, `includeScore`, etc.) * **`workerOptions`**— Worker-specific options: Option| Type| Default| Description ---|---|---|--- `numWorkers`| `number`| `navigator.hardwareConcurrency` (max 8)| Number of parallel workers `workerUrl`| `string | URL`| Auto-resolved| Custom path to the worker script ``` -------------------------------- ### FuseWorker Constructor Options Source: https://www.fusejs.io/web-workers.html Configure the number of workers and the worker script URL when creating a new FuseWorker instance. ```javascript const fuse = new FuseWorker(docs, options?, workerOptions?) ``` -------------------------------- ### Basic Fuse.js Search Component in React Source: https://www.fusejs.io/articles/using-fuse-with-react.html A simple React component that filters a list of books based on user input using Fuse.js. It uses `useMemo` to optimize Fuse instance creation and falls back to the full list when the query is empty. ```jsx import { useMemo, useState } from 'react' import Fuse from 'fuse.js' const books = [ { title: 'The Great Gatsby', author: 'F. Scott Fitzgerald' }, { title: 'To Kill a Mockingbird', author: 'Harper Lee' }, { title: 'One Hundred Years of Solitude', author: 'Gabriel Garcia Marquez' }, { title: 'The Catcher in the Rye', author: 'J.D. Salinger' }, { title: 'Brave New World', author: 'Aldous Huxley' }, ] function BookSearch() { const [query, setQuery] = useState('') // Create the Fuse instance once — the index is built at construction time const fuse = useMemo(() => { return new Fuse(books, { keys: ['title', 'author'], // fields to search threshold: 0.4, // 0 = exact, 1 = match anything }) }, []) const results = query ? fuse.search(query) : [] // Show search results when there's a query, full list otherwise const displayItems = results.length > 0 ? results.map(({ item }) => item) : books return (
setQuery(e.target.value)} />
    {displayItems.map((book) => (
  • {book.title} — {book.author}
  • ))}
) } ``` -------------------------------- ### Importing Worker Script with Bundlers Source: https://www.fusejs.io/web-workers.html When using bundlers like Webpack, you can import the worker script directly. This is the recommended approach if your bundler supports it. ```javascript import workerUrl from 'fuse.js/worker-script' const fuse = new FuseWorker(docs, options, { workerUrl }) ``` -------------------------------- ### Complete Fuzzy Search Component for React Source: https://www.fusejs.io/articles/using-fuse-with-react.html This React component integrates Fuse.js for fuzzy searching. It includes a custom `useDebounce` hook for efficient input handling and a `highlightMatches` utility for displaying search results with highlighted matches. The Fuse instance is memoized using `useMemo` to prevent unnecessary re-creations. ```jsx import { useEffect, useMemo, useState } from 'react' import Fuse from 'fuse.js' function useDebounce(value, delay) { const [debounced, setDebounced] = useState(value) useEffect(() => { const timer = setTimeout(() => setDebounced(value), delay) return () => clearTimeout(timer) }, [value, delay]) return debounced } function highlightMatches(text, regions = []) { if (!regions.length) return text const chunks = [] let lastIndex = 0 for (const [start, end] of regions) { if (start > lastIndex) chunks.push(text.slice(lastIndex, start)) chunks.push({text.slice(start, end + 1)}) lastIndex = end + 1 } if (lastIndex < text.length) chunks.push(text.slice(lastIndex)) return chunks } function FuzzySearch({ items, keys, itemKey, placeholder = 'Search...' }) { const [query, setQuery] = useState('') const debouncedQuery = useDebounce(query, 200) // Recreate Fuse only when items or keys change const fuse = useMemo( () => new Fuse(items, { keys, includeMatches: true, threshold: 0.4 }), [items, keys] ) // Cap results to keep rendering fast const results = debouncedQuery ? fuse.search(debouncedQuery, { limit: 50 }) : [] return (
setQuery(e.target.value)} />
    {results.length > 0 ? results.map(({ item, matches }) => (
  • {keys.map((key) => { const match = matches?.find((m) => m.key === key) return ( {highlightMatches(item[key], match?.indices)}{' '} ) })}
  • )) : items.slice(0, 50).map((item) => (
  • {keys.map((key) => ( {item[key]} ))}
  • ))}
) } ``` -------------------------------- ### add(doc) Source: https://www.fusejs.io/web-workers.html Adds a single document to one of the worker shards using a round-robin distribution. This operation is asynchronous. ```APIDOC ## `add(doc)` js``` await fuse.add({ title: 'New Item', author: 'Jane' }) ``` Adds a document to one of the worker shards (round-robin distribution). ``` -------------------------------- ### Memoize Fuse.js Index in React Source: https://www.fusejs.io/articles/using-fuse-with-react.html Pre-build and cache the Fuse.js index using `useMemo` and `Fuse.createIndex()` for large datasets that change frequently. This prevents the index from being rebuilt on every component instance. ```jsx import { useMemo } from 'react' import Fuse from 'fuse.js' function useSearch(items, keys, query) { const fuse = useMemo(() => { // Pre-build the index so Fuse doesn't rebuild it on every new instance const index = Fuse.createIndex(keys, items) // pass pre-built index return new Fuse(items, { keys, threshold: 0.4 }, index) }, [items, keys]) return query ? fuse.search(query) : [] } ``` -------------------------------- ### Limit Search Results with Fuse.js Source: https://www.fusejs.io/articles/using-fuse-with-react.html To optimize performance with large lists, limit the number of results returned by Fuse.js. This is the simplest approach and works well when combined with other strategies. ```jsx const results = query ? fuse.search(query, { limit: 20 }) : [] ``` -------------------------------- ### Perform a Limited Search with FuseWorker Source: https://www.fusejs.io/web-workers.html Execute a search query using FuseWorker and specify a limit for the number of results returned. The search() method returns a Promise. ```javascript const results = await fuse.search('query') const limited = await fuse.search('query', { limit: 10 }) ``` -------------------------------- ### AND Operator Search Source: https://www.fusejs.io/logical-search.html Use the $and operator to find documents that match all specified clauses. It supports short-circuit evaluation. ```javascript const result = fuse.search({ $and: [{ author: 'abc' }, { title: 'xyz' }] }) ``` -------------------------------- ### OR Operator Search Source: https://www.fusejs.io/logical-search.html Use the $or operator to find documents that match any of the specified clauses. It supports short-circuit evaluation. ```javascript const result = fuse.search({ $or: [{ author: 'abc' }, { author: 'def' }] }) ``` -------------------------------- ### Dotted Keys Search with $path and $val Source: https://www.fusejs.io/logical-search.html When dealing with keys containing literal dots, use $path and $val within logical expressions to specify the exact key and value. ```javascript const books = [ { title: "Old Man's War", author: { 'first.name': 'John', 'last.name': 'Scalzi' } } ] const fuse = new Fuse(books, { keys: ['title', ['author', 'first.name'], ['author', 'last.name']] }) const result = fuse.search({ $and: [ { $path: ['author', 'first.name'], $val: 'jon' }, { $path: ['author', 'last.name'], $val: 'scazi' } ] }) ``` -------------------------------- ### Combining Extended Search with Logical Queries Source: https://www.fusejs.io/extended-search.html Extended search operators can be seamlessly integrated within Fuse.js's logical AND/OR queries for complex filtering. ```javascript fuse.search({ $and: [ { title: '^Old' }, // title starts with "Old" { author: "'Scalzi" } // author includes "Scalzi" ] }) ``` -------------------------------- ### Semantic Search Pseudocode Source: https://www.fusejs.io/articles/vs-semantic-search.html This pseudocode illustrates a semantic search query, requiring an embedding model and a vector database. It's suitable for natural language queries where understanding meaning is key. ```javascript // Pseudocode — requires an embedding model + vector database const embedding = await openai.embeddings.create({ model: 'text-embedding-3-small', input: 'lightweight search library' }) const results = await vectorDB.query({ vector: embedding.data[0].embedding, topK: 5 }) ``` -------------------------------- ### Fuse.js Extended Search Operators Source: https://www.fusejs.io/extended-search.html Fuse.js supports various operators for different matching types: fuzzy, exact, include, inverse exact, prefix exact, inverse prefix exact, suffix exact, and inverse suffix exact. ```javascript // Items that include "Man" AND "Old", OR end with "Artist" fuse.search("'Man 'Old | Artist$") ``` -------------------------------- ### Add a Document to FuseWorker Source: https://www.fusejs.io/web-workers.html Asynchronously add a new document to the dataset managed by FuseWorker. The document is added to one of the worker shards using a round-robin approach. ```javascript await fuse.add({ title: 'New Item', author: 'Jane' }) ``` -------------------------------- ### Debounced Search Component in React with Fuse.js Source: https://www.fusejs.io/articles/using-fuse-with-react.html A React component that implements debouncing for the search input to improve performance with larger datasets. It uses a custom `useDebounce` hook to delay Fuse.js searches until the user stops typing. ```jsx import { useEffect, useMemo, useState } from 'react' import Fuse from 'fuse.js' // Delays updating the value until the user stops typing function useDebounce(value, delay) { const [debounced, setDebounced] = useState(value) useEffect(() => { const timer = setTimeout(() => setDebounced(value), delay) return () => clearTimeout(timer) // reset timer on each keystroke }, [value, delay]) return debounced } function BookSearch({ books }) { const [query, setQuery] = useState('') const debouncedQuery = useDebounce(query, 200) // wait 200ms after last keystroke // Rebuild the Fuse instance when the book list changes const fuse = useMemo(() => { return new Fuse(books, { keys: ['title', 'author'], threshold: 0.4, }) }, [books]) // Search only fires after debounce settles const results = debouncedQuery ? fuse.search(debouncedQuery) : [] const displayItems = results.length > 0 ? results.map(({ item }) => item) : books return (
setQuery(e.target.value)} />
    {displayItems.map((book) => (
  • {book.title} — {book.author}
  • ))}
) } ``` -------------------------------- ### Using Double Quotes for Phrases in Fuse.js Source: https://www.fusejs.io/extended-search.html Enclose phrases containing spaces in double quotes to ensure they are matched as a single unit. ```javascript fuse.search('="scheme language"') // exact match for "scheme language" fuse.search("'^hello world") // include-match for "hello world" ``` -------------------------------- ### Update Inverted Index with Dynamic Collection Source: https://www.fusejs.io/token-search.html The inverted index used for token search is automatically maintained when documents are added or removed from the Fuse.js collection. This ensures search relevance remains up-to-date. ```javascript const fuse = new Fuse(docs, { useTokenSearch: true, keys: ['title'] }) // Adding a document updates the inverted index fuse.add({ title: 'New Book' }) // Removing documents also updates the index fuse.remove((doc) => doc.title === 'Old Book') ``` -------------------------------- ### Replace Dataset in FuseWorker Source: https://www.fusejs.io/web-workers.html Replace the entire dataset in FuseWorker with new documents. This operation redistributes the data across workers and rebuilds the indexes. ```javascript await fuse.setCollection(newDocs) ``` -------------------------------- ### terminate() Source: https://www.fusejs.io/web-workers.html Terminates all worker threads and cleans up associated resources. This method should always be called when the FuseWorker is no longer needed to prevent memory leaks. ```APIDOC ## `terminate()` js``` fuse.terminate() ``` Terminates all workers and cleans up resources. Always call this when you're done searching. ``` -------------------------------- ### Terminate FuseWorker Source: https://www.fusejs.io/web-workers.html Clean up resources by terminating all active Web Workers. This should be called when the FuseWorker is no longer needed. ```javascript fuse.terminate() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.