Elasticsearch Clients document

Spring Boot integrates with ES

Java REST Client [7.10] Java High Level REST Client

  • Finding native dependencies
    <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>elasticsearch-rest-high-level-client</artifactId>
        <version>7.10.2</version>
    </dependency>
Copy the code
  • To find the object
RestHighLevelClient client = new RestHighLevelClient(
        RestClient.builder(
                new HttpHost("localhost".9200."http"),
                new HttpHost("localhost".9201."http")));

// Close when finished
client.close();
Copy the code

Configuration base project issue: Make sure that the dependencies we import are consistent with our ES version

ElasticSearchConfig

  • ElasticSearchConfig
/** * find the object ** put it in Spring to use ** *@author mxz
 */
@Configuration
public class ElasticSearchConfig {

    @Bean
    public RestHighLevelClient restHighLevelClient(a) {
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost".9200."http")));
// new HttpHost("localhost", 9201, "http")));
        returnclient; }}Copy the code
  • Index test code
package cn.com.codingce;

import cn.com.codingce.config.ElasticSearchConfig;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;

@SpringBootTest
class CodingceEsApiApplicationTests {

    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient client;

    @Test
    void contextLoads(a) throws IOException {
        // Create index
        CreateIndexRequest request = new CreateIndexRequest("codingce_index");
        // Execute the create request, IndicesClient, request and get the response
        CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
        System.out.println(createIndexResponse);
    }

    // Test to get index
    @Test
    void testExistIndex(a) throws IOException {
        GetIndexRequest request = new GetIndexRequest("codingce_index");
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);

    }


    // Test to delete index
    @Test
    void testDeleteIndex(a) throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest("codingce_index"); AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT); System.out.println(delete.isAcknowledged()); }}Copy the code

Test the basic operations of the document

  • Entity class
package cn.com.codingce.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;

/ * * *@author mxz
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@Component
public class User {
    private String name;
    private int age;
}
Copy the code
  • The test code
// Test adding documentation
    @Test
    void testAddDocument(a) throws IOException {
        User u = new User("Full Stack Self-learning Community".3);
        // Create the request
        IndexRequest request = new IndexRequest("codingce_index");

        // Put codingce_index/_doc/1
        request.id("1");
        // 1s
        request.timeout(TimeValue.timeValueSeconds(1));

        // Put our data into the request JSON
        IndexRequest source = request.source(JSON.toJSONString(u), XContentType.JSON);

        // The client sends the request
        IndexResponse index = client.index(request, RequestOptions.DEFAULT);

        System.out.println(index.toString());
        System.out.println(index.status()); // Success is CREATE
    }

    // Check whether the document exists first
    @Test
    void testIsExists(a) throws IOException {
        GetRequest request = new GetRequest("codingce_index"."1");
        // Do not get the context of the _source returned
        request.fetchSourceContext(new FetchSourceContext(false));
        request.storedFields("_none_");


        boolean exists = client.exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);
    }

    // Obtain the document information after determining the existence
    @Test
    void testGetDocument(a) throws IOException {
        GetRequest request = new GetRequest("codingce_index"."1");

        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        System.out.println(response.getSourceAsString());
        System.out.println(response);
    }

    @Test
    void testUpdateDocument(a) throws IOException {
        UpdateRequest updateRequest = new UpdateRequest("codingce_index"."1");
        updateRequest.timeout(TimeValue.timeValueSeconds(1));
        User u = new User("Full Stack Self-learning Community".4);
        updateRequest.doc(JSON.toJSONString(u), XContentType.JSON);


        UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);
        System.out.println(updateResponse);
        System.out.println(updateResponse.status());
    }

    @Test
    void testDeleteDocument(a) throws IOException {
        DeleteRequest deleteRequest = new DeleteRequest("codingce_index"."1");
        deleteRequest.timeout(TimeValue.timeValueSeconds(1));

        DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT);
        System.out.println(deleteResponse.toString());
        System.out.println(deleteResponse.status());
    }


    // Batch insert
    @Test
    void testAddDocuments(a) throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout(TimeValue.timeValueSeconds(10));

        List<User> list = new ArrayList<>();
        list.add(new User("Full Stack Self-learning Community 1".1));
        list.add(new User("Full Stack Self-taught Community 2".2));
        list.add(new User("Full Stack Self-taught Community 3".3));
        list.add(new User("Full Stack Self-taught Community 4".4));
        list.add(new User("Full Stack Self-taught Community 5".5));
        list.add(new User("Full Stack Self-taught Community 6".6));
        list.add(new User("Full Stack Self-taught Community 7".7));
        list.add(new User("Full Stack Self-taught Community 8".8));

        for (int i = 0; i < list.size(); i++) {
            // Batch update and batch delete, modify the corresponding request here
            bulkRequest.add(new IndexRequest("codingce_index")
                    .id("" + (i + 1))
                    .source(JSON.toJSONString(list.get(i)), XContentType.JSON));
        }
        BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(bulkResponse.toString());
        System.out.println(bulkResponse.hasFailures());
    }

    // Batch query
    // SearchRequest indicates the SearchRequest
    // SearchSourceBuilder conditional construct
    @Test
    void testSearchAll(a) throws IOException {
        SearchRequest searchRequest = new SearchRequest(ES_INDEX);

        // Query criteria can use the QueryBuilders tool class
        // termQuery Indicates an exact match
// TermQueryBuilder TermQueryBuilder = QueryBuilders. TermQuery ("name", "full stack Self study community 1");
        MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();


        // Build the search criteria
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();


        searchSourceBuilder.query(matchAllQueryBuilder);
// searchSourceBuilder.timeout(TimeValue.timeValueSeconds(60));
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        searchSourceBuilder.from();
        searchSourceBuilder.size();

        searchRequest.source(searchSourceBuilder);


        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        System.out.println(JSON.toJSONString(searchResponse.getHits()));
        for(SearchHit hit : searchResponse.getHits().getHits()) { System.out.println(hit.getSourceAsMap()); }}Copy the code

This article has been uploaded to gitee gitee.com/codingce/he… Project address: github.com/xzMhehe/cod…