“This is the 25th day of my participation in the Gwen Challenge in November. See details: The Last Gwen Challenge in 2021”

1. SpringBoot integrates ES

Create a new Spring Boot project and add the ElasticSearch module:

2. Modify the ES version

As you can see, the ES version imported by SpringBoot is 7.12.1:

The version we use locally is 7.8.0, so in order to prevent ES connection failure, we need to change the version number to be consistent with the local.

<! -- Add to the properties property of the pom.xml file: -->
<elasticsearch.version>7.8.0</elasticsearch.version>
Copy the code

Make sure the modification succeeds.

3. Write a configuration file

package com.cheng;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.client.RestClients;

@Configuration
public class ElasticSearchClientConfig {


    // Configure RestHighLevelClient to rely on the Spring container to be used later
    @Bean
    public RestHighLevelClient restHighLevelClient(a){
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        // Bind the host, port, and protocol. If it is an ES cluster, configure multiple
                        new HttpHost("127.0.0.1".9200."http")));
        returnclient; }}Copy the code

Now that ElasticSearch and SpringBoot integration are complete, here’s how to use the index and document apis.

Java REST Client

Java REST Clients come in two styles:

  • Java Low Level REST Client: an official low-level Client for Elasticsearch. It allows communication with the Elasticsearch cluster over HTTP. Leave request orchestration and response unorchestration to the user. It is compatible with all versions of Elasticsearch.
  • Java High Level REST Client: The official advanced Client for Elasticsearch. It is based on low-level clients, provides many apis, and is responsible for choreography of requests and unchoreography of responses.
  • The official recommendation is to use the Java High Level REST Client, which performs HTTP requests rather than serial Number Java requests.

The following test uses a Java advanced client.

2, index API operation details

Create indexes

    // Create an index test
    @Test
    void contextLoads(a) throws IOException {
        // A request to create an index
        CreateIndexRequest request = new CreateIndexRequest("wanli");
        // Execute the request to create the index and return a response
        CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
        // Prints the response
        System.out.println(response); //org.elasticsearch.client.indices.CreateIndexResponse@6ce3e00
    }
Copy the code

All apis in RestHighLevelClient accept RequestOptions, which you can use to customize the request without changing how Elasticsearch executes the request. For example, you can specify a node selector here to control which node receives requests.

Check whether the index exists

    // If the index exists, return true if it does, false if it does not
    @Test
    public void test1(a) throws IOException {
        GetIndexRequest request = new GetIndexRequest("wanli_index");
        boolean b = client.indices().exists(request, RequestOptions.DEFAULT);
        System.out.println(b); //true
    }
Copy the code

Remove the index

    // Drop index
    @Test
    public void test2(a) throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest("wanli_index");
        AcknowledgedResponse response = client.indices().delete(request,RequestOptions.DEFAULT);
        System.out.println(response.isAcknowledged()); // Returns true
    }
Copy the code

3. Detailed explanation of API operation of the document

Add the document

Entity class:

@Component
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private String name;
    private int age;
}
Copy the code

Add documentation code:

    @Test
    public void test3(a) throws IOException {

        User user = new User("Thousands of miles".3);

        // Create the request
        IndexRequest request = new IndexRequest("wanli_index");

        request
                .id("1")  // Document id, do not specify the default id
                .timeout(TimeValue.timeValueSeconds(1))// Fragment timeout
                .source(JSON.toJSONString(user), XContentType.JSON); // Set the document source to the index and convert the user object to a JSON string

        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
        System.out.println(response.toString());        //IndexResponse[index=wanli_index,type=_doc,id=1,version=1,result=created,seqNo=0,primaryTerm=1,shards={"total":2,"succe ssful":1,"failed":0}]

        System.out.println(response.status());//CREATED Specifies the operation status
    }
Copy the code

Determine whether the document exists

    // Check whether the document exists
    @Test
    public void test4(a) throws IOException {
        // Construct a new GET request for the specified index and document ID
        GetRequest request = new GetRequest("wanli_index"."1");
        
        String[] includes = Strings.EMPTY_ARRAY;
        String[] excludes = new String[]{"age"};// gets information about the document containing age in _source
        //fetchSourceContext Specifies the context of the field to be returned. It provides more comprehensive filtering logic, including, exclude, and full text filtering.
        request.fetchSourceContext(new FetchSourceContext(true, includes, excludes));

        boolean b = client.exists(request, RequestOptions.DEFAULT);
        System.out.println(b); / / true existence
    }
Copy the code

Obtaining Document Information

    // Get the document information
    @Test
    public void test5(a) throws IOException {
        GetRequest request = new GetRequest("wanli_index"."1");

        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        System.out.println(response.toString());//{"_index":"wanli_index","_type":"_doc","_id":"1","_version":1,"_seq_no":0,"_primary_term":1,"found":true,"_source":{"a Ge ": 3," name ":" wanli "}}

        System.out.println(response.getSource());// get _source: {name= wanli, age=3}
        System.out.println(response.getVersion());/ / 1
        System.out.println(response);//{"_index":"wanli_index","_type":"_doc","_id":"1","_version":1,"_seq_no":0,"_primary_term":1,"found":true,"_source":{"a Ge ": 3," name ":" wanli "}}
        
    }
Copy the code

Modifying Document Information

    // Modify the document information
    @Test
    public void test6(a) throws IOException {
        UpdateRequest request = new UpdateRequest("wanli_index"."1");
        request.timeout("1s");
        User user = new User("Gods".18);

        // fill in the specific content and document format
        request.doc(JSON.toJSONString(user),XContentType.JSON);

        UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
        System.out.println(response.status()); // If ok is returned, the operation succeeded
    }
Copy the code

Delete the document

    // Delete the document
    @Test
    public void test7(a) throws IOException {

        DeleteRequest request = new DeleteRequest("wanli_index"."1");
        request.timeout("1s");
        DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
        System.out.println(response.status());// If ok is returned, the operation succeeded
    }
Copy the code

Batch Insert documents

BulkRequest: Bulk requests contain ordered IndexRequest, DeleteRequest, and UpdateRequest and allow it to be executed in a single batch. Please note that we only support batch requests and not refresh per item.

   // Insert documents in batches
    @Test
    public void test8(a) throws IOException {
        BulkRequest request = new BulkRequest();

        request.timeout("10s");

        ArrayList<User> list = new ArrayList<>();

        list.add(new User("shenming1".3));
        list.add(new User("shenming2".3));
        list.add(new User("shenming3".3));
        list.add(new User("shenming4".3));
        list.add(new User("shenming5".3));

        for (int i = 0; i < list.size(); i++) {
            request.add(
                   new IndexRequest("wanli_index")
                    .id(""+(i+1))
                    .source(JSON.toJSONString(list.get(i)),XContentType.JSON));
        }
            BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
            System.out.println(response.status()); //ok

    }
Copy the code

Invoke the following methods based on your specific requirements.

Complex query operation

SearchRequest = new SearchRequest(“wanli_index”);

2, build the search criteria: SearchSourceBuilder sourceBuilder = SearchSourceBuilder. SearchSource ();

3, add query criteria to request: request.source(sourceBuilder);

SearchResponse response = client.search(request, requestOptions.default);

@Test
public void test9(a) throws IOException {
    // Build the query request
    SearchRequest request = new SearchRequest("wanli_index");

    // Build the search criteria
    SearchSourceBuilder sourceBuilder = SearchSourceBuilder.searchSource();
    
    // Set the highlight
    //HighlightBuilder highlightBuilder = new HighlightBuilder();
    //highlightBuilder.field("name");
    //highlightBuilder.preTags("<span style='color:red'>");
    //highlightBuilder.postTags("</span>");
    //searchSourceBuilder.highlighter(highlightBuilder);
    / / page:
    //sourceBuilder.from(0);
    //sourceBuilder.size(10);

    The QueryBuilders utility class implements the build of query criteria
    / / QueryBuilders termQuery precise queries
    / / QueryBuilders matchAllQuery match all ()
    TermQueryBuilder queryBuilder = QueryBuilders.termQuery("name"."shenming1");
    sourceBuilder.query(queryBuilder);// Add the exact query criteria to the search criteria
    sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));// Set the timeout period

    // Put the query criteria into the request
    request.source(sourceBuilder);

    // Execute the request
    SearchResponse response = client.search(request, RequestOptions.DEFAULT);
    // Prints the result of the search
    System.out.println(JSON.toJSONString(response.getHits()));
    //{"fragment":true,"hits":[{"fields":{},"fragment":false,"highlightFields":{},"id":"1","matchedQueries":[],"primaryTerm" : 0, "rawSortValues" : [], "score" : 1.1727202, "seqNo" : 2, "sortValues" : [], "sourceAsMap" : {" name ":" shenming1 ", "age" : 3}, "sourceAsS Tring ":" {\ "age \" : 3, \ "name \" : \ "shenming1 \"} ", "sourceRef" : {" fragments ": true}," type ":" _doc ", "version" : 1}], "maxScore" : 1.1727 202,"totalHits":{"relation":"EQUAL_TO","value":1}}


    System.out.println("= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =");
    for (SearchHit searchHit : response.getHits().getHits()) {
        System.out.println(searchHit.getSourceAsMap());//{name=shenming1, age=3}}}Copy the code