Quick environment setup

  1. Import dependence
<properties> # Since the default version is inconsistent with the version we have, we need to customize the version of es <elasticsearch.version>7.121.</elasticsearch.version>
</properties>

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
Copy the code
  1. Register with Spring
@Configuration
public class ElasticSearch_Config {
    @Bean
    public RestHighLevelClient restHighLevelClient(a){
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        // Configure a non-cluster configuration
                        new HttpHost("localhost".9200."http"),
                        new HttpHost("localhost".9201."http")));
        returnclient; }}Copy the code

The API test

1. Create an index

@SpringBootTest
class DemoApplicationTests {
	@Resource(name="restHighLevelClient")
	private RestHighLevelClient client;
	@Test
	void contextLoads(a) throws IOException {
		// 1. Create a request to create index
		CreateIndexRequest request = new CreateIndexRequest("spring-es-test");
		//2. The client processes the request and returns a response
		CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
		//3. View the responseSystem.out.println(response); }}Copy the code

2. Obtain indexes

We can only determine if an index exists

@Test
	void contextLoads_2(a) throws IOException {
		// 1. Create a request to fetch the index
		GetIndexRequest request = new GetIndexRequest("spring-es-test");
		//2. The client processes the request and returns a response
		boolean bool = client.indices().exists(request,RequestOptions.DEFAULT);
		//3. View the response
		System.out.println(bool);
	}
Copy the code

3. Delete indexes

@Test
	void contextLoads_3(a) throws IOException {
		// 1. Create a drop index request
		DeleteIndexRequest request = new DeleteIndexRequest("spring-es-test");
		//2. The client processes the request and returns a response
		AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT);
		//3. View the response
		System.out.println(delete.isAcknowledged());
	}
Copy the code

4. Document operation CRUD

1. Add documents

        @Test
	void contextLoads_4(a) throws IOException {
		// Create an object
		User user = new User("Meet".18);
		// Create the request
		IndexRequest request=new IndexRequest("spring-es-test");
		// put spring-es-test/_doc/1
		request.id("1");
		request.timeout("1s");
		// Provide the data source as a JSON string
		request.source(JSON.toJSONString(user), XContentType.JSON);
		IndexResponse index = client.index(request, RequestOptions.DEFAULT);
		System.out.println(index.toString());
		System.out.println(index.status());

	}
Copy the code

2. Obtain documents

StoredFields and fetchSourceContext

@Test
	void contextLoads_5(a) throws IOException {
		// Create the request
		GetRequest request=new GetRequest("spring-es-test"."1");
		Get spring-es-test/_doc/1
		// Let FetchSourceContext be set for this request to control whether and how _source should be returned.
                // Do not perform field filtering
		//request.fetchSourceContext(new FetchSourceContext(false));
		// Explicitly specify the storage field to be returned. By default, the _source field is returned.
		// Returns only if the field's store(default false) is true
                //request.storedFields("_type");
		System.out.println(client.exists(request, RequestOptions.DEFAULT));
		GetResponse response = client.get(request, RequestOptions.DEFAULT);
		System.out.println(response.getSourceAsString());
		System.out.println(response);

	}
        
true
{"age":18."name":"Meet"}
{"_index":"spring-es-test"."_type":"_doc"."_id":"1"."_version":1."_seq_no":0."_primary_term":1."found":true."_source": {"age":18."name":"Meet"}}
Copy the code

3. Update documents

@Test
void contextLoads_6(a) throws IOException {
	// Create the request
	UpdateRequest request=new UpdateRequest("spring-es-test"."1");
	request.timeout("1s");
	User user = new User("Meet".20);
	request.doc(JSON.toJSONString(user), XContentType.JSON);
	UpdateResponse update = client.update(request, RequestOptions.DEFAULT);
	System.out.println(update.toString());
	System.out.println(update.status());
}
UpdateResponse[index=spring-es-test,type=_doc,id=1,version=2,seqNo=1,primaryTerm=1,result=updated,shards=ShardInfo{total=2, successful=1, failures=[]}]
OK
Copy the code

4. Delete the document

       @Test
void contextLoads_7(a) throws IOException {
	// Create the request
	DeleteRequest request=new DeleteRequest("spring-es-test"."1");
	request.timeout("1s");
	DeleteResponse delete = client.delete(request, RequestOptions.DEFAULT);
	System.out.println(delete.toString());
	System.out.println(delete.status());
}
DeleteResponse[index=spring-es-test,type=_doc,id=1,version=3,result=deleted,shards=ShardInfo{total=2, successful=1, failures=[]}]
OK
Copy the code

The batch operation

  1. Batch add
@Test
void contextLoads_8(a) throws IOException {
	BulkRequest bulkRequest=new BulkRequest();
	bulkRequest.timeout("10s");
	ArrayList<User> userlist=new ArrayList<>();
	userlist.add(new User("Meet 1".18));
	userlist.add(new User("Meet 2".19));
	userlist.add(new User("Meet 3".20));
	userlist.add(new User("Meet 4".21));
	for (int i=0; i<userlist.size(); i++) { bulkRequest.add(new IndexRequest("spring-es-test")
				.id(""+(i+1))
				.source(JSON.toJSONString(userlist.get(i)),XContentType.JSON));
	}
	BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
	// With or without failure, false represents success
	System.out.println(bulk.hasFailures());
}
Copy the code
  1. Batch delete

Similar to adding, just change the method in the for loop

  1. Batch query
@Test
void contextLoads_9(a) throws IOException {
	SearchRequest request=new SearchRequest("spring-es-test");
	SearchSourceBuilder sourceBuilder=new SearchSourceBuilder();
	// Use the QueryBuilders utility class to build query criteria
	/ / QueryBuilders termQuery precise matching
	/ / QueryBuilders matchAllQuery match all
	QueryBuilder queryBuilder= QueryBuilders.termQuery("name.keyword"."Meet 1");
	sourceBuilder.timeout(new TimeValue(10, TimeUnit.SECONDS));
	sourceBuilder.query(queryBuilder);
	request.source(sourceBuilder);

	SearchResponse search = client.search(request, RequestOptions.DEFAULT);
	System.out.println(JSON.toJSONString(search.getHits()));
	System.out.println(search.status());
	System.out.println("= = = = = = = = = = = = = = = = = = = = = = = = = = = = =");
	for (SearchHit documentFields:search.getHits().getHits())
		System.out.println(documentFields.getSourceAsMap());
}
Copy the code

Small talk

In a static inner class ElasticsearchRestClientAutoConfiguration classes are automatically configured for us this object, use can also be directly. ConditionalOnMissingBean you can no longer use this class if you are already registered

@Configuration(proxyBeanMethods = false)
	@ConditionalOnMissingBean(RestHighLevelClient.class)
	static class RestHighLevelClientConfiguration {

		@Bean
		RestHighLevelClient elasticsearchRestHighLevelClient(RestClientBuilder restClientBuilder) {
			return newRestHighLevelClient(restClientBuilder); }}Copy the code