SoFunction
Updated on 2025-03-10

Use to achieve efficient fuzzy search

In modern web applications, it is crucial to implement efficient search capabilities. Whether you are developing an e-commerce website, blogging platform, or other types of applications, helping users quickly find the information they need is a key feature. is a powerful JavaScript library that provides flexible fuzzy search and text matching capabilities, allowing you to easily achieve an excellent search experience.

What is ?

It is a lightweight JavaScript library that focuses on implementing fuzzy search and text matching functions. It uses an approximate string matching algorithm to quickly find matches in large datasets, while also supporting advanced search options and custom configurations.

Install

You can install using npm or yarn:

npm install 
# oryarn add 

Basic usage examples

Let's start with a basic example and introduce the basic usage of . Suppose we have an array of multiple books and want to do a fuzzy search by the title.

// Importconst Fuse = require('');

// Sample data - an array of multiple objectsconst books = [
  { title: 'JavaScript: The Good Parts' },
  { title: 'Eloquent JavaScript' },
  { title: 'JavaScript: The Definitive Guide' },
  { title: 'Learning JavaScript Design Patterns' },
  { title: 'You Don't Know JS' },
];

// Create an instance and configure search optionsconst options = {
  keys: ['title'], // Search key, only search for the 'title' attribute here};

const fuse = new Fuse(books, options);

// Perform fuzzy searchconst result = ('JavaScript');

// Output search results(result);

In this example, we first import the library. Then we create an array containing multiple book objectsbooks. Next, we create an instance, configure the search option, and specify the key to search (here is'title'property). Finally, we usesearchThe method performs a fuzzy search and'JavaScript'Pass it as a search term and output the search results.

The search results will be an array of matching book objects, with the degree of matching controlled by the default threshold.

Advanced usage examples

Not only does it support basic fuzzy searches, it also offers a wealth of advanced options to meet a variety of needs. Here are some advanced usage examples:

Customize search options

You can configure various options for the instance to suit your needs. For example, you can specify matching thresholds, weights for search keys, sorting rules, and more.

const options = {
  keys: ['title', 'author'], // Multiple search keys  threshold: 0.6, // Threshold controls the sensitivity of matching  shouldSort: true, // Whether to sort the results  location: 0, // Match position, 0 means the beginning match  distance: 100, // Maximum distance to search  minMatchCharLength: 2, // Minimum matching character length};

Custom search functions

You can also define custom search functions to control the search logic more accurately. For example, you can implement a custom search function to handle special search requirements.

const customSearchFunction = (pattern, options) => {
  // Custom search logic  // Return an array of matches};

const fuse = new Fuse(data, { customSearch: customSearchFunction });

Advanced example: Real-time search

Real-time search interaction with the user interface, such as dynamically displaying search results in the input box.

// Listen to input box changesconst inputElement = ('searchInput');
('input', (event) => {
  const searchTerm = ;
  
  // Perform fuzzy search  const result = (searchTerm);
  
  // Update the search results display  renderSearchResults(result);
});

In this example, we listen for changes in the input box, perform a fuzzy search every time the content of the input box changes, and update the display of the search results.

Practical applications: Real-time association function with React

In this practical application example, we will explore how to use React to implement a real-time association function to provide a better user search experience. We will create a React component with an input box where users will get search suggestions related to their input in real time as they enter.

Step 1: Install and React

First, make sure your React project is configured and run. Then, install and the necessary dependencies:

npm install 

Step 2: Create React Components

Create a React component that accepts user input and displays search suggestions. Here is the basic structure of an example component:

import React, { useState } from 'react';
import Fuse from '';

const SearchSuggestions = ({ data }) => {
  const [searchTerm, setSearchTerm] = useState('');
  const [suggestions, setSuggestions] = useState([]);

  // Create an instance and configure search options  const options = {
    keys: ['name'], // Search key    threshold: 0.4, // Threshold controls the sensitivity of matching  };

  const fuse = new Fuse(data, options);

  // Handle input box changes  const handleInputChange = (event) => {
    const { value } = ;
    setSearchTerm(value);

    // Perform fuzzy search    const result = (value);

    // Update search suggestions    setSuggestions(result);
  };

  return (
    <div>
      <input
        type="text"
        placeholder="search..."
        value={searchTerm}
        onChange={handleInputChange}
      />
      <ul>
        {((item, index) => (
          <li key={index}>{}</li>
        ))}
      </ul>
    </div>
  );
};

export default SearchSuggestions;

Step 3: Use Real-time Search

In the above code, we created a namedSearchSuggestionsReact component. This component contains an input box and a list showing search suggestions. When the user enters content, we perform a fuzzy search using it and update the list of suggestions based on the search results.

First, we created an instance and configured the search options. Then, we enter the input boxonChangePerform a fuzzy search in the event handler to store the search results insuggestionsstate and render these suggestions in the list.

Step 4: Use components in your application

You can now use it in your React appSearchSuggestionsComponents. Pass data to components for search suggestions. For example:

import React from 'react';
import ReactDOM from 'react-dom';
import SearchSuggestions from './SearchSuggestions';

const data = [
  { name: 'JavaScript: The Good Parts' },
  { name: 'Eloquent JavaScript' },
  { name: 'JavaScript: The Definitive Guide' },
  { name: 'Learning JavaScript Design Patterns' },
  { name: 'You Don't Know JS' },
];

(
  <SearchSuggestions data={data} />,
  ('root')
);

This will render a search input box in your app that contains real-time association functionality.

summary

By combining   and React, you can easily implement real-time association features to provide a better search experience. This practical application example shows you how to create a React component that will be integrated with so that users can get relevant search suggestions when entering. This feature is very useful for a variety of web applications, especially e-commerce websites and blogging platforms.

Once you have mastered this example, you can further customize and optimize your search capabilities according to your project needs to improve the user experience. The combination of React provides a powerful tool for developing efficient search capabilities.

Summarize

is a powerful JavaScript library that can be used to implement efficient fuzzy search and text matching functions. It offers a wealth of configuration options and advanced features that enable you to adapt to a variety of search needs. Whether you are developing an e-commerce website, blog platform, or other types of applications, using it can help users quickly find the information they need and improve the user experience.

The above is the detailed content of using efficient fuzzy search. For more information about fuzzy search, please pay attention to my other related articles!