Connection configuration, principle and use of Elasticsearch in Spring Boot

Connection configuration, principle and use of Elasticsearch in Spring Boot

introduction

Elasticsearch is an open source distributed search and data analysis engine, which can be used in application scenarios such as full-text search, structured search, and analysis. In Spring Boot, we can search and analyze data through Elasticsearch. This article will introduce the connection configuration, principle and usage of Elasticsearch in Spring Boot.

insert image description here

Elasticsearch connection configuration

In Spring Boot, we can use it by introducing Elasticsearch dependency. Add the following dependencies to the pom.xml file:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

Then add the configuration of Elasticsearch in the application.properties or application.yml file:

spring.data.elasticsearch.cluster-name=my-application
spring.data.elasticsearch.cluster-nodes=localhost:9300

In the above configuration, cluster-namethe name of the Elasticsearch cluster is specified, and cluster-nodesthe address and port number of the Elasticsearch node are specified.

In addition, if you need to use the security features of Elasticsearch, you can add the following configuration:

spring.data.elasticsearch.repositories.enabled=true
spring.data.elasticsearch.cluster-nodes=localhost:9300
spring.data.elasticsearch.cluster-name=my-application
spring.data.elasticsearch.username=elastic
spring.data.elasticsearch.password=changeme

In the above configuration, spring.data.elasticsearch.repositories.enabledthe Elasticsearch-enabled repository is specified, spring.data.elasticsearch.usernameand spring.data.elasticsearch.passwordthe Elasticsearch username and password are specified. Of course, this requires corresponding configuration in Elasticsearch.

Elasticsearch connection principle

When using Elasticsearch connection in Spring Boot, you need to use the Elasticsearch Java client to connect to the Elasticsearch cluster. The Java client of Elasticsearch uses TransportClient or NodeClient to connect to the Elasticsearch cluster.

When using TransportClient to connect to the Elasticsearch cluster, you need to specify the address and port number of the Elasticsearch node. TransportClient will randomly select an available node to connect to, and automatically retry to connect to other nodes when the connection fails. After the connection is successful, TransportClient will establish a TCP connection with the Elasticsearch cluster and communicate with it through this connection.

When using NodeClient to connect to the Elasticsearch cluster, you need to start a node in the application, which will communicate with other nodes in the Elasticsearch cluster. NodeClient communicates with the local node using the Java API, and then forwards requests to other nodes in the Elasticsearch cluster. This approach reduces network communication costs and improves query and index performance.

How to use Elasticsearch

In Spring Boot, we can use Elasticsearch by injecting ElasticsearchTemplateor ElasticsearchRestTemplate. Both classes implement ElasticsearchOperationsthe interface and provide various operations on Elasticsearch.

ElasticsearchTemplate

ElasticsearchTemplateIt is a way to operate the Elasticsearch cluster provided by the Elasticsearch Java client. It provides a large number of methods, including indexing, updating, deleting, searching and other operations.

Here is an ElasticsearchTemplateexample of searching using:

@Autowired
private ElasticsearchTemplate elasticsearchTemplate;

public List<Article> searchArticle(String keyword) {
    
    
    QueryBuilder queryBuilder = QueryBuilders.matchQuery("title", keyword);
    NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
            .withQuery(queryBuilder)
            .build();
    SearchHits<Article> searchHits = elasticsearchTemplate.search(searchQuery, Article.class);
    return Arrays.stream(searchHits.getHits())
            .map(SearchHit::getContent)
            .collect(Collectors.toList());
}

In the above code, we first QueryBuildercreated a query condition, and then NativeSearchQueryBuildercreated a search request. Finally, the method we use ElasticsearchTemplateperforms searchthe search and converts the results into a list of Article objects.

ElasticsearchRestTemplate

ElasticsearchRestTemplateIt is a way to operate the Elasticsearch cluster provided by Spring Data Elasticsearch. It provides a large number of methods, including indexing, updating, deleting, searching and other operations. The difference ElasticsearchTemplateis that ElasticsearchRestTemplatethe REST API is used to communicate with the Elasticsearch cluster.

Here is an ElasticsearchRestTemplateexample of indexing using:

@Autowired
private ElasticsearchRestTemplate elasticsearchRestTemplate;

public void indexArticle(Article article) {
    
    
    IndexQuery indexQuery = new IndexQueryBuilder()
            .withObject(article)
            .build();
    elasticsearchRestTemplate.index(indexQuery, IndexCoordinates.of("articles"));
}

In the above code, we first IndexQueryBuildercreate an index request, and then use ElasticsearchRestTemplatethe indexmethod to perform the index operation, and save the Article object to the index named "articles".

in conclusion

This article introduces the connection configuration, principle and usage of Elasticsearch in Spring Boot. When using Elasticsearch, we need to pay attention to some configuration and usage details, such as specifying the name and node address of the Elasticsearch cluster, selecting an appropriate Java client, and so on. Through the introduction of this article, we hope readers can better understand how to use Elasticsearch in Spring Boot and apply it more flexibly in projects.

Guess you like

Origin blog.csdn.net/2301_77835649/article/details/131487799