Java实战 - 简单使用

说明: 本次演示版本:SpringBoot 2.4.1,Elasticsearch 7.6.1

注意: 使用时引入的Maven包、安装的Elasticsearch、kibana版本必须一致

一. 引入Maven依赖

<!-- Elasticsearch包start:第一个包第一阶段未用 -->
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.6.1</version>
</dependency>
<!-- Elasticsearch包end -->

二. 设置链接时使用的参数

package com.example.spring_boot_demo.utils;

/**
 * @author :zhangbocong
 * @version :V1.0
 * @program :spring_boot_demo
 * @date :Created in 2020年12月28日 0:30
 * @description :业务使用地址
 */
public class ApiCountUtils {
    /**
     * @Author zhangbocong
     * @Description Elasticsearch 地址
     * @Date 2020/12/29
     */
    public static final String ELASTIC_SEARCH_URL = "127.0.0.1";

    /**
     * @Author zhangbocong
     * @Description Elasticsearch 端口号
     * @Date 2020/12/29
     */
    public static final Integer ELASTIC_SEARCH_PORT = 9200;

    /**
     * @Author zhangbocong
     * @Description Elasticsearch 使用的协议
     * @Date 2020/12/30
     */
    public static final String ELASTIC_SEARCH_SCHEMA = "http";

}

三. 设置ElasticsearchConfig - 设置链接

package com.example.spring_boot_demo.config;

import com.example.spring_boot_demo.utils.ApiCountUtils;
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 :zhangbocong
 * @version :V1.0
 * @program :spring_boot_demo
 * @date :Created in 2020年12月29日 15:48
 * @description :Elasticsearch 链接配置 - 方法1
 */
@Configuration
public class ElasticsearchConfig {
    @Bean
    public RestHighLevelClient restHighLevelClient() {
        return new RestHighLevelClient(
            RestClient.builder(
                //有几个集群写几个!! 逗号(",")间隔
                new HttpHost(ApiCountUtils.ELASTIC_SEARCH_URL, ApiCountUtils.ELASTIC_SEARCH_PORT, ApiCountUtils.ELASTIC_SEARCH_SCHEMA)
            )
        );
    }
}

四. 设置ElasticsearchEntity参数

package com.example.spring_boot_demo.vo;

import lombok.Data;

/**
 * @author :zhangbocong
 * @version :V1.0
 * @program :spring_boot_demo
 * @date :Created in 2020年12月29日 9:34
 * @description :Elasticsearch 参数
 */
@Data
public class ElasticsearchEntity {
    /**
     * 姓名
     */
    private String userName;

    /**
     * 年龄
     */
    private int age;
}

五. ES的基本使用方法 - 此教程通过Postman进行测试

package com.example.spring_boot_demo.controller;

import com.alibaba.fastjson.JSON;
import com.example.spring_boot_demo.vo.ElasticsearchEntity;
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.text.Text;
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.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author :zhangbocong
 * @version :V1.0
 * @program :spring_boot_demo
 * @date :Created in 2020年12月31日 8:51
 * @description :Elasticsearch 7.6.1 功能测试
 */
@RestController
@RequestMapping("ElasticsearchDemo")
public class ElasticsearchDemo {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * @Author zhangbocong
     * @Description 创建索引
     * @Date 2020/12/30
     * @Param []
     * @Return void
     */
    @RequestMapping("createIndex")
    void createIndex() throws IOException {
        //创建索引请求
        CreateIndexRequest index = new CreateIndexRequest("hcode_index"); //hcode_index为索引名
        //执行请求,获得响应
        CreateIndexResponse response = restHighLevelClient.indices().create(index, RequestOptions.DEFAULT);
        System.out.println(response);
    }

    /**
     * @Author zhangbocong
     * @Description 判断索引是否存在
     * @Date 2020/12/30
     * @Param []
     * @Return void
     */
    @RequestMapping("ExistIndex")
    void ExistIndex() throws IOException {
        GetIndexRequest request = new GetIndexRequest("hcode_index");
        boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);
    }

    /**
     * @Author zhangbocong
     * @Description 删除索引
     * @Date 2020/12/30
     * @Param []
     * @Return void
     */
    @RequestMapping("DeleteIndex")
    void DeleteIndex() throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest("hcode_index");
        AcknowledgedResponse delete = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
        System.out.println(delete.isAcknowledged()); //为true表示删除成功
    }

    /**
     * @Author zhangbocong
     * @Description 添加文档
     * @Date 2020/12/30
     * @Param []
     * @Return void
     */
    @RequestMapping("AddDocument")
    void AddDocument() throws IOException {
        ElasticsearchEntity user = new ElasticsearchEntity();
        user.setAge(22);
        user.setUserName("hcode");
        //创建索引请求
        IndexRequest request = new IndexRequest("hcode_index");
        //设置规则 例如相当于 PUT /hcode_index/_doc/1 命令
        request.id("1").timeout(TimeValue.timeValueSeconds(1));//设置id,1秒超时
        request.timeout("1s");

        // 数据转换成json 放入请求
        request.source(JSON.toJSONString(user), XContentType.JSON);

        //将请求发出去,获取响应结果
        IndexResponse indexResponse = restHighLevelClient.index(request, RequestOptions.DEFAULT);

        System.out.println(indexResponse.status()); // 返回当前操作的类型:CREATE
        System.out.println(indexResponse.toString()); //响应内容
    }

    /**
     * @Author zhangbocong
     * @Description 判断文档是否存在
     * @Date 2020/12/30
     * @Param []
     * @Return void
     */
    @RequestMapping("IsExists")
    void IsExists() throws IOException {
        GetRequest getRequest = new GetRequest("hcode_index", "1");
        // 不获取返回的_source 的上下文,会提高速度
        getRequest.fetchSourceContext(new FetchSourceContext(false));
        getRequest.storedFields("_none_");
        boolean exists = restHighLevelClient.exists(getRequest, RequestOptions.DEFAULT);
        System.out.println(exists);
    }

    /**
     * @Author zhangbocong
     * @Description 相当于  GET /hcode_index/_doc/1
     * @Date 2020/12/30
     * @Param []
     * @Return void
     */
    @RequestMapping("getDocument")
    void getDocument() throws IOException {
        GetRequest getRequest = new GetRequest("hcode_index", "1");
        GetResponse response = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
        System.out.println(response.getSourceAsString()); //获取文档的内容
    }

    /**
     * @Author zhangbocong
     * @Description 更新文档信息
     * @Date 2020/12/30
     * @Param []
     * @Return void
     */
    @RequestMapping("updateDocument")
    void updateDocument() throws IOException {
        UpdateRequest request = new UpdateRequest("hcode_index", "1");

        request.timeout("1s");
        ElasticsearchEntity user = new ElasticsearchEntity();
        user.setAge(18);
        user.setUserName("hhhzzz");
        request.doc(JSON.toJSONString(user), XContentType.JSON);

        UpdateResponse response = restHighLevelClient.update(request, RequestOptions.DEFAULT);
        System.out.println(response.status()); //成功返回 OK
        System.out.println(response.toString());
    }

    /**
     * @Author zhangbocong
     * @Description 删除文档信息
     * @Date 2020/12/30
     * @Param []
     * @Return void
     */
    @RequestMapping("deleteDocument")
    void deleteDocument() throws IOException {
        DeleteRequest request = new DeleteRequest("hcode_index", "1");
        request.timeout("1s");
        DeleteResponse response = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
        System.out.println(response.status()); //成功返回 OK
        System.out.println(response.toString());
    }

    /**
     * @Author zhangbocong
     * @Description 批量操作
     * @Date 2020/12/30
     * @Param []
     * @Return void
     */
    @RequestMapping("BulkRequest")
    void BulkRequest() throws IOException {
        BulkRequest request = new BulkRequest();
        request.timeout("10s");
        ArrayList<Object> list = new ArrayList<>();
        ElasticsearchEntity user = new ElasticsearchEntity();
        user.setAge(18);
        user.setUserName("hhhzzz");
        list.add(user);

        ElasticsearchEntity user1 = new ElasticsearchEntity();
        user.setAge(22);
        user.setUserName("ddddd");
        list.add(user1);

        ElasticsearchEntity user2 = new ElasticsearchEntity();
        user.setAge(11);
        user.setUserName("ydouth");
        list.add(user2);

        //批量请求,批量更新,删除都差不多!!!不设置id就会自动生成随机id,演示为批量插入
        for (int i = 0; i < list.size(); i++) {
            request.add(new IndexRequest("hcode_index")
                    .id("" + (i + 1))
                    .source(JSON.toJSONString(list.get(i)), XContentType.JSON));
        }

        BulkResponse response = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
        System.out.println(response.hasFailures());//是否失败,false表示成功,true表示失败
    }

    /**
     * @Author zhangbocong
     * @Description 搜索查询+高亮
     * @Date 2020/12/31
     * @Param []
     * @Return void
     */
    @RequestMapping("Query")
    void Query() throws IOException {
        SearchRequest request = new SearchRequest();
        //创建查询条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 使用QueryBuilders工具,精确查询term
        //QueryBuilders.matchAllQuery() 匹配所有
        TermQueryBuilder termQuery = QueryBuilders.termQuery("name", "hcode");

        //配置高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("name"); //绑定属性
        highlightBuilder.requireFieldMatch(false); //关闭多个高亮,只显示一个高亮
        highlightBuilder.preTags("<p style='color:red'>"); //设置前缀
        highlightBuilder.postTags("</p>"); //设置后缀
        sourceBuilder.highlighter(highlightBuilder);

        sourceBuilder.query(termQuery);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        request.source(sourceBuilder);

        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);

        //获取结果对象
        SearchHits hits = response.getHits();

        System.out.println(JSON.toJSONString(hits));

        for (SearchHit searchHit : hits) {
            //获取高亮的html
            Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
            HighlightField name = highlightFields.get("name");

            //替换原有的字段
            Map<String, Object> sourceAsMap = searchHit.getSourceAsMap();

            if (name != null) {
                Text[] fragments = name.fragments();
                String light_name = "";
                for (Text fragment : fragments) {
                    light_name += fragment;
                }
                sourceAsMap.put("name", light_name); //进行替换
            }


            System.out.println(searchHit.getSourceAsMap());
        }
    }

}