[개선 방법 배우기] Elastic search7.6 예제

서문 : ES 버전 반복이 너무 빠르며 es5, es6 및 es7의 차이는 여전히 상대적으로 큽니다. https://blog.csdn.net/chenghuanhuaning/article/details/105235006을 참조하십시오.

여기서 장황하지 않고 예제로 이동하십시오. 그건 그렇고, 내가 손으로 두드린 데모 비용을 지불하십시오.

https://github.com/javaSunson/es7.6demo.git

1. 치어 의존성

<!-es 核心 jar 包-> 
<dependency> 
    <groupId> org.elasticsearch </ groupId> 
    <artifactId> elasticsearch </ artifactId> 
</ dependency> 
<dependency> 
    <groupId> org.springframework.boot </ groupId > 
    <artifactId> spring-boot-starter-data-elasticsearch </ artifactId> 
</ dependency> 

<dependency> 
    <groupId> org.springframework.data </ ​​groupId> 
    <artifactId> spring-data-elasticsearch </ artifactId> 
</ dependency> 
<!-注意
    版本-> 
<dependency> <groupId> org.elasticsearch.client </ groupId> 
    <artifactId>elasticsearch-rest-high-level-client </ artifactId> 
    <version> 7.6.1 </ version> 
</ dependency>
<! 
    -https://mvnrepository.com/artifact/com.google.code.gson/gson- > 
<dependency> 
    <groupId> com.google.code.gson </ groupId> <artifactId> gson </ artifactId > 
    <버전> 2.8.6 </ 버전> 
</ dependency>

 2. pom-properties (기본 Springboot 2.x 또는 es6 버전, 버전을 수동으로 지정해야합니다. 여기에 통합 된 상위 버전이 있습니다.)

 

<properties> 
    <java.version> 1.8 </java.version> 
    <!-버전은 es와 일치합니다 
    .--> 
< elasticsearch.version> 7.6.1 </elasticsearch.version> </ properties>

 

3. 구성

package com.hmwl.myes.config;

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;

/**
 * @author martin
 * @version 1.0
 * @name: ElasticConfig
 * @date: 2021/2/1 9:08
 * @description 注意将配置放置到配置中心配置
 **/
@Configuration
public class ElasticConfig {
    @Bean
    public RestHighLevelClient restHighLevelClient(){
        RestHighLevelClient client = new RestHighLevelClient(
                // 构建者支持 单机 和 集群配置。
                RestClient.builder(
                        new HttpHost("localhost", 19201, "http")));

            return client;
        }

}

 예:

package com.hmwl.myes;

import com.google.gson.Gson;
import entity.User;
import org.apache.lucene.util.QueryBuilder;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
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.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.net.UnknownServiceException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SpringBootTest
class MyesApplicationTests {

    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Test
    void contextLoads() throws IOException {
        CreateIndexRequest createIndexRequest = new CreateIndexRequest("user2");
        CreateIndexResponse indexResponse = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
        System.out.println(indexResponse.toString());
    }
    /**
     * 测试索引是否存在
     */
    @Test
    void testExistIndex() throws IOException {
        GetIndexRequest request = new GetIndexRequest("user2");
        boolean exist = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
        System.out.println("索引是否存在:"+exist);
    }

    /**
     * 测试indexAPi
     */
    @Test
    public void testIndexApi(){
        Map<String, Object> param = new HashMap<>();
        param.put("name","martin");
        param.put("code","11111111");
        param.put("job","programer");

    }

    /**
     * 删除index
     */
    @Test
    public void deleteIndex() throws IOException {
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("user2");
        AcknowledgedResponse delete = restHighLevelClient.indices().delete(deleteIndexRequest,RequestOptions.DEFAULT);
        System.out.println(delete.isAcknowledged());
    }
    /********************* 文档操作 ***************************/
    @Test
    public void createNewDocuments() throws IOException {
        User user = new User("1111","martin","25");
        IndexRequest indexRequest = new IndexRequest("user1");
        indexRequest.id("1");
        indexRequest.timeout("1s");
        Gson gson = new Gson();
        indexRequest.source(gson.toJson(user),XContentType.JSON);
        IndexResponse index = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        System.out.println("创建文档结果:"+index.status());
    }
    /**
     * 判断文档是否存在
     */
    @Test
    public void testExistDocument() throws IOException {
        GetRequest request = new GetRequest("user1", "2");
        boolean exists = restHighLevelClient.exists(request, RequestOptions.DEFAULT);
        System.out.println("文档是否存在:"+exists);
    }
    /**
     * 获取文档
     */
    @Test
    void testGetDocument() throws IOException {
        GetRequest request = new GetRequest("user1","1");
        GetResponse doc = restHighLevelClient.get(request, RequestOptions.DEFAULT);
        System.out.println(doc.getSourceAsString());
    }
    /***
     * 修改文档
     */
    @Test
    public void updateDocument() throws IOException {
        User user = new User();
        user.setAge("18");
        UpdateRequest request = new UpdateRequest("user1","1");
        request.timeout(TimeValue.MINUS_ONE);
        Gson gson = new Gson();
        request.doc(gson.toJson(user),XContentType.JSON);
        UpdateResponse result = restHighLevelClient.update(request, RequestOptions.DEFAULT);
        System.out.println(result);
    }
    /**
     * 测试删除文档
     */
    @Test
    void testDeleteDocument() throws IOException {
        DeleteRequest request = new DeleteRequest("user1","1");
        request.timeout("1s");
        DeleteResponse result = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
        System.out.println(result);
    }

    /**
     * 批量插入文档
     */
    @Test
    public void testBatchAddDocument() throws IOException {
        List<User> userList = new ArrayList<>();
        userList.add(new User("222","张三","11"));
        userList.add(new User("223","张四","11"));
        userList.add(new User("224","张五","11"));
        userList.add(new User("225","张刘","11"));
        userList.add(new User("226","张七","11"));
        userList.add(new User("227","张八","11"));
        Gson gson = new Gson();
        BulkRequest request = new BulkRequest();
        request.timeout("1s");
        for(int i =0;i<userList.size();i++){
            request.add(new IndexRequest("user1").
                    id(""+(i+1)).
                    source(gson.toJson(userList.get(i)),XContentType.JSON));
            BulkResponse result = restHighLevelClient.bulk(request,RequestOptions.DEFAULT);
            System.out.println(result.status());
        }

    }
    /**
     * 查询文档
     */
    @Test
    public void searchDocument() throws IOException {
        SearchRequest request = new SearchRequest("user1");
        // builder condition 构建查询条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 高亮
        sourceBuilder.highlighter();
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "张四");
        sourceBuilder.query(termQueryBuilder);
        sourceBuilder.timeout(new TimeValue(6000));
        request.source(sourceBuilder);
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        for (SearchHit hit:
             response.getHits().getHits()) {
            System.out.println(hit.getSourceAsMap());
        }
    }

}

Mad God Java 덕분에 

참조 웹 사이트 : https://blog.csdn.net/mgdj25/article/details/105740191 , https://blog.csdn.net/lisen01070107/article/details/108288037

참조 비디오 : https://www.bilibili.com/video/BV17a4y1x7zq

추천

출처blog.csdn.net/qq_26834611/article/details/113572396