Spring Boot2.1.x integrates Elasticsearch8.x
- Preface
- Introduce dependencies
- Add configuration class
- code testing
-
- 1. Query all according to the index
- 2.Paging query
- 3. Multi-field word segmentation query
Foreword
Recently, because the project needs to use the full-text search function, and the project is springboot2, a new version used by es service, I checked the es official website and found that the official has given up on Java REST Client (High Level Rest Client (HLRC) in the old version in 7.15.0 )), thus replacing it with the recommended Java API Client 8.x, and using the RestClient tool according to the official website recommendation.
Introduce dependencies
- Since my project uses SpringBoot2.1.x version, the project will introduce the 6.4.3 version of es by default, so I need to manually add the dependent version number.
<properties> <elasticsearch.version>8.2.3</elasticsearch.version> <jakartajson.version>2.0.1</jakartajson.version> <httpclient.version>4.5.13</httpclient.version> </properties>
<dependencies> <!--elasticsearch dependency--> <dependency> <groupId>co.elastic.clients</groupId> <artifactId>elasticsearch-java</artifactId> <version>${elasticsearch.version}</version> <!--Ignore introduced dependencies due to version conflicts--> <exclusions> <exclusion> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-client</artifactId> </exclusion> <exclusion> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-client</artifactId> <version>${elasticsearch.version}</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>${httpclient.version}</version> </dependency> <dependency> <groupId>jakarta.json</groupId> <artifactId>jakarta.json-api</artifactId> <version>${jakartajson.version}</version> </dependency> </dependencies>
Add configuration class
import co.elastic.clients.elasticsearch.ElasticsearchAsyncClient; import co.elastic.clients.elasticsearch.ElasticsearchClient; import co.elastic.clients.json.jackson.JacksonJsonpMapper; import co.elastic.clients.transport.ElasticsearchTransport; import co.elastic.clients.transport.rest_client.RestClientTransport; import org.apache.http.Header; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.message.BasicHeader; import org.elasticsearch.client.RestClient; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class ElasticsearchConfig {<!-- --> @Value("${elasticsearch.scheme}") private String scheme; @Value("${elasticsearch.host}") private String host; @Value("${elasticsearch.port}") private int port; @Value("${elasticsearch.enable}") private boolean enable; @Value("${elasticsearch.username}") private String username; @Value("${elasticsearch.password}") private String password; //Inject IOC container @Bean public ElasticsearchClient elasticsearchClient(){<!-- --> ElasticsearchClient client = new ElasticsearchClient(null); if (enable){<!-- --> final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); if (username != null & amp; & amp; !username.isEmpty() & amp; & amp; password != null & amp; & amp; !password.isEmpty()) {<!-- --> //Set account password credentialsProvider.setCredentials( AuthScope.ANY, new UsernamePasswordCredentials(username, password)); } Header[] defaultHeaders = new Header[]{<!-- -->new BasicHeader("header", "value")}; RestClient restClient = RestClient.builder(new HttpHost(host, port, scheme)) .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)) .setDefaultHeaders(defaultHeaders) .build(); ElasticsearchTransport transport = new RestClientTransport(restClient,new JacksonJsonpMapper()); client = new ElasticsearchClient(transport); } return client; } //Inject IOC container @Bean public ElasticsearchAsyncClient elasticsearchAsyncClient(){<!-- --> ElasticsearchAsyncClient syncClient = new ElasticsearchAsyncClient(null); if (enable){<!-- --> final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); if (username != null & amp; & amp; !username.isEmpty() & amp; & amp; password != null & amp; & amp; !password.isEmpty()) {<!-- --> //Set account password credentialsProvider.setCredentials( AuthScope.ANY, new UsernamePasswordCredentials(username, password)); } Header[] defaultHeaders = new Header[]{<!-- -->new BasicHeader("header", "value")}; RestClient restClient = RestClient.builder(new HttpHost(host, port, scheme)) .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)) .setDefaultHeaders(defaultHeaders) .build(); ElasticsearchTransport transport = new RestClientTransport(restClient,new JacksonJsonpMapper()); syncClient = new ElasticsearchAsyncClient(transport); } return syncClient; } }
Code testing
@Autowired private ElasticsearchClient esClient;
1. Query all according to index
@Test public void matchDataTest() throws IOException {<!-- --> TrackHits.Builder trackHitsbuilder = new TrackHits.Builder();//Set whether to query accurately SearchResponse<Map> searchResponse = esClient.search(srBuilder -> srBuilder .trackTotalHits(trackHitsbuilder.enabled(true)//default false returns a total of 10000 .index("esTest") , Map.class); HitsMetadata<Map> hitsMetadata = searchResponse.hits(); System.out.println(hitsMetadata.total());//The total number returned by the file List<Hit<Map>> hitList = hitsMetadata.hits();//data }
2. Paging query
size keyword: Specifies the specified number of items to be returned in the query results. The default return value is 10.
from keyword: used to specify the starting return position. The default position is 0. Use it with the size keyword to achieve paging effect.
[Paging principle from * size + size]
@Test public void matchDataTest() throws IOException {<!-- --> TrackHits.Builder trackHitsbuilder = new TrackHits.Builder();//Set whether to query accurately SearchResponse<Map> searchResponse = esClient.search(srBuilder -> srBuilder .trackTotalHits(trackHitsbuilder.enabled(true)//default false returns a total of 10000 .index("esTest") .from(0) .size(20) , Map.class); HitsMetadata<Map> hitsMetadata = searchResponse.hits(); System.out.println(hitsMetadata.total());//The total number returned by the file List<Hit<Map>> hitList = hitsMetadata.hits();//data }
3. Multi-field word segmentation query
@Test public void matchDataTest() throws IOException {<!-- --> TrackHits.Builder trackHitsbuilder = new TrackHits.Builder();//Set whether to query accurately SearchResponse<Map> searchResponse = esClient.search(srBuilder -> srBuilder .trackTotalHits(trackHitsbuilder.enabled(true)//default false returns a total of 10000 .index("esTest") ..query(queryBuilder -> queryBuilder .multiMatch(matchQueryBuilder -> matchQueryBuilder .fields("name").query("Zhang San"))) .from(0) .size(20) , Map.class); HitsMetadata<Map> hitsMetadata = searchResponse.hits(); System.out.println(hitsMetadata.total());//The total number returned by the file List<Hit<Map>> hitList = hitsMetadata.hits();//data }