Search Functionality with Elasticsearch and Next.js

Search Functionality with Elasticsearch and Next.js

Implementing powerful search capabilities is crucial for enhancing user experience and content discovery. In this tutorial, we’ll explore how to integrate Elasticsearch with your Next.js application to add efficient search functionality.

Setting Up Elasticsearch

Step 1: Install and Run Elasticsearch

If you haven’t already, download and install Elasticsearch on your server or use a cloud-based Elasticsearch service.

Step 2: Create an Index

Create an index in Elasticsearch to store the data you want to search. For example, let’s create an index named articles:

PUT /articles
{
  "mappings": {
    "properties": {
      "title": { "type": "text" },
      "content": { "type": "text" }
    }
  }
}

Step 3: Index Data

Index some sample data into the articles index:

POST /articles/_doc/1
{
  "title": "Getting Started with Elasticsearch",
  "content": "Learn the basics of Elasticsearch and how to get started."
}

POST /articles/_doc/2
{
  "title": "Advanced Elasticsearch Techniques",
  "content": "Explore advanced techniques and features of Elasticsearch for powerful search."
}

Integrating Elasticsearch with Next.js

Step 1: Install Dependencies

Install the @elastic/elasticsearch library for interacting with Elasticsearch in your Next.js app:

npm install @elastic/elasticsearch

Step 2: Create a SearchComponent

Create a new component, for example, SearchComponent.js:

// components/SearchComponent.js

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

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

const SearchComponent = () => {
  const [searchTerm, setSearchTerm] = useState('');
  const [searchResults, setSearchResults] = useState([]);

  const handleSearch = async () => {
    try {
      const { body } = await elasticsearchClient.search({
        index: 'articles',
        body: {
          query: {
            match: {
              title: searchTerm,
            },
          },
        },
      });

      setSearchResults(body.hits.hits);
    } catch (error) {
      console.error('Error searching:', error);
    }
  };

  return (
    <div>
      <h1>Search Functionality with Elasticsearch and Next.js</h1>
      <input
        type="text"
        value={searchTerm}
        onChange={(e) => setSearchTerm(e.target.value)}
        placeholder="Search for articles..."
      />
      <button onClick={handleSearch}>Search</button>
      <ul>
        {searchResults.map((result) => (
          <li key={result._id}>{result._source.title}</li>
        ))}
      </ul>
      {/* Your page content goes here */}
    </div>
  );
};

export default SearchComponent;

Step 3: Add SearchComponent to Your Pages

Integrate the SearchComponent into your Next.js pages or components where search functionality is desired.

// pages/index.js

import SearchComponent from '../components/SearchComponent';

const SearchPage = () => {
  return (
    <div>
      <SearchComponent />
      {/* Your page content goes here */}
    </div>
  );
};

export default SearchPage;

Conclusion

Integrating Elasticsearch with your Next.js application enables powerful and efficient search functionality. By following these steps, you can enhance user experience by providing a robust search feature for your content.

In the upcoming tutorials, we’ll explore more advanced topics, including integrating with external services and building a dynamic blog with Next.js and MDX.

Stay tuned for the next tutorial where we’ll focus on creating a dynamic and flexible blog using Next.js and MDX.

Happy coding and Elasticsearch-powered search in Next.js!


© 2023. All rights reserved.