Home Web Front-end JS Tutorial How to use React and Elasticsearch to achieve efficient full-text retrieval

How to use React and Elasticsearch to achieve efficient full-text retrieval

Sep 27, 2023 pm 04:00 PM
react elasticsearch Full Text Search

How to use React and Elasticsearch to achieve efficient full-text retrieval

How to use React and Elasticsearch to achieve efficient full-text retrieval

Introduction:
With the advent of the era of information explosion, full-text retrieval has become an efficient way to obtain and A way to manage large amounts of information. React and Elasticsearch are both very popular technologies at the moment, and their combination can help us achieve efficient full-text search functions. This article will introduce in detail how to use React and Elasticsearch to implement full-text retrieval, and provide specific code examples.

  1. Install and configure Elasticsearch

First, we need to install and configure Elasticsearch. You can go to the Elasticsearch official website (https://www.elastic.co/cn/downloads/elasticsearch) to download the installation package suitable for your operating system, and install and configure it according to the official documentation. Once completed, start the Elasticsearch service.

  1. Create React Project

Before we start, we need to create a React project. Open the command line and execute the following command:

npx create-react-app search-demo
cd search-demo
npm start
Copy after login

At this point, a new React project has been created and started.

  1. Install and configure the Elasticsearch plug-in

In the root directory of the React project, execute the following command to install the elasticsearch plug-in:

npm install @elastic/elasticsearch
Copy after login

Then create it in the src directory An elasticsearch.js file and add the following code:

import { Client } from '@elastic/elasticsearch';

const client = new Client({ node: 'http://localhost:9200' });

export default client;
Copy after login

In this way we have completed the installation and configuration of Elasticsearch.

  1. Create search component

Create the Search.js file in the src directory and add the following code:

import React, { useState } from 'react';
import client from './elasticsearch';

function Search() {
  const [searchTerm, setSearchTerm] = useState('');
  const [searchResults, setSearchResults] = useState([]);

  const handleSearch = async () => {
    const response = await client.search({
      index: 'your_index_name',
      body: {
        query: {
          match: {
            content: searchTerm
          }
        }
      }
    });

    const hits = response.body.hits.hits;
    setSearchResults(hits);
  };

  return (
    <div>
      <input
        type="text"
        value={searchTerm}
        onChange={e => setSearchTerm(e.target.value)}
      />
      <button onClick={handleSearch}>搜索</button>

      {searchResults.map(result => (
        <div key={result._id}>{result._source.content}</div>
      ))}
    </div>
  );
}

export default Search;
Copy after login

In the above code, we first The elasticsearch module was introduced and a Search component was created. This component contains an input box and a search button, as well as divs used to display search results. In the handleSearch function, we obtain the search results by calling the elasticsearch search interface and update the searchResults status.

  1. Use the search component in App.js

Open the App.js file and add the following code to it:

import React from 'react';
import Search from './Search';

function App() {
  return (
    <div>
      <Search />
    </div>
  );
}

export default App;
Copy after login

So we are The Search component is introduced in the App component.

  1. Run the project

Now, you can run the React project through the command line.

npm start
Copy after login

Open the browser and visit http://localhost:3000, you will see a page containing a search input box. Enter keywords in the input box and click the search button to get the search results.

Conclusion:
Through the above steps, we successfully used React and Elasticsearch to implement efficient full-text retrieval function. React provides a platform for quickly building UI, while Elasticsearch provides a powerful full-text search engine. Their combination allows us to easily develop powerful full-text search applications. I hope this article can be helpful to readers and can play a greater role in practice.

Reference materials:

  • React official documentation: https://reactjs.org/
  • Elasticsearch official documentation: https://www.elastic.co/ guide/index.html

The above is the detailed content of How to use React and Elasticsearch to achieve efficient full-text retrieval. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP, Vue and React: How to choose the most suitable front-end framework? PHP, Vue and React: How to choose the most suitable front-end framework? Mar 15, 2024 pm 05:48 PM

PHP, Vue and React: How to choose the most suitable front-end framework? With the continuous development of Internet technology, front-end frameworks play a vital role in Web development. PHP, Vue and React are three representative front-end frameworks, each with its own unique characteristics and advantages. When choosing which front-end framework to use, developers need to make an informed decision based on project needs, team skills, and personal preferences. This article will compare the characteristics and uses of the three front-end frameworks PHP, Vue and React.

Integration of Java framework and front-end React framework Integration of Java framework and front-end React framework Jun 01, 2024 pm 03:16 PM

Integration of Java framework and React framework: Steps: Set up the back-end Java framework. Create project structure. Configure build tools. Create React applications. Write REST API endpoints. Configure the communication mechanism. Practical case (SpringBoot+React): Java code: Define RESTfulAPI controller. React code: Get and display the data returned by the API.

In-depth study of Elasticsearch query syntax and practical combat In-depth study of Elasticsearch query syntax and practical combat Oct 03, 2023 am 08:42 AM

In-depth study of Elasticsearch query syntax and practical introduction: Elasticsearch is an open source search engine based on Lucene. It is mainly used for distributed search and analysis. It is widely used in full-text search of large-scale data, log analysis, recommendation systems and other scenarios. When using Elasticsearch for data query, flexible use of query syntax is the key to improving query efficiency. This article will delve into the Elasticsearch query syntax and give it based on actual cases.

Log analysis and exception monitoring based on Elasticsearch in PHP Log analysis and exception monitoring based on Elasticsearch in PHP Oct 03, 2023 am 10:03 AM

Summary of log analysis and exception monitoring based on Elasticsearch in PHP: This article will introduce how to use the Elasticsearch database for log analysis and exception monitoring. Through concise PHP code examples, it shows how to connect to the Elasticsearch database, write log data to the database, and use Elasticsearch's powerful query function to analyze and monitor anomalies in the logs. Introduction: Log analysis and exception monitoring are

Vue.js vs. React: Project-Specific Considerations Vue.js vs. React: Project-Specific Considerations Apr 09, 2025 am 12:01 AM

Vue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.

What closures does react have? What closures does react have? Oct 27, 2023 pm 03:11 PM

React has closures such as event handling functions, useEffect and useCallback, higher-order components, etc. Detailed introduction: 1. Event handling function closure: In React, when we define an event handling function in a component, the function will form a closure and can access the status and properties within the component scope. In this way, the state and properties of the component can be used in the event processing function to implement interactive logic; 2. Closures in useEffect and useCallback, etc.

React's Role in HTML: Enhancing User Experience React's Role in HTML: Enhancing User Experience Apr 09, 2025 am 12:11 AM

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

Common Elasticsearch performance optimization tips in PHP development Common Elasticsearch performance optimization tips in PHP development Oct 03, 2023 am 08:43 AM

Summary of common Elasticsearch performance optimization tips in PHP development: Elasticsearch is a popular open source search engine with powerful search and analysis capabilities. In PHP development, we often use Elasticsearch as data storage and search engine. However, as the amount of data increases, the search speed may slow down, so performance optimization is very important. This article will introduce some common Elasticsearch

See all articles