With the explosive growth of information, it is increasingly difficult for users to quickly obtain the information they need. In this case, providing full-text search functionality has become one of the must-have features for every website and application. In this article, we will introduce how to implement full-text search functionality in an application using the Spring Boot framework and the Elasticsearch database.
What is Elasticsearch?
Elasticsearch is an open source distributed search engine that enables easy data analysis and real-time search. It is based on the Apache Lucene search engine library and provides a RESTful API that allows developers to easily access its functionality. Almost any type of data can be stored and searched using Elasticsearch, including structured, unstructured, and geospatial data.
Integration of Spring Boot and Elasticsearch
Spring Boot is a framework for building independent, production-based Spring applications. It simplifies the development of Spring applications through automatic configuration and a convention-over-configuration approach. For integrating with Elasticsearch, Spring Boot provides some default configuration and customization options out of the box.
First, we need to add the dependency of Elasticsearch to the Spring Boot application. Add the following dependencies in the build.gradle file:
dependencies {
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-data-elasticsearch', version: '2.5.0'
}
After adding this dependency, we can easily use the Repository mode of the Spring Data Elasticsearch library Define models and indexes. Spring Data Elasticsearch provides us with many classes and methods to operate Elasticsearch from the application. We also need to set the Elasticsearch connection configuration in the Spring Boot application's configuration file. We can add the following configuration in the application.properties file:
// Set the address and port of elasticsearch
spring.data.elasticsearch.cluster-nodes=localhost:9200
// Set the elasticsearch username and password (if authentication is required)
spring.data.elasticsearch.properties.username=elasticsearch
spring.data.elasticsearch.properties.password=password
Define the index and Type
Before using Elasticsearch for full-text search, we need to first define the index and type. In Elasticsearch, an index is equivalent to a database, and a type is equivalent to a table in the database. We can use the annotations provided in Spring Data Elasticsearch to define our entities and indexes. The following is a simple example:
// Define entity
@Document(indexName = "articles")
public class Article {
// 定义id @Id private String id; // 定义标题 @Field(type = FieldType.Text) private String title; // 定义内容 @Field(type = FieldType.Text) private String content; // 定义创建时间 @Field(type = FieldType.Date) private Date createTime; // 省略get和set方法
}
In the above example, we used the @Document annotation to define our entities and indexes. We created an index with indexName as articles and used the @Field annotation to annotate the fields in our entities that need to be saved to Elasticsearch. Next, we can create an interface to ArticleRepository, which inherits from the ElasticsearchRepository class. This interface can provide a large number of data query methods based on Elasticsearch through inheritance. The following is a simple example:
public interface ArticleRepository extends ElasticsearchRepository42407456a0fce5117f6e0cdb707509c6 {
List<Article> findByTitle(String title);
}
For the ArticleRepository interface defined in the above example, Spring Data Elasticsearch will automatically create a concrete entity class that implements the service layer interface for us, and automatically inject it into the Spring container for us when the application starts. In this service interface, we have defined a findByTitle method, which is used to query articles based on their titles. In actual use, we can easily operate Elasticsearch through ArticleRepository, including adding, deleting, querying, etc.
Implementation of full-text search function
After we define entities, indexes and types, we can start full-text search operations on them. In Elasticsearch, full-text search functionality is implemented by creating queries. Querying is the process of performing a search within specified indexes, types, and fields. The following is a simple example:
public interface ArticleRepository extends ElasticsearchRepository42407456a0fce5117f6e0cdb707509c6 {
List<Article> searchArticle(String keyword);
}
In this example, we define a searchArticle method to Search for articles. In this method, we can use Elasticsearch's QueryBuilder builder to build query conditions, as follows:
public List59da28f5dfb08cc4320eedd48bbc94b6 searchArticle(String keyword) {
NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder(); builder.withQuery(QueryBuilders.boolQuery() .should(QueryBuilders.matchQuery("title", keyword)) .should(QueryBuilders.matchQuery("content", keyword))); return elasticsearchTemplate.queryForList(builder.build(), Article.class);
}
Here, we use a NativeSearchQueryBuilder to create the query. We can use QueryBuilders to build different types of queries. Here, we use a Boolean query to match articles that contain keywords in their titles and content. After the query is built, we can use elasticsearchTemplate.queryForList() to execute the query and obtain the results. Of course, we can also use various query methods provided by Spring Data Elasticsearch to perform query operations.
Summarize
In this article, we introduce how to use Spring Boot and Elasticsearch to implement full-text search functionality. We first introduced the basic knowledge of Elasticsearch and the integration method of Spring Boot and Elasticsearch, and then explained in detail how to define indexes and types, and implement the full-text search function. After studying this article, we can easily integrate the full-text search function into our Spring Boot application, so that users can find the required information faster.
The above is the detailed content of Implement full-text search functionality using Spring Boot and Elasticsearch. For more information, please follow other related articles on the PHP Chinese website!