陈凯凯 3 years ago
parent
commit
798b7833b7
38 changed files with 2641 additions and 0 deletions
  1. 138 0
      pom.xml
  2. 21 0
      src/main/java/com/example/Application.java
  3. 54 0
      src/main/java/com/example/common/ResponseBean.java
  4. 76 0
      src/main/java/com/example/config/ExceptionAdvice.java
  5. 61 0
      src/main/java/com/example/config/RestClientConfig.java
  6. 31 0
      src/main/java/com/example/config/WebMvcConfig.java
  7. 11 0
      src/main/java/com/example/constant/Constant.java
  8. 373 0
      src/main/java/com/example/controller/HighLevelRestController.java
  9. 146 0
      src/main/java/com/example/controller/IndexController.java
  10. 287 0
      src/main/java/com/example/controller/LowLevelRestController.java
  11. 98 0
      src/main/java/com/example/controller/test.java
  12. 10 0
      src/main/java/com/example/dao/EsDemoMapper.java
  13. 11 0
      src/main/java/com/example/dao/EsOtherMapper.java
  14. 18 0
      src/main/java/com/example/exception/CustomException.java
  15. 18 0
      src/main/java/com/example/exception/SystemException.java
  16. 66 0
      src/main/java/com/example/model/BookDto.java
  17. 30 0
      src/main/java/com/example/model/NewsDto.java
  18. 28 0
      src/main/java/com/example/pojo/EsDemo.java
  19. 26 0
      src/main/java/com/example/pojo/EsOther.java
  20. 17 0
      src/main/java/com/example/service/EsDemoService.java
  21. 13 0
      src/main/java/com/example/service/EsOtherService.java
  22. 478 0
      src/main/java/com/example/service/impl/EsDemoServiceImpl.java
  23. 52 0
      src/main/java/com/example/service/impl/EsOtherServiceImpl.java
  24. 21 0
      src/main/resources/application.yml
  25. 95 0
      src/main/resources/banner.txt
  26. BIN
      src/main/resources/static/element-ui/fonts/element-icons.ttf
  27. BIN
      src/main/resources/static/element-ui/fonts/element-icons.woff
  28. 0 0
      src/main/resources/static/element-ui/index.css
  29. 0 0
      src/main/resources/static/element-ui/index.js
  30. BIN
      src/main/resources/static/favicon.ico
  31. BIN
      src/main/resources/static/img/baidu.png
  32. BIN
      src/main/resources/static/img/logo.png
  33. 1 0
      src/main/resources/static/js/axios.min.js
  34. 0 0
      src/main/resources/static/js/moment.min.js
  35. 5 0
      src/main/resources/static/js/vue.min.js
  36. 45 0
      src/main/resources/templates/common/common.html
  37. 395 0
      src/main/resources/templates/index.html
  38. 16 0
      src/test/java/com/example/ApplicationTests.java

+ 138 - 0
pom.xml

@@ -0,0 +1,138 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <modelVersion>4.0.0</modelVersion>
+    <parent>
+        <groupId>org.springframework.boot</groupId>
+        <artifactId>spring-boot-starter-parent</artifactId>
+        <version>2.1.3.RELEASE</version>
+        <relativePath/> <!-- lookup parent from repository -->
+    </parent>
+    <groupId>com.example</groupId>
+    <artifactId>01-SpringBoot-ES-Local</artifactId>
+    <version>0.0.1-SNAPSHOT</version>
+    <name>01-SpringBoot-ES-Local</name>
+    <description>Demo project for Spring Boot</description>
+
+    <properties>
+        <java.version>1.8</java.version>
+        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+        <fastjson.version>1.2.47</fastjson.version>
+        <commons-lang3.version>3.7</commons-lang3.version>
+        <elasticsearch.version>6.6.1</elasticsearch.version>
+    </properties>
+
+    <dependencies>
+
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-test</artifactId>
+            <scope>test</scope>
+        </dependency>
+
+        <!-- DevTools -->
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-devtools</artifactId>
+            <optional>true</optional>
+        </dependency>
+
+        <!-- Web -->
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-web</artifactId>
+        </dependency>
+
+        <!-- Thymeleaf -->
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-thymeleaf</artifactId>
+        </dependency>
+
+        <!-- Java Low Level REST Client -->
+        <dependency>
+            <groupId>org.elasticsearch.client</groupId>
+            <artifactId>elasticsearch-rest-client</artifactId>
+            <version>${elasticsearch.version}</version>
+        </dependency>
+
+        <!-- Java High Level REST Client -->
+        <dependency>
+            <groupId>org.elasticsearch.client</groupId>
+            <artifactId>elasticsearch-rest-high-level-client</artifactId>
+            <version>${elasticsearch.version}</version>
+        </dependency>
+
+        <!-- Fastjson -->
+        <dependency>
+            <groupId>com.alibaba</groupId>
+            <artifactId>fastjson</artifactId>
+            <version>${fastjson.version}</version>
+        </dependency>
+
+        <!-- Commons-Lang3工具包 -->
+        <dependency>
+            <groupId>org.apache.commons</groupId>
+            <artifactId>commons-lang3</artifactId>
+            <version>${commons-lang3.version}</version>
+        </dependency>
+
+        <!-- lombok的依赖 -->
+        <dependency>
+            <groupId>org.projectlombok</groupId>
+            <artifactId>lombok</artifactId>
+            <optional>true</optional>
+        </dependency>
+
+        <!--  -->
+        <dependency>
+            <groupId>org.elasticsearch.client</groupId>
+            <artifactId>elasticsearch-rest-high-level-client</artifactId>
+            <version>${elasticsearch.version}</version>
+        </dependency>
+
+        <dependency>
+            <groupId>mysql</groupId>
+            <artifactId>mysql-connector-java</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>com.baomidou</groupId>
+            <artifactId>mybatis-plus-boot-starter</artifactId>
+            <version>3.2.0</version>
+        </dependency>
+
+
+    </dependencies>
+
+    <build>
+        <plugins>
+            <!-- SrpingBoot打包工具 -->
+            <plugin>
+                <groupId>org.springframework.boot</groupId>
+                <artifactId>spring-boot-maven-plugin</artifactId>
+            </plugin>
+            <!-- 指定JDK编译版本 -->
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-compiler-plugin</artifactId>
+                <configuration>
+                    <source>${java.version}</source>
+                    <target>${java.version}</target>
+                    <encoding>${project.build.sourceEncoding}</encoding>
+                </configuration>
+            </plugin>
+            <!-- JavaDoc -->
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-javadoc-plugin</artifactId>
+                <version>3.0.0</version>
+            </plugin>
+        </plugins>
+    </build>
+
+</project>

+ 21 - 0
src/main/java/com/example/Application.java

@@ -0,0 +1,21 @@
+package com.example;
+
+//import org.mybatis.spring.annotation.MapperScan;
+import org.mybatis.spring.annotation.MapperScan;
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+/**
+ *
+ * @author wliduo[i@dolyw.com]
+ * @date 2019/7/31 18:00
+ */
+@MapperScan("com.example.dao")
+@SpringBootApplication
+public class Application {
+
+    public static void main(String[] args) {
+        SpringApplication.run(Application.class, args);
+    }
+
+}

+ 54 - 0
src/main/java/com/example/common/ResponseBean.java

@@ -0,0 +1,54 @@
+package com.example.common;
+
+/**
+ * ResponseBean
+ *
+ * @author wliduo[i@dolyw.com]
+ * @date 2018/8/30 11:39
+ */
+public class ResponseBean {
+    /**
+     * HTTP状态码
+     */
+    private Integer code;
+
+    /**
+     * 返回信息
+     */
+    private String msg;
+
+    /**
+     * 返回的数据
+     */
+    private Object data;
+
+    public ResponseBean(int code, String msg, Object data) {
+        this.code = code;
+        this.msg = msg;
+        this.data = data;
+    }
+
+    public Integer getCode() {
+        return code;
+    }
+
+    public void setCode(Integer code) {
+        this.code = code;
+    }
+
+    public String getMsg() {
+        return msg;
+    }
+
+    public void setMsg(String msg) {
+        this.msg = msg;
+    }
+
+    public Object getData() {
+        return data;
+    }
+
+    public void setData(Object data) {
+        this.data = data;
+    }
+}

+ 76 - 0
src/main/java/com/example/config/ExceptionAdvice.java

@@ -0,0 +1,76 @@
+package com.example.config;
+
+import com.example.common.ResponseBean;
+import com.example.exception.CustomException;
+import com.example.exception.SystemException;
+import org.springframework.http.HttpStatus;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.ResponseStatus;
+import org.springframework.web.bind.annotation.RestControllerAdvice;
+import org.springframework.web.servlet.NoHandlerFoundException;
+
+import javax.servlet.http.HttpServletRequest;
+
+/**
+ * 异常控制处理器
+ *
+ * @author wliduo[i@dolyw.com]
+ * @date 2018/8/30 14:02
+ */
+@RestControllerAdvice
+public class ExceptionAdvice {
+    /**
+     * 捕捉自定义异常
+     * @return
+     */
+    @ResponseStatus(HttpStatus.BAD_REQUEST)
+    @ExceptionHandler(CustomException.class)
+    public ResponseBean handle(CustomException e) {
+        return new ResponseBean(HttpStatus.BAD_REQUEST.value(), e.getMessage(), null);
+    }
+
+    /**
+     * 捕捉系统异常
+     * @return
+     */
+    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
+    @ExceptionHandler(SystemException.class)
+    public ResponseBean handle(SystemException e) {
+        return new ResponseBean(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage(), null);
+    }
+
+    /**
+     * 捕捉404异常
+     * @return
+     */
+    @ResponseStatus(HttpStatus.NOT_FOUND)
+    @ExceptionHandler(NoHandlerFoundException.class)
+    public ResponseBean handle(NoHandlerFoundException e) {
+        return new ResponseBean(HttpStatus.NOT_FOUND.value(), e.getMessage(), null);
+    }
+
+    /**
+     * 捕捉其他所有异常
+     * @param request
+     * @param ex
+     * @return
+     */
+    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
+    @ExceptionHandler(Exception.class)
+    public ResponseBean globalException(HttpServletRequest request, Throwable ex) {
+        return new ResponseBean(this.getStatus(request).value(), ex.toString() + ": " + ex.getMessage(), null);
+    }
+
+    /**
+     * 获取状态码
+     * @param request
+     * @return
+     */
+    private HttpStatus getStatus(HttpServletRequest request) {
+        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
+        if (statusCode == null) {
+            return HttpStatus.INTERNAL_SERVER_ERROR;
+        }
+        return HttpStatus.valueOf(statusCode);
+    }
+}

+ 61 - 0
src/main/java/com/example/config/RestClientConfig.java

@@ -0,0 +1,61 @@
+package com.example.config;
+
+import org.apache.http.Header;
+import org.apache.http.HttpHost;
+import org.apache.http.message.BasicHeader;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestClientBuilder;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+/**
+ * RestClientConfig
+ *
+ * @author wliduo[i@dolyw.com]
+ * @date 2019/8/14 15:34
+ */
+@Configuration
+public class RestClientConfig {
+
+    @Value("${elasticsearch.hostname}")
+    private String hostname;
+
+    @Value("${elasticsearch.port}")
+    private int port;
+
+    /**
+     * LowLevelRestConfig
+     *
+     * @param
+     * @return org.elasticsearch.client.RestClient
+     * @author wliduo[i@dolyw.com]
+     * @date 2019/8/12 18:56
+     */
+    @Bean
+    public RestClient restClient() {
+        // 如果有多个从节点可以持续在内部new多个HttpHost,参数1是IP,参数2是端口,参数3是通信协议
+        RestClientBuilder clientBuilder = RestClient.builder(new HttpHost(hostname, port, "http"));
+        // 设置Header编码
+        Header[] defaultHeaders = {new BasicHeader("content-type", "application/json")};
+        clientBuilder.setDefaultHeaders(defaultHeaders);
+        // 添加其他配置,这些配置都是可选的,详情配置可看https://blog.csdn.net/jacksonary/article/details/82729556
+        return clientBuilder.build();
+    }
+
+    /**
+     * HighLevelRestConfig
+     *
+     * @param
+     * @return org.elasticsearch.client.RestClient
+     * @author wliduo[i@dolyw.com]
+     * @date 2019/8/12 18:56
+     */
+    @Bean
+    public RestHighLevelClient restHighLevelClient() {
+        // 如果有多个从节点可以持续在内部new多个HttpHost,参数1是IP,参数2是端口,参数3是通信协议
+        return new RestHighLevelClient(RestClient.builder(new HttpHost(hostname, port, "http")));
+    }
+
+}

+ 31 - 0
src/main/java/com/example/config/WebMvcConfig.java

@@ -0,0 +1,31 @@
+package com.example.config;
+
+import org.springframework.context.annotation.Configuration;
+import org.springframework.core.Ordered;
+import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
+import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
+
+/**
+ * 在SpringBoot2.0及Spring5.0中WebMvcConfigurerAdapter以被废弃,建议实现WebMvcConfigurer接口
+ *
+ * @author wliduo[i@dolyw.com]
+ * @date 2019/1/24 19:17
+ */
+@Configuration
+public class WebMvcConfig implements WebMvcConfigurer {
+
+    /**
+     * 设置首页
+     *
+     * @param registry
+     * @return void
+     * @author wliduo[i@dolyw.com]
+     * @date 2019/1/24 19:18
+     */
+    @Override
+    public void addViewControllers(ViewControllerRegistry registry) {
+        registry.addViewController("/").setViewName("forward:/index.shtml");
+        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
+    }
+
+}

+ 11 - 0
src/main/java/com/example/constant/Constant.java

@@ -0,0 +1,11 @@
+package com.example.constant;
+
+/**
+ * 常量
+ *
+ * @author wliduo[i@dolyw.com]
+ * @date 2018/9/3 16:03
+ */
+public interface Constant {
+    String INDEX = "book";
+}

+ 373 - 0
src/main/java/com/example/controller/HighLevelRestController.java

@@ -0,0 +1,373 @@
+package com.example.controller;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
+import com.example.common.ResponseBean;
+import com.example.constant.Constant;
+import com.example.model.BookDto;
+import com.example.model.NewsDto;
+//import com.example.service.EsDemoService;
+import com.example.service.EsDemoService;
+import org.apache.commons.lang3.StringUtils;
+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.update.UpdateRequest;
+import org.elasticsearch.action.update.UpdateResponse;
+import org.elasticsearch.client.*;
+import org.elasticsearch.common.text.Text;
+import org.elasticsearch.common.xcontent.XContentType;
+import org.elasticsearch.index.query.BoolQueryBuilder;
+import org.elasticsearch.index.query.QueryBuilder;
+import org.elasticsearch.index.query.QueryBuilders;
+import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
+import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
+import org.elasticsearch.search.SearchHit;
+import org.elasticsearch.search.SearchHits;
+import org.elasticsearch.search.builder.SearchSourceBuilder;
+import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
+import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
+import org.elasticsearch.search.sort.ScoreSortBuilder;
+import org.elasticsearch.search.sort.SortBuilder;
+import org.elasticsearch.search.sort.SortBuilders;
+import org.elasticsearch.search.sort.SortOrder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.HttpStatus;
+import org.springframework.web.bind.annotation.*;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * HighLevelRestController
+ *
+ * @author wliduo[i@dolyw.com]
+ * @date 2019/8/14 16:24
+ */
+@RestController
+@RequestMapping("/high")
+public class HighLevelRestController {
+
+    /**
+     * logger
+     */
+    private static final Logger logger = LoggerFactory.getLogger(HighLevelRestController.class);
+
+    @Autowired
+    private RestHighLevelClient restHighLevelClient;
+
+    @Autowired
+    private EsDemoService esDemoService;
+
+    /**
+     * 获取ES信息
+     *
+     * @param
+     * @return com.example.common.ResponseBean
+     * @throws IOException
+     * @author wliduo[i@dolyw.com]
+     * @date 2019/8/14 17:11
+     */
+    @GetMapping("/es")
+    public ResponseBean getEsInfo() throws IOException {
+        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
+        // SearchRequest
+        SearchRequest searchRequest = new SearchRequest();
+        searchRequest.source(searchSourceBuilder);
+        // 查询ES
+        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
+        return new ResponseBean(HttpStatus.OK.value(), "查询成功", searchResponse);
+    }
+
+    @GetMapping("/testget")
+    public ResponseBean testget() throws IOException {
+
+//        return new ResponseBean(HttpStatus.OK.value(), "查询成功", esDemoService.compareMysqlDataToEs());
+        return new ResponseBean(HttpStatus.OK.value(), "查询成功", esDemoService.importMysqlDataToEs());
+    }
+
+    /**
+     * 列表查询
+     *
+     * @param page
+	 * @param rows
+	 * @param keyword
+     * @return com.example.common.ResponseBean
+     * @throws
+     * @author wliduo[i@dolyw.com]
+     * @date 2019/8/15 16:01
+     */
+    @GetMapping("/book")
+    public ResponseBean list(@RequestParam(defaultValue = "1") Integer page,
+                             @RequestParam(defaultValue = "10") Integer rows,
+                             String keyword) throws IOException {
+//        System.err.println("---------");
+        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
+        // 分页采用简单的from + size分页,适用数据量小的
+        searchSourceBuilder.from((page - 1) * rows);
+        searchSourceBuilder.size(rows);
+
+        // 查询条件,只有查询关键字不为空才带查询条件
+        if (StringUtils.isNoneBlank(keyword)) {
+
+//            QueryBuilder queryBuilder = QueryBuilders.multiMatchQuery(keyword, "es_dome03");
+//            QueryBuilder queryBuilder = QueryBuilders.queryStringQuery(keyword);
+//            QueryBuilder queryBuilder = QueryBuilders.queryStringQuery(keyword);
+//            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
+            if(keyword.contains("政策")){
+                System.err.println("进入政策条件");
+//                QueryBuilder queryBuilder1 = QueryBuilders.matchQuery("type", "水电");
+//                searchSourceBuilder.query(queryBuilder1);
+                BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery()
+                        .must(QueryBuilders.queryStringQuery(keyword))
+                        .must(QueryBuilders.termQuery("source","国家能源局"));
+                        // 单字搜索,由于类型未设置关键词。
+//                        .must(QueryBuilders.termQuery("source","能"));
+//                        .must(QueryBuilders.wildcardQuery("source","国家能源局"));
+//                 searchSourceBuilder.query(queryBuilder).sort("_score", SortOrder.DESC).sort("date", SortOrder.DESC);
+                // todo 根据日期排序。
+                FunctionScoreQueryBuilder.FilterFunctionBuilder[] filterFunctionBuilders = new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
+                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.boolQuery(), ScoreFunctionBuilders.weightFactorFunction(100)),
+//                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.regexpQuery("date","2021"), ScoreFunctionBuilders.weightFactorFunction(80)),
+//                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.fi("date","2021"), ScoreFunctionBuilders.weightFactorFunction(80)),
+//                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.multiMatchQuery("date","2021"), ScoreFunctionBuilders.weightFactorFunction(80)),
+                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.termQuery("source","国家能源局"), ScoreFunctionBuilders.weightFactorFunction(10))
+                };
+                FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(queryBuilder, filterFunctionBuilders);
+                searchSourceBuilder.query(functionScoreQueryBuilder)
+                        .sort("date", SortOrder.DESC)
+                        .sort("_score", SortOrder.DESC);
+                // searchSourceBuilder.sort("date",SortOrder.DESC);
+            }else {
+                System.out.println(keyword);
+                QueryBuilder queryBuilder = QueryBuilders.queryStringQuery(keyword);
+                // searchSourceBuilder.query(queryBuilder).sort("_score", SortOrder.DESC).sort("date", SortOrder.DESC);
+                // todo 根据日期排序。
+                FunctionScoreQueryBuilder.FilterFunctionBuilder[] filterFunctionBuilders = new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
+                        // new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("type", 1), ScoreFunctionBuilders.weightFactorFunction(1))
+//                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.regexpQuery("date","2021"), ScoreFunctionBuilders.weightFactorFunction(80)),
+//                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.multiMatchQuery("date","2021"), ScoreFunctionBuilders.weightFactorFunction(80)),
+                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.queryStringQuery(keyword), ScoreFunctionBuilders.weightFactorFunction(10))
+                };
+
+//                SortBuilder sortBuilder = SortBuilders.fieldSort("date")
+//                        .order(SortOrder.DESC);
+//                ScoreSortBuilder order = SortBuilders.scoreSort().order(SortOrder.DESC);
+                FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(queryBuilder, filterFunctionBuilders);
+                searchSourceBuilder.query(functionScoreQueryBuilder)
+                        .sort("date", SortOrder.DESC)
+                        .sort("_score", SortOrder.DESC);
+                // searchSourceBuilder.sort("date",SortOrder.DESC);
+            }
+
+            // 暂时弃用。
+//            searchSourceBuilder.query(queryBuilder);
+
+            // 高亮
+            HighlightBuilder highlightBuilder = new HighlightBuilder();
+            highlightBuilder.field("title")
+                    .field("content")
+                    .field("type")
+                    .field("date")
+                    .requireFieldMatch(false)
+                    .preTags("<span style='color:red'>")
+                    .postTags("</span>");
+            searchSourceBuilder.highlighter(highlightBuilder);
+        }else {
+            List<NewsDto> newsDtos = new ArrayList<>();
+            Map<String, Object> result = new HashMap<String, Object>(16);
+            result.put("count", 0);
+            result.put("data", newsDtos);
+            return new ResponseBean(HttpStatus.OK.value(), "查询成功", result);
+        }
+
+
+        // 排序,根据ID倒叙
+//        searchSourceBuilder.sort("id", SortOrder.DESC);
+        // SearchRequest
+        // 原60W数据的索引
+//        SearchRequest searchRequest = new SearchRequest("es_new_demo_change");
+        // 新增13W加60W数据的索引
+        SearchRequest searchRequest = new SearchRequest("bd-es");
+        searchRequest.source(searchSourceBuilder);
+        // 查询ES
+        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
+        SearchHits hits = searchResponse.getHits();
+        // 获取总数
+        Long total = hits.getTotalHits();
+        // 遍历封装列表对象
+        List<NewsDto> newsDtos = new ArrayList<>();
+        SearchHit[] searchHits = hits.getHits();
+        for (SearchHit searchHit : searchHits) {
+            Map<String, HighlightField> highlightFieldMap = searchHit.getHighlightFields() ;
+
+            HighlightField title = highlightFieldMap.get("title");
+            HighlightField content = highlightFieldMap.get("content");
+            HighlightField type = highlightFieldMap.get("type");
+            HighlightField date = highlightFieldMap.get("date");
+
+            NewsDto newsDto = JSON.parseObject(searchHit.getSourceAsString(), NewsDto.class);
+            high(title, "title", newsDto);
+            high(content, "content", newsDto);
+            high(type, "type", newsDto);
+            high(date, "date", newsDto);
+            // 处理新增来源模块
+            if (!newsDto.getUrl().isEmpty()){
+                String url = newsDto.getUrl();
+                if (url.contains("bjx.com.cn")){
+                    newsDto.setSource("北极星");
+                }
+                if (url.contains("chinagas.org.cn")) {
+                    newsDto.setSource("中国燃气网");
+                }
+                if (url.contains("cneeex.com")) {
+                    newsDto.setSource("上海环境能源交易所");
+                }
+                if (url.contains("cctd.com.cn")) {
+                    newsDto.setSource("中国煤炭市场网");
+                }
+                if (url.contains("coalresource.com")) {
+                    newsDto.setSource("中国煤炭资源网");
+                }
+                if (url.contains("news.mysteel.com")) {
+                    newsDto.setSource("我的钢铁");
+                }
+                if (url.contains("info.glinfo.com")) {
+                    newsDto.setSource("我的钢铁");
+                }
+                if (url.contains("cecn.org.cn")) {
+                    newsDto.setSource("建设工程造价信息网");
+                }
+                if (url.contains("iesplaza.com")) {
+                    newsDto.setSource("IESPlaza综合能源服务网");
+                }
+                if (url.contains("cnnpn.cn")) {
+                    newsDto.setSource("中国核电网");
+                }
+
+            }else {
+                newsDto.setSource("未匹配到来源");
+            }
+            newsDtos.add(newsDto);
+        }
+        // 封装Map参数返回
+        Map<String, Object> result = new HashMap<String, Object>(16);
+        result.put("count", total);
+        result.put("data", newsDtos);
+        return new ResponseBean(HttpStatus.OK.value(), "查询成功", result);
+    }
+
+    public void high(HighlightField size, String type, NewsDto newsDto){
+        // 解析高亮字段,将原来得字段换为高亮字段。
+            if (null != size){
+                Text[] fragments = size.fragments();
+                String newSize = "";
+                for (Text fragment : fragments) {
+                    newSize += fragment;
+                }
+                switch(type){
+                    case "title" :
+                        newsDto.setTitle(newSize);
+                        break;
+                    case "content" :
+                        newsDto.setContent(newSize);
+                        break;
+                    case "date" :
+                        newsDto.setDate(newSize);
+                        break;
+                    case "type" :
+                        newsDto.setType(newSize);
+                        break;
+                }
+            }
+    }
+
+    /**
+     * 根据ID查询
+     *
+     * @param id
+     * @return com.example.common.ResponseBean
+     * @throws IOException
+     * @author wliduo[i@dolyw.com]
+     * @date 2019/8/15 14:10
+     */
+//    @GetMapping("/book/{id}")
+//    public ResponseBean getById(@PathVariable("id") String id) throws IOException {
+//        // GetRequest
+//        GetRequest getRequest = new GetRequest(Constant.INDEX, id);
+//        // 查询ES
+//        GetResponse getResponse = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
+//        NewsDto newsDto = JSON.parseObject(getResponse.getSourceAsString(), NewsDto.class);
+//        return new ResponseBean(HttpStatus.OK.value(), "查询成功", newsDto);
+//    }
+
+    /**
+     * 添加文档
+     *
+     * @param bookDto
+     * @return com.example.common.ResponseBean
+     * @throws
+     * @author wliduo[i@dolyw.com]
+     * @date 2019/8/15 16:01
+     */
+//    @PostMapping("/book")
+//    public ResponseBean add(@RequestBody BookDto bookDto) throws IOException {
+//        // IndexRequest
+//        IndexRequest indexRequest = new IndexRequest(Constant.INDEX);
+//        Long id = System.currentTimeMillis();
+//        bookDto.setId(id);
+//        String source = JSON.toJSONString(bookDto);
+//        indexRequest.id(id.toString()).source(source, XContentType.JSON);
+//        // 操作ES
+//        IndexResponse indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
+//        return new ResponseBean(HttpStatus.OK.value(), "添加成功", indexResponse);
+//    }
+
+    /**
+     * 修改文档
+     *
+     * @param bookDto
+     * @return com.example.common.ResponseBean
+     * @throws
+     * @author wliduo[i@dolyw.com]
+     * @date 2019/8/15 16:02
+     */
+//    @PutMapping("/book")
+//    public ResponseBean update(@RequestBody BookDto bookDto) throws IOException {
+//        // UpdateRequest
+//        UpdateRequest updateRequest = new UpdateRequest(Constant.INDEX, bookDto.getId().toString());
+//        updateRequest.doc(JSON.toJSONString(bookDto), XContentType.JSON);
+//        // 操作ES
+//        UpdateResponse updateResponse = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
+//        return new ResponseBean(HttpStatus.OK.value(), "修改成功", updateResponse);
+//    }
+
+    /**
+     * 删除文档
+     *
+     * @param id
+     * @return com.example.common.ResponseBean
+     * @throws
+     * @author wliduo[i@dolyw.com]
+     * @date 2019/8/15 16:02
+     */
+//    @DeleteMapping("/book/{id}")
+//    public ResponseBean deleteById(@PathVariable("id") String id) throws IOException {
+//        // DeleteRequest
+//        DeleteRequest deleteRequest = new DeleteRequest(Constant.INDEX, id);
+//        // 操作ES
+//        DeleteResponse deleteResponse = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
+//        return new ResponseBean(HttpStatus.OK.value(), "删除成功", deleteResponse);
+//    }
+
+}

+ 146 - 0
src/main/java/com/example/controller/IndexController.java

@@ -0,0 +1,146 @@
+package com.example.controller;
+
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestMapping;
+
+import javax.imageio.ImageIO;
+import java.awt.image.BufferedImage;
+import java.io.File;
+import java.util.*;
+
+/**
+ * 通用访问匹配页面跳转
+ *
+ * @author wliduo[i@dolyw.com]
+ * @date 2019/1/24 19:27
+ */
+@Controller
+public class IndexController {
+
+    /**
+     * 通用页面跳转
+     *
+     * @param url
+     * @return java.lang.String
+     * @author wliduo[i@dolyw.com]
+     * @date 2019/1/24 19:27
+     */
+    @RequestMapping("{url}.shtml")
+    public String page(@PathVariable("url") String url) {
+        return url;
+    }
+
+    /**
+     * 通用页面跳转(二级目录)
+     *
+     * @param module
+	 * @param url
+     * @return java.lang.String
+     * @author wliduo[i@dolyw.com]
+     * @date 2019/1/24 19:27
+     */
+    @RequestMapping("{module}/{url}.shtml")
+    public String page(@PathVariable("module") String module, @PathVariable("url") String url) {
+        return module + "/" + url;
+    }
+
+    /**
+     * 通用页面跳转(三级目录)
+     *
+     * @param module
+	 * @param url
+     * @return java.lang.String
+     * @author wliduo[i@dolyw.com]
+     * @date 2019/1/25 19:35
+     */
+    @RequestMapping("{module}/{module2}/{url}.shtml")
+    public String page(@PathVariable("module") String module, @PathVariable("module2") String module2,
+                       @PathVariable("url") String url) {
+        return module + "/" + module2 + "/" + url;
+    }
+
+
+
+    public static void main(String[] args) {
+        List<Integer> five = new ArrayList<>();
+        List<Integer> two = new ArrayList<>();
+
+        // g:位数  l:数字范围
+        sum(five,5,35);
+        sum(two,2,12);
+        Collections.sort(five);
+        Collections.sort(two);
+        String s = five.toString() + "<-->" + two.toString();
+        System.out.println("");
+//        System.out.println("                .-\"\"\"-.\n" +
+//                "               / .===. \\\n" +
+//                "               \\/ 6 6 \\/\n" +
+//                "               ( \\___/ )\n" +
+//                "  _________ooo__\\_____/_____________\n" +
+//                " /                                  \\\n" +
+//                " |     I  am  Superman ! ! !        |\n" +
+//                " \\_______________________ooo________/ \n" +
+//                "                |  |  |\n" +
+//                "                |_ | _|\n" +
+//                "                |  |  |\n" +
+//                "                |__|__|\n" +
+//                "                /-'Y'-\\\n" +
+//                "               (__/ \\__)");
+        System.out.println("                .-\"\"\"-.\n" +
+                "               / .===. \\\n" +
+                "               \\/ 6 6 \\/\n" +
+                "               ( \\___/ )\n" +
+                "  _________ooo__\\_____/_____________\n" +
+                " /                                  \\\n" +
+                " |     "+s+" |\n" +
+                " \\_______________________ooo________/ \n" +
+                "                |  |  |\n" +
+                "                |_ | _|\n" +
+                "                |  |  |\n" +
+                "                |__|__|\n" +
+                "                /-'Y'-\\\n" +
+                "               (__/ \\__)");
+    }
+
+    public static void sum(List<Integer> arr, Integer g, Integer l){
+        Random rand = new Random();
+        for(int i=0; i<g; i++) {
+            if (arr.size() != g){
+                int b = rand.nextInt(l) + 1;
+                if (!arr.contains(b)){
+                    arr.add(b);
+                }else {
+                    i--;
+                }
+            }
+        }
+    }
+
+
+    public static void test01() {
+        String path = "W:\\xiaoxiong.jpg";//导入的图片
+        String base = "ceo";//将会用这个字符串里的字符填充图片
+        BufferedImage image;
+        try {
+           image = ImageIO.read(new File(path));//读入图片,并用图片缓冲区对象来接收
+            //双层for循环,遍历图片
+            for (int y = 0; y < image.getHeight(); y+=2) {//先竖向遍历,再横向遍历,即一行一行的找,后面也会一行一行的打印
+                for (int x = 0; x < image.getWidth(); x++) {
+                    int color = image.getRGB(x, y);//图片缓冲区自带的方法,可以得到当前点的颜色值,返回值是int类型
+                    int r=(color>>16)&0xff;
+                    int g=(color>>8)&0xff;
+                    int b=color&0xff;
+                    float gray = 0.299f * r + 0.578f * g + 0.114f * b;//灰度值计算公式,固定比例,无需理解
+                    int index = Math.round(gray * (base.length()) / 255);
+                    if(index>=base.length()) {
+                        System.out.print(" ");//白色的地方打空格,相当于白色背景,这样图片轮廓比较明显
+                    }else {
+                        System.out.print(base.charAt(index));//有颜色的地方打字符
+                    }
+                }
+                System.out.println();//一行打完,换行
+            }
+        }catch (Exception e){}
+    }
+}

+ 287 - 0
src/main/java/com/example/controller/LowLevelRestController.java

@@ -0,0 +1,287 @@
+package com.example.controller;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
+import com.example.common.ResponseBean;
+import com.example.model.BookDto;
+import org.apache.http.Header;
+import org.apache.http.HttpHost;
+import org.apache.http.RequestLine;
+import org.apache.http.entity.ContentType;
+import org.apache.http.nio.entity.NStringEntity;
+import org.apache.http.util.EntityUtils;
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.client.*;
+import org.elasticsearch.common.xcontent.XContentBuilder;
+import org.elasticsearch.common.xcontent.json.JsonXContent;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.*;
+
+import java.io.IOException;
+import java.util.regex.Pattern;
+
+/**
+ * LowLevelRestController
+ *
+ * @author wliduo[i@dolyw.com]
+ * @date 2019/8/7 17:20
+ */
+@RestController
+@RequestMapping("/low")
+public class LowLevelRestController {
+
+    /**
+     * logger
+     */
+    private static final Logger logger = LoggerFactory.getLogger(LowLevelRestController.class);
+
+    /**
+     * PATTERN
+     */
+    private static Pattern PATTERN = Pattern.compile("\\s*|\t|\r|\n");
+
+    @Autowired
+    private RestClient restClient;
+
+    /**
+     * 同步执行HTTP请求
+     *
+     * @param
+     * @return org.springframework.http.ResponseEntity<java.lang.String>
+     * @throws IOException
+     * @author wliduo[i@dolyw.com]
+     * @date 2019/8/8 17:15
+     */
+    @GetMapping("/es")
+    public ResponseBean getEsInfo() throws IOException {
+        Request request = new Request("GET", "/");
+        // performRequest是同步的,将阻塞调用线程并在请求成功时返回Response,如果失败则抛出异常
+        Response response = restClient.performRequest(request);
+        // 获取请求行
+        RequestLine requestLine = response.getRequestLine();
+        // 获取host
+        HttpHost host = response.getHost();
+        // 获取状态码
+        int statusCode = response.getStatusLine().getStatusCode();
+        // 获取响应头
+        Header[] headers = response.getHeaders();
+        // 获取响应体
+        String responseBody = EntityUtils.toString(response.getEntity());
+        return new ResponseBean(HttpStatus.OK.value(), "查询成功", JSON.parseObject(responseBody));
+    }
+
+
+    /**
+     * 异步执行HTTP请求
+     *
+     * @param
+     * @return org.springframework.http.ResponseEntity<java.lang.String>
+     * @author wliduo[i@dolyw.com]
+     * @date 2019/8/8 17:15
+     */
+    @GetMapping("/es/async")
+    public ResponseBean asynchronous() {
+        Request request = new Request("GET", "/");
+        restClient.performRequestAsync(request, new ResponseListener() {
+            @Override
+            public void onSuccess(Response response) {
+                logger.info("异步执行HTTP请求并成功");
+            }
+
+            @Override
+            public void onFailure(Exception exception) {
+                logger.info("异步执行HTTP请求并失败");
+            }
+        });
+        return new ResponseBean(HttpStatus.OK.value(), "异步请求中", null);
+    }
+
+    /**
+     * 分词分页查询列表
+     *
+     * @param page
+	 * @param rows
+	 * @param keyword
+     * @return com.example.common.ResponseBean
+     * @author wliduo[i@dolyw.com]
+     * @date 2019/8/9 15:32
+     */
+    @GetMapping("/book")
+    public ResponseBean getBookList(@RequestParam(defaultValue = "1") Integer page,
+                                    @RequestParam(defaultValue = "10") Integer rows,
+                                    String keyword) {
+        Request request = new Request("POST", new StringBuilder("/_search").toString());
+        // 添加Json返回优化
+        request.addParameter("pretty", "true");
+        // 拼接查询Json
+        IndexRequest indexRequest = new IndexRequest();
+        XContentBuilder builder = null;
+        Response response = null;
+        String responseBody = null;
+        try {
+            builder = JsonXContent.contentBuilder()
+                    .startObject()
+                    .startObject("query")
+                    .startObject("multi_match")
+                    .field("query", keyword)
+                    .array("fields", new String[]{"name", "desc"})
+                    .endObject()
+                    .endObject()
+                    .startObject("sort")
+                    .startObject("id")
+                    .field("order", "desc")
+                    .endObject()
+                    .endObject()
+                    .endObject();
+            indexRequest.source(builder);
+            // 设置请求体并指定ContentType,如果不指定会乱码
+            request.setEntity(new NStringEntity(indexRequest.source().utf8ToString(), ContentType.APPLICATION_JSON));
+            // 执行HTTP请求
+            response = restClient.performRequest(request);
+            responseBody = EntityUtils.toString(response.getEntity());
+        } catch (IOException e) {
+            return new ResponseBean(HttpStatus.NOT_FOUND.value(), "can not found the book by your id", null);
+        }
+        return new ResponseBean(HttpStatus.OK.value(), "查询成功", JSON.parseObject(responseBody));
+    }
+
+    /**
+     * 根据Id获取ES对象
+     *
+     * @param id
+     * @return org.springframework.http.ResponseEntity<java.lang.String>
+     * @author wliduo[i@dolyw.com]
+     * @date 2019/8/8 17:48
+     */
+    @GetMapping("/book/{id}")
+    public ResponseBean getBookById(@PathVariable("id") String id) {
+        Request request = new Request("GET", new StringBuilder("/book/book/")
+                .append(id).toString());
+        // 添加Json返回优化
+        request.addParameter("pretty", "true");
+        Response response = null;
+        String responseBody = null;
+        try {
+            // 执行HTTP请求
+            response = restClient.performRequest(request);
+            responseBody = EntityUtils.toString(response.getEntity());
+        } catch (IOException e) {
+            return new ResponseBean(HttpStatus.NOT_FOUND.value(), "can not found the book by your id", null);
+        }
+        return new ResponseBean(HttpStatus.OK.value(), "查询成功", JSON.parseObject(responseBody));
+    }
+
+    /**
+     * 添加ES对象, Book的ID就是ES中存储的Document的ID,ES的POST和PUT可以看下面这个文章
+     * https://blog.csdn.net/z457181562/article/details/93470152
+     *
+     * @param bookDto
+     * @return org.springframework.http.ResponseEntity<java.lang.String>
+     * @throws IOException
+     * @author wliduo[i@dolyw.com]
+     * @date 2019/8/8 17:46
+     */
+    @PostMapping("/book")
+    public ResponseBean add(@RequestBody BookDto bookDto) throws IOException {
+        // Endpoint直接指定为Index/Type的形式
+        /*Request request = new Request("POST", new StringBuilder("/book/book/").toString());*/
+        // 防重复新增数据
+        bookDto.setId(System.currentTimeMillis());
+        Request request = new Request("PUT", new StringBuilder("/book/book/")
+                .append(bookDto.getId()).append("/_create").toString());
+        // 设置其他一些参数比如美化Json
+        request.addParameter("pretty", "true");
+        // 设置请求体并指定ContentType,如果不指定会乱码
+        request.setEntity(new NStringEntity(JSONObject.toJSONString(bookDto), ContentType.APPLICATION_JSON));
+        // 发送HTTP请求
+        Response response = restClient.performRequest(request);
+        // 获取响应体
+        String responseBody = EntityUtils.toString(response.getEntity());
+        return new ResponseBean(HttpStatus.OK.value(), "添加成功", JSON.parseObject(responseBody));
+    }
+
+    /**
+     * 根据Id更新Book,ES的POST和PUT可以看下面这个文章
+     *
+     * https://blog.csdn.net/z457181562/article/details/93470152
+     * @param bookDto
+     * @return org.springframework.http.ResponseEntity<java.lang.String>
+     * @throws IOException
+     * @author wliduo[i@dolyw.com]
+     * @date 2019/8/9 10:04
+     */
+    @PutMapping("/book")
+    public ResponseBean update(@RequestBody BookDto bookDto) throws IOException {
+        // 构造HTTP请求
+        /*Request request = new Request("POST", new StringBuilder("/book/book/")
+                .append(bookDto.getId()).append("/_update").toString());*/
+        Request request = new Request("PUT", new StringBuilder("/book/book/")
+                .append(bookDto.getId()).toString());
+        // 设置其他一些参数比如美化Json
+        request.addParameter("pretty", "true");
+        /*// 将数据丢进去,这里一定要外包一层'doc',否则内部不能识别
+        JSONObject jsonObject = new JSONObject();
+        jsonObject.put("doc", new JSONObject(bookDto));*/
+        // 设置请求体并指定ContentType,如果不指定会乱码
+        request.setEntity(new NStringEntity(JSONObject.toJSONString(bookDto), ContentType.APPLICATION_JSON));
+        // 执行HTTP请求
+        Response response = restClient.performRequest(request);
+        // 获取返回的内容
+        String responseBody = EntityUtils.toString(response.getEntity());
+        return new ResponseBean(HttpStatus.OK.value(), "更新成功", JSON.parseObject(responseBody));
+    }
+
+    /**
+     * 使用脚本更新Name
+     *
+     * @param id
+	 * @param bookDto
+     * @return org.springframework.http.ResponseEntity<java.lang.String>
+     * @throws IOException
+     * @author wliduo[i@dolyw.com]
+     * @date 2019/8/9 11:37
+     */
+    @PutMapping("/book/{id}")
+    public ResponseEntity<String> update2(@PathVariable("id") String id, @RequestBody BookDto bookDto) throws IOException {
+        // 构造HTTP请求
+        Request request = new Request("POST", new StringBuilder("/book/book/")
+                .append(id).append("/_update").toString());
+        // 设置其他一些参数比如美化Json
+        request.addParameter("pretty", "true");
+        JSONObject jsonObject = new JSONObject();
+        // 创建脚本语言,如果是字符变量,必须加单引号
+        StringBuilder op1 = new StringBuilder("ctx._source.name=").append("'" + bookDto.getName() + "'");
+        jsonObject.put("script", op1);
+        request.setEntity(new NStringEntity(jsonObject.toString(), ContentType.APPLICATION_JSON));
+        // 执行HTTP请求
+        Response response = restClient.performRequest(request);
+        // 获取返回的内容
+        String responseBody = EntityUtils.toString(response.getEntity());
+        return new ResponseEntity<>(responseBody, HttpStatus.OK);
+    }
+
+    /**
+     * 根据ID删除
+     *
+     * @param id
+     * @return org.springframework.http.ResponseEntity<java.lang.String>
+     * @throws IOException
+     * @author wliduo[i@dolyw.com]
+     * @date 2019/8/8 17:54
+     */
+    @DeleteMapping("/book/{id}")
+    public ResponseBean deleteById(@PathVariable("id") String id) throws IOException {
+        Request request = new Request("DELETE", new StringBuilder("/book/book/")
+                .append(id).toString());
+        request.addParameter("pretty", "true");
+        // 执行HTTP请求
+        Response response = restClient.performRequest(request);
+        // 获取结果
+        String responseBody = EntityUtils.toString(response.getEntity());
+        return new ResponseBean(HttpStatus.OK.value(), "删除成功", JSON.parseObject(responseBody));
+    }
+}

+ 98 - 0
src/main/java/com/example/controller/test.java

@@ -0,0 +1,98 @@
+package com.example.controller;
+
+import javax.imageio.ImageIO;
+import javax.swing.*;
+import java.awt.*;
+import java.awt.image.BufferedImage;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.InputStream;
+import java.security.MessageDigest;
+
+public class test {
+
+    // test
+    public static void main(String[] args) {
+//        System.out.println(getMD5Code("你若安好,便是晴天"));
+        transferAlpha();
+    }
+
+    public static byte[] transferAlpha() {
+
+        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
+        File file = new File("D:\\08\\11.png");
+        InputStream is;
+        try {
+            is = new FileInputStream(file);
+            // 如果是MultipartFile类型,那么自身也有转换成流的方法:is = file.getInputStream();
+            BufferedImage bi = ImageIO.read(is);
+            Image image = (Image) bi;
+            ImageIcon imageIcon = new ImageIcon(image);
+            BufferedImage bufferedImage = new BufferedImage(imageIcon.getIconWidth(), imageIcon.getIconHeight(),
+                    BufferedImage.TYPE_4BYTE_ABGR);
+            Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics();
+            g2D.drawImage(imageIcon.getImage(), 0, 0, imageIcon.getImageObserver());
+            int alpha = 0;
+            for (int j1 = bufferedImage.getMinY(); j1 < bufferedImage.getHeight(); j1++) {
+                for (int j2 = bufferedImage.getMinX(); j2 < bufferedImage.getWidth(); j2++) {
+                    int rgb = bufferedImage.getRGB(j2, j1);
+
+                    int R = (rgb & 0xff0000) >> 16;
+                    int G = (rgb & 0xff00) >> 8;
+                    int B = (rgb & 0xff);
+                    if (((255 - R) < 30) && ((255 - G) < 30) && ((255 - B) < 30)) {
+                        rgb = ((alpha + 1) << 24) | (rgb & 0x00ffffff);
+                    }
+
+                    bufferedImage.setRGB(j2, j1, rgb);
+
+                }
+            }
+
+            g2D.drawImage(bufferedImage, 0, 0, imageIcon.getImageObserver());
+            ImageIO.write(bufferedImage, "png", new File("D:\\08\\12.png"));// 直接输出文件
+        } catch (Exception e) {
+            e.printStackTrace();
+        } finally {
+
+        }
+        return byteArrayOutputStream.toByteArray();
+    }
+
+    // md5加密
+    public static String getMD5Code(String message) {
+        String md5Str = "";
+        try {
+            //创建MD5算法消息摘要
+            MessageDigest md = MessageDigest.getInstance("MD5");
+            //生成的哈希值的字节数组
+            byte[] md5Bytes = md.digest(message.getBytes());
+            md5Str = bytes2Hex(md5Bytes);
+        }catch(Exception e) {
+            e.printStackTrace();
+        }
+        return md5Str;
+    }
+
+    // 2进制转16进制
+    public static String bytes2Hex(byte[] bytes) {
+        StringBuffer result = new StringBuffer();
+        int temp;
+        try {
+            for (int i = 0; i < bytes.length; i++) {
+                temp = bytes[i];
+                if(temp < 0) {
+                    temp += 256;
+                }
+                if (temp < 16) {
+                    result.append("0");
+                }
+                result.append(Integer.toHexString(temp));
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return result.toString();
+    }
+}

+ 10 - 0
src/main/java/com/example/dao/EsDemoMapper.java

@@ -0,0 +1,10 @@
+package com.example.dao;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.example.pojo.EsDemo;
+import org.springframework.stereotype.Component;
+
+@Component
+public interface EsDemoMapper extends BaseMapper<EsDemo> {
+
+}

+ 11 - 0
src/main/java/com/example/dao/EsOtherMapper.java

@@ -0,0 +1,11 @@
+package com.example.dao;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.example.pojo.EsDemo;
+import com.example.pojo.EsOther;
+import org.springframework.stereotype.Component;
+
+@Component
+public interface EsOtherMapper extends BaseMapper<EsOther> {
+
+}

+ 18 - 0
src/main/java/com/example/exception/CustomException.java

@@ -0,0 +1,18 @@
+package com.example.exception;
+
+/**
+ * 自定义异常(CustomException)
+ *
+ * @author wliduo[i@dolyw.com]
+ * @date 2018/8/30 13:59
+ */
+public class CustomException extends RuntimeException {
+
+    public CustomException(String msg){
+        super(msg);
+    }
+
+    public CustomException() {
+        super();
+    }
+}

+ 18 - 0
src/main/java/com/example/exception/SystemException.java

@@ -0,0 +1,18 @@
+package com.example.exception;
+
+/**
+ * 系统异常(SystemException)
+ *
+ * @author wliduo[i@dolyw.com]
+ * @date 2018/8/30 13:59
+ */
+public class SystemException extends RuntimeException {
+
+    public SystemException(String msg){
+        super(msg);
+    }
+
+    public SystemException() {
+        super();
+    }
+}

+ 66 - 0
src/main/java/com/example/model/BookDto.java

@@ -0,0 +1,66 @@
+package com.example.model;
+
+
+import java.io.Serializable;
+
+/**
+ * BookDto
+ *
+ * @author wliduo[i@dolyw.com]
+ * @date 2019/8/19 18:57
+ */
+public class BookDto implements Serializable {
+
+    /**
+     * Id
+     */
+    private Long id;
+
+    /**
+     * 名称
+     */
+    private String name;
+
+    /**
+     * 描述
+     */
+    private String desc;
+
+    /**
+     * 空构造方法
+     */
+    public BookDto() {}
+
+    /**
+     * 构造赋值方法
+     */
+    public BookDto(Long id, String name, String desc) {
+        this.id = id;
+        this.name = name;
+        this.desc = desc;
+    }
+
+    public Long getId() {
+        return id;
+    }
+
+    public void setId(Long id) {
+        this.id = id;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public String getDesc() {
+        return desc;
+    }
+
+    public void setDesc(String desc) {
+        this.desc = desc;
+    }
+}

+ 30 - 0
src/main/java/com/example/model/NewsDto.java

@@ -0,0 +1,30 @@
+package com.example.model;
+
+import lombok.*;
+
+import java.io.Serializable;
+
+/**
+ * BookDto
+ *
+ * @author wliduo[i@dolyw.com]
+ * @date 2019/8/19 18:57
+ */
+@Data
+public class NewsDto implements Serializable {
+
+    private String title;
+
+    private String type;
+
+    private String date;
+
+    private String url;
+
+    private String source;
+
+    private String content;
+
+    private String subtitle;
+
+}

+ 28 - 0
src/main/java/com/example/pojo/EsDemo.java

@@ -0,0 +1,28 @@
+package com.example.pojo;
+
+import com.baomidou.mybatisplus.annotation.IdType;
+import com.baomidou.mybatisplus.annotation.TableId;
+import com.baomidou.mybatisplus.annotation.TableName;
+import lombok.*;
+
+import java.io.Serializable;
+
+
+@Getter
+@Setter
+@NoArgsConstructor
+@AllArgsConstructor
+@Builder
+@TableName("es_demo")
+public class EsDemo implements Serializable {
+
+
+    private Integer id;
+    private String title;
+    private String subTitle;
+    private String source;
+    private String type;
+    private String url;
+    private String content;
+    private String date;
+}

+ 26 - 0
src/main/java/com/example/pojo/EsOther.java

@@ -0,0 +1,26 @@
+package com.example.pojo;
+
+import com.baomidou.mybatisplus.annotation.TableName;
+import lombok.*;
+
+import java.io.Serializable;
+
+
+@Getter
+@Setter
+@NoArgsConstructor
+@AllArgsConstructor
+@Builder
+@TableName("es_other")
+public class EsOther implements Serializable {
+
+
+    private Integer id;
+    private String title;
+    private String subTitle;
+    private String source;
+    private String type;
+    private String url;
+    private String content;
+    private String date;
+}

+ 17 - 0
src/main/java/com/example/service/EsDemoService.java

@@ -0,0 +1,17 @@
+package com.example.service;
+
+
+import com.baomidou.mybatisplus.extension.service.IService;
+import com.example.pojo.EsDemo;
+
+import java.io.IOException;
+import java.util.Map;
+
+public interface EsDemoService  extends IService<EsDemo>{
+
+    Map<String,Object> importMysqlDataToEs() throws IOException;
+
+    Map<String, Object> compareMysqlDataToEs() throws IOException;
+
+    Map<String, Object> selEs() throws IOException;
+}

+ 13 - 0
src/main/java/com/example/service/EsOtherService.java

@@ -0,0 +1,13 @@
+package com.example.service;
+
+
+import com.baomidou.mybatisplus.extension.service.IService;
+import com.example.pojo.EsDemo;
+import com.example.pojo.EsOther;
+
+import java.io.IOException;
+import java.util.Map;
+
+public interface EsOtherService extends IService<EsOther>{
+
+}

+ 478 - 0
src/main/java/com/example/service/impl/EsDemoServiceImpl.java

@@ -0,0 +1,478 @@
+package com.example.service.impl;
+
+import com.alibaba.fastjson.JSON;
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.example.dao.EsDemoMapper;
+import com.example.dao.EsOtherMapper;
+import com.example.pojo.EsDemo;
+import com.example.pojo.EsOther;
+import com.example.service.EsDemoService;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
+import org.elasticsearch.action.bulk.BulkRequest;
+import org.elasticsearch.action.bulk.BulkRequestBuilder;
+import org.elasticsearch.action.bulk.BulkResponse;
+import org.elasticsearch.action.delete.DeleteRequest;
+import org.elasticsearch.action.get.GetRequest;
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.action.search.SearchRequest;
+import org.elasticsearch.action.search.SearchRequestBuilder;
+import org.elasticsearch.action.search.SearchResponse;
+import org.elasticsearch.action.update.UpdateRequest;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.common.xcontent.XContentType;
+import org.elasticsearch.index.query.*;
+import org.elasticsearch.script.Script;
+import org.elasticsearch.search.SearchHit;
+import org.elasticsearch.search.SearchHits;
+import org.elasticsearch.search.builder.SearchSourceBuilder;
+import org.springframework.beans.BeanUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import javax.swing.filechooser.FileSystemView;
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
+
+/**
+ * @program: 01-SpringBoot-ES-Local
+ * @description: EsDemoServiceImpl
+ * @author: Guanzi
+ * @created: 2021/10/14 15:31
+ */
+@Slf4j
+@Service
+public class EsDemoServiceImpl extends ServiceImpl<EsDemoMapper,EsDemo> implements EsDemoService {
+
+//    @Autowired
+//    private EsDemoMapper esDemoMapper;
+
+    private static final String IndexRequest = "bd-es";
+    private static final String indexType = "dome220308";
+
+
+    @Autowired
+    @Qualifier("restHighLevelClient")
+    private RestHighLevelClient client;
+
+    @Resource
+    private EsDemoMapper esDemoMapper;
+
+
+    @Resource
+    private EsOtherMapper esOtherMapper;
+//
+    @Autowired
+    private EsDemoService esDemoService;
+
+    @Autowired
+    private EsOtherServiceImpl esOtherService;
+
+    public Map<String, Object> selEs() throws IOException {
+        // 返回信息。
+        Map<String,Object> map = new HashMap<>();
+//        SearchResponse searchResp = searchByParam("id","10");
+//        System.out.println("total:" + searchResp.getHits().getTotalHits());
+//        int pageNum = 8;
+//        int one = 0;
+//        int two = 5000;
+        int pageNum = 123;
+        int one = 0;
+        int two = 5000;
+        for (int i1 = 1; i1 < pageNum; i1++) {
+            one = (i1 - 1) * two;
+            String limitStr = "limit " + one + "," + two;
+            QueryWrapper<EsDemo> esDemoQueryWrapper = new QueryWrapper<>();
+            esDemoQueryWrapper.lambda()
+                    .isNotNull(true, EsDemo::getId)
+//                    .like(true,EsDemo::getDate,"[")
+//                    .or()
+//                    .like(true,EsDemo::getDate,":")
+                    .last(limitStr);
+            List<EsDemo> demos = esDemoMapper.selectList(esDemoQueryWrapper);
+            System.err.println("sel from mysql:" + demos.size());
+            // 插入30241多数据
+            List<EsDemo> esDemos = new ArrayList<>();
+            for (EsDemo demo : demos) {
+                String date = demo.getDate();
+                System.err.println(date);
+                date = StringUtils.remove(date,"[");
+                date = StringUtils.remove(date,"]");
+                date = StringUtils.substringBeforeLast(date," ");
+                date = StringUtils.remove(date," ");
+                System.out.println("deal date:" + date);
+                demo.setDate(date);
+                esDemos.add(demo);
+            }
+//            System.err.println(JSON.toJSONString(esDemos));
+            System.out.println(esDemos.get(0).getDate());
+//           if (esDemos.size() == 3){
+//               break;
+//           }
+            if (esDemos.size() > 0){
+                // 批量导入es库。
+                BulkRequest bulkRequest = new BulkRequest();
+                bulkRequest.timeout("100000s");
+
+                System.err.println("demos size:" + demos.size());
+                // 批处理请求。
+                for (int i = 0; i < esDemos.size(); i++) {
+                    bulkRequest.add(
+//                     new IndexRequest("es_test_demo")
+//                            new IndexRequest("es_new_demo")
+                            new IndexRequest(IndexRequest)
+//                                    .type("dome210929")
+                                    .type(indexType)
+                                    .source(JSON.toJSONString(esDemos.get(i)), XContentType.JSON)
+                    );
+                }
+                BulkResponse bulkResp = client.bulk(bulkRequest, RequestOptions.DEFAULT);
+
+                System.err.println("current insert data:" + JSON.toJSONString(esDemos));
+                System.err.println("current insert data:" + esDemos.get(0).getId());
+                System.err.println("inset result:" + bulkResp.hasFailures()); // 是否失败,返回false 代表成功。
+
+                if (false == bulkResp.hasFailures()){
+                    map.put("mes","SUCC");
+                }else {
+                    map.put("mes","fail");
+                }
+//                break;
+            }
+
+//            break;
+        }
+        return map;
+
+    }
+
+    public Map<String, Object> compareMysqlDataToEs() throws IOException {
+        // 返回信息。
+        Map<String,Object> map = new HashMap<>();
+        int pageNum = 8;
+        int one = 0;
+        int two = 5000;
+        for (int i1 = 1; i1 < pageNum; i1++) {
+            one = (i1-1)*two;
+            String limitStr = "limit " + one + "," + two;
+            QueryWrapper<EsDemo> esDemoQueryWrapper = new QueryWrapper<>();
+            esDemoQueryWrapper.lambda()
+                    .isNotNull(true, EsDemo::getId)
+                    .last(limitStr);
+            List<EsDemo> demos = esDemoMapper.selectList(esDemoQueryWrapper);
+            System.err.println("sel from mysql:" + JSON.toJSONString(demos));
+
+            List<EsDemo> esDemos = new ArrayList<>();
+            for (EsDemo demo : demos) {
+                SearchResponse searchResp = searchByParam("id",demo.getId().toString());
+                System.out.println("total:" + searchResp.getHits().getTotalHits());
+                long total = searchResp.getHits().getTotalHits();
+                if (total == 0){
+                    esDemos.add(demo);
+                }
+
+            }
+
+            if (esDemos.size() > 0){
+                // 批量导入es库。
+                BulkRequest bulkRequest = new BulkRequest();
+                bulkRequest.timeout("100000s");
+
+                System.err.println("demos size:" + demos.size());
+                // 批处理请求。
+                for (int i = 0; i < esDemos.size(); i++) {
+                    bulkRequest.add(
+//                     new IndexRequest("es_test_demo")
+                            new IndexRequest(IndexRequest)
+                                    .type(indexType)
+                                    .source(JSON.toJSONString(esDemos.get(i)), XContentType.JSON)
+                    );
+                }
+                BulkResponse bulkResp = client.bulk(bulkRequest, RequestOptions.DEFAULT);
+
+                System.err.println("current insert data:" + JSON.toJSONString(esDemos));
+                System.err.println("current insert data:" + esDemos.get(0).getId());
+                System.err.println("inset result:" + bulkResp.hasFailures()); // 是否失败,返回false 代表成功。
+
+                if (false == bulkResp.hasFailures()){
+                    map.put("mes","SUCC");
+                }else {
+                    map.put("mes","fail");
+                }
+                break;
+            }
+
+
+        }
+        return map;
+    }
+
+    @Autowired
+    private RestHighLevelClient restHighLevelClient;
+
+    public long findEs(String id) throws IOException {
+        // 搜索请求对象
+        SearchRequest searchRequest = new SearchRequest("bd-es");
+        // 指定类型
+        searchRequest.types("dome220308");
+        // 搜索源构建对象
+        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
+        // 搜索方式
+        // matchAllQuery搜索全部
+//        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
+        searchSourceBuilder.query(QueryBuilders.termQuery("id", id));
+        // 设置源字段过虑,第一个参数结果集包括哪些字段,第二个参数表示结果集不包括哪些字段
+//        searchSourceBuilder.fetchSource(new String[]{"name","studymodel","price","timestamp"},new String[]{});
+        // 向搜索请求对象中设置搜索源
+        searchRequest.source(searchSourceBuilder);
+        // 执行搜索,向ES发起http请求
+        SearchResponse searchResponse = client.search(searchRequest);
+        // 搜索结果
+        SearchHits hits = searchResponse.getHits();
+        // 匹配到的总记录数
+        long totalHits = hits.getTotalHits();
+        System.err.println(totalHits);
+        return totalHits;
+    }
+
+    // 数据丢失后再次导入mysql后,移入es。
+    public Map<String, Object> importMysqlDataToEsOther() throws IOException {
+        // 返回信息。
+        Map<String,Object> map = new HashMap<>();
+//        int i = 609165;
+        int pageNum = 134;
+        int one = 0;
+        int two = 5000;
+//        (pageNum-1)*pageSize
+        for (int i1 = 1; i1 < pageNum; i1++) {
+            one = (i1-1)*two;
+            String limitStr = "limit " + one + "," + two;
+            QueryWrapper<EsDemo> esDemoQueryWrapper = new QueryWrapper<>();
+            esDemoQueryWrapper.lambda()
+                    .isNotNull(true, EsDemo::getId)
+                    .last(limitStr);
+            List<EsDemo> demos = esDemoMapper.selectList(esDemoQueryWrapper);
+            System.err.println("sel from mysql:" + JSON.toJSONString(demos));
+            List<EsDemo> otherDemo = new ArrayList<>();
+            for (EsDemo demo : demos) {
+                // 获取总数
+                long es = findEs(demo.getId().toString());
+                if (es <= 0){
+                    otherDemo.add(demo);
+                }
+            }
+            System.err.println("otherDemo:" + JSON.toJSONString(otherDemo));
+            List<EsOther> esOthers = new ArrayList<>();
+            EsOther esOther;
+            for (EsDemo esDemo : otherDemo) {
+                esOther = new EsOther();
+                BeanUtils.copyProperties(esDemo,esOther);
+                esOther.setId(esDemo.getId());
+                esOthers.add(esOther);
+            }
+
+            esOtherService.saveBatch(esOthers);
+        }
+        return map;
+    }
+
+    @Override
+    // 自然导入数据。
+    public Map<String, Object> importMysqlDataToEs() throws IOException {
+        // 返回信息。
+        Map<String,Object> map = new HashMap<>();
+//        int i = 609165;
+        int pageNum = 6;
+        int one = 0;
+        int two = 5000;
+        for (int i1 = 1; i1 < pageNum; i1++) {
+            one = (i1-1)*two;
+            String limitStr = "limit " + one + "," + two;
+
+            // 正常导入。
+//            QueryWrapper<EsDemo> esDemoQueryWrapper = new QueryWrapper<>();
+//            esDemoQueryWrapper.lambda()
+//                    .isNotNull(true, EsDemo::getId)
+//                    .last(limitStr);
+//            List<EsDemo> demos = esDemoMapper.selectList(esDemoQueryWrapper);
+
+            // 部分未导入成功,再次从新库导入。
+            QueryWrapper<EsOther> esOtherQueryWrapper = new QueryWrapper<>();
+            esOtherQueryWrapper.lambda()
+                    .isNotNull(true, EsOther::getId)
+                    .last(limitStr);
+            List<EsOther> demos = esOtherMapper.selectList(esOtherQueryWrapper);
+
+            // 批量导入es库。
+            BulkRequest bulkRequest = new BulkRequest();
+            bulkRequest.timeout("100000s");
+
+            // 批量删除
+//         SearchResponse searchResp = searchByParam("source","能");
+//         System.out.println("total:" + searchResp.getHits().getTotalHits());
+//         EsDemo esDemo;
+//         List<EsDemo> esDemos = new ArrayList<>();
+//         List<EsDemo> failedEsDemos = new ArrayList<>();
+//         for(SearchHit hit : searchResp.getHits()){
+//             String id = hit.getId();
+//             System.out.println("id:" + id);
+//             Map<String,Object> map = hit.getSourceAsMap();
+//             System.err.println("map:" + JSON.toJSONString(map));
+//             EsDemo esDemo1 = JSON.parseObject(JSON.toJSONString(map), EsDemo.class);
+////             int insert = esDemoMapper.insert(esDemo1);
+////             if (insert <= 0){
+////                 failedEsDemos.add(esDemo1);
+////             }
+//             esDemos.add(esDemo1);
+//
+//             // 批量删除
+//             // bulkRequest.add(
+//             //         new DeleteRequest("es_test_demo")
+//             //         .id(id)
+//             // );
+////             break;
+//         }
+//        System.err.println("****************** esDemos siZe:" + esDemos.size());
+//        System.err.println("esDemos:" + JSON.toJSONString(esDemos));
+//        System.err.println("failedEsDemos:" + JSON.toJSONString(failedEsDemos));
+//         // 插入数据库
+//        boolean b = esDemoService.saveBatch(esDemos);
+//        System.err.println("b:" + b);
+
+
+            // 批量更新
+            // for (int i = 0; i < demos.size(); i++) {
+            //     SearchResponse searchUpResp = searchByParam("title", demos.get(i).getTitle());
+            //     for (SearchHit hit : searchUpResp.getHits()) {
+            //         String id = hit.getId();
+            //         Map<String,Object> map = hit.getSourceAsMap();
+            //         System.out.println(JSON.toJSONString(map));
+            //         // 批量更新
+            //         bulkRequest.add(
+            //                 new UpdateRequest()
+            //                         .index("es_test_demo")
+            //                         .id(id)
+            //                 .upsert(JSON.toJSONString(demos.get(i)),XContentType.JSON)
+            //         );
+            //     }
+            //
+            // }
+
+            // SearchResponse searchUpResp = searchByParam("title", demos.get(0).getTitle());
+//        for (SearchHit hit : searchUpResp.getHits()) {
+//            System.err.println(searchUpResp.getHits().totalHits);
+//            Map<String,Object> map = hit.getSourceAsMap();
+//             System.out.println(JSON.toJSONString(map));
+//
+//        SearchResponse searchUpResp = searchByParam("title", "铁");
+//        SearchResponse searchUpResp = searchByParam("date", "20");
+//            // EsDemo esDemo = JSON.parseObject(JSON.toJSONString(map),EsDemo.class);
+//            Map<String,Object> selMap = new HashMap<>();
+//            selMap.put("title",map.get("title"));
+//            if (map.containsKey("date")){
+//                String date = map.get("date").toString();
+//                System.out.println("1:" + date);
+//                date = StringUtils.remove(date,"[");
+//                date = StringUtils.remove(date,"]");
+//                date = StringUtils.removeFirst(date," ");
+//
+//                System.out.println("2:" + date);
+//
+//                map.put("date",date);
+//                selMap.put("date",date);
+//
+//                System.out.println("map:" + JSON.toJSONString(map));
+//                System.out.println("selMap:" + JSON.toJSONString(selMap));
+////            System.err.println(map.get("title"));
+////            List<EsDemo> esDemos = esDemoMapper.selectByMap(selMap);
+////            if (esDemos.size() > 0){
+////                System.out.println("2:" + esDemos.get(0).getContent());
+////                map.put("content","eeeeeeeeee" + esDemos.get(0).getContent());
+////                System.out.println("2:" + map.get("content"));
+////            }
+//
+//                System.out.println("3:" + map.get("title"));
+//                System.err.println("33:" + map.get("id"));
+//                System.err.println("333:" + hit.getId());
+//                // 批量更新
+//                bulkRequest.add(
+//                        new UpdateRequest()
+//                                .index("es_test_demo")
+//                                .type("dome210929")
+//                                .id(hit.getId())
+//                                .doc(XContentType.JSON, "date", map.get("date").toString()).upsert()
+//                );
+////                break;
+//            }
+//        }
+
+            System.err.println("demos size:" + demos.size());
+            // 批处理请求。
+            for (int i = 0; i < demos.size(); i++) {
+                bulkRequest.add(
+//                     new IndexRequest("es_test_demo")
+                        new IndexRequest(IndexRequest)
+                                .type(indexType)
+                                .source(JSON.toJSONString(demos.get(i)), XContentType.JSON)
+                );
+            }
+            BulkResponse bulkResp = client.bulk(bulkRequest, RequestOptions.DEFAULT);
+            System.err.println("导入结果:" + bulkResp.hasFailures()); // 是否失败,返回false 代表成功。
+
+            if (false == bulkResp.hasFailures()){
+                map.put("mes","SUCC");
+            }else {
+                map.put("mes","fail");
+            }
+        }
+        return map;
+    }
+
+    public SearchResponse searchByParam(String key,String val) throws IOException {
+        log.info("key:{},val:{}",key,val);
+//        SearchRequest searchRequest = new SearchRequest("es_new_demo");
+        SearchRequest searchRequest = new SearchRequest("bd-es");
+        // SearchRequest searchRequest = new SearchRequest("es_dome");
+        // 构建搜索条件
+        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
+
+        // 查询条件,用QueryBuilders实现
+        //         QueryBuilders.matchAllQuery() // 匹配所有。
+
+        // QueryBuilders.termQuery 精确查找
+        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery(key,val);
+//        QueryBuilder termQueryBuilder = QueryBuilders.matchQuery(key,val);
+
+//         MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
+        Integer page = 1;
+        // Integer rows = 3568;
+        Integer rows = 609165;
+//        Integer page = 7;
+//        Integer rows = 100000;
+        searchSourceBuilder.from((page - 1) * rows);
+        searchSourceBuilder.size(rows);
+//        searchSourceBuilder.sort("")
+        searchSourceBuilder.query(termQueryBuilder);
+        searchSourceBuilder.timeout(new TimeValue(600000, TimeUnit.SECONDS));
+
+        searchRequest.source(searchSourceBuilder);
+
+        SearchResponse searchResp = client.search(searchRequest, RequestOptions.DEFAULT);
+        System.out.println("search total:" + searchResp.getHits().getTotalHits());
+        return searchResp;
+    }
+}

+ 52 - 0
src/main/java/com/example/service/impl/EsOtherServiceImpl.java

@@ -0,0 +1,52 @@
+package com.example.service.impl;
+
+import com.alibaba.fastjson.JSON;
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.example.dao.EsDemoMapper;
+import com.example.dao.EsOtherMapper;
+import com.example.pojo.EsDemo;
+import com.example.pojo.EsOther;
+import com.example.service.EsDemoService;
+import com.example.service.EsOtherService;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
+import org.elasticsearch.action.bulk.BulkRequest;
+import org.elasticsearch.action.bulk.BulkResponse;
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.action.search.SearchRequest;
+import org.elasticsearch.action.search.SearchResponse;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestHighLevelClient;
+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.SearchHits;
+import org.elasticsearch.search.builder.SearchSourceBuilder;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * @program: 01-SpringBoot-ES-Local
+ * @description: EsDemoServiceImpl
+ * @author: Guanzi
+ * @created: 2021/10/14 15:31
+ */
+@Slf4j
+@Service
+public class EsOtherServiceImpl extends ServiceImpl<EsOtherMapper, EsOther> implements EsOtherService {
+
+}

+ 21 - 0
src/main/resources/application.yml

@@ -0,0 +1,21 @@
+server:
+    port: 8076
+
+spring:
+    thymeleaf:
+        # 开发时关闭缓存不然没法看到实时页面
+        cache: false
+        # 启用不严格检查
+#        mode: LEGACYHTML5
+        mode: HTML5
+        prefix: classpath:/templates/
+    datasource:
+        url: jdbc:mysql://localhost:3306/es_demo_3?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT
+        driver-class-name: com.mysql.cj.jdbc.Driver
+        username: root
+        password: root
+# Elasticsearch配置
+elasticsearch:
+#    hostname: 127.0.0.1
+    hostname: 192.168.0.202
+    port: 9200

+ 95 - 0
src/main/resources/banner.txt

@@ -0,0 +1,95 @@
+@@@@@@@@@@@@@@@@@##w@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@$k$w@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@$k##$kkw@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#k$w@w$k@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@w$@kk$@@k#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#$@#ktdw##@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@k@t    t@d@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@k@j    j@d@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@k@i     $##@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@##$     .@d@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@k@.     d@$@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@$@t     .@dw@@@@@@@@@@@@@
+@@@@@@@@@@#kkk$@.     t@k@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@$@t     .@#$kdk@@@@@@@@@@
+@@@@@@@@@k#@w##d      d@$@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#wd      tk$#@wd@@@@@@@@@
+@@@@@@@@w$wi          $#w@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@$#          .##$@@@@@@@@
+@@@@@@@@k@t          .@$w@@@@@@@@@@@@@@@@@@@w#kddttddk#w@@@@@@@@@@@@@@@@@@@#$@.          t@d@@@@@@@@
+@@@@@@@@k@j           d@kw@@@@@@@@@@@@@@#djijdk$###$$kdjijd#@@@@@@@@@@@@@@#$@t           t@d@@@@@@@@
+@@@@@@@@$wd            d@kw@@@@@@@@@@wditkw@@@@@@@@@@@@@@wkjidw@@@@@@@@@@#$@t            kw$@@@@@@@@
+@@@@@@@@@kw.     .      d@k#@@@@@@@#jj$@@@@@@@@@@@@@@@@@@@@@@$jj#@@@@@@@#$@j     .i     .wk@@@@@@@@@
+@@@@@@@@@d@k.  .d@k      d@k#@@@@#jtw@@@@@@@@@@@@@@@@@@@@@@@@@@#jj#@@@@#$@j     .$@$j. .$@d@@@@@@@@@
+@@@@@@@@@wk@w$#@@$@d      t@k#@@tjw@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#jd@@#$@j     .$@kw@@w@@d@@@@@@@@@@
+@@@@@@@@@@wkk$kkk#k@d      t@$ki$@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@kik#@j     .$@dw#kkkkk@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@@wk@d      t@$w@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@w#@j     .k@dw@@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@@@wk@d     .$@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@k     .$@dw@@@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@@@@wk@k   .$@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@k.  .$@dw@@@@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@@@@@wk@d .$@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@k..$@dw@@@@@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@@@@@@wk@d$@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@k$@dw@@@@@@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@@@@@@@wd@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@tw@@@@@@@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@@@@@@@kd@@@@@@@@@@@@@@@@@@@@$dji...ijd$w@@@@@@@@@@@@@@@@@@jk@@@@@@@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@@@@@@#j@@@@@@@@@@@@@@@@@@$j.            ik@@@@@@@@@@@@@@@@@iw@@@@@@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@@@@@@jw@@@@@@@@@@@@@@@@$i                 .d@@@@@@@@@@@@@@@#j@@@@@@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@@@@@kk@@@@@@@@@@@@@@@wi                     .$@@@@@@@@@@@@@@dk@@@@@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@@@@@j@@@@@@@@@@@@@@@k.                        t@@@@@@@@@@@@@@i@@@@@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@@@@d#@@@@@@@@@@@@@@d                           iw@@@@@@@@@@@@$d@@@@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@@@@j@@@@@@@@@@@@@@t                             iw@@@@@@@@@@@@i@@@@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@@@d#@@@@@@@@@@@@@d                               i@@@@@@@@@@@@kk@@@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@@@j@@@@@@@@@@@@@k  ..ijtdkk$$####ww###$$$kdttji.  j@@@@@@@@@@@@i@@@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@@#k@@@@@@@@@@@@@$#w@@@@@@@@@@@@@@@@@@@@@@@@@@@@@w#$w@@@@@@@@@@@t#@@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@@dw@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#t@@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@@j@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@i@@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@wd@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@tw@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@k$@@@@@@@@@@@@w#$kddtjjii...         .....iijjtdkk$#@@@@@@@@@@@@k$@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@wtw@@@@@#$dtj..          .ijtdk$$$$$$kkdtji.          .ijtk#w@@@@wd$@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@#k#@@#kti.            .jd$w@@@@w##$$$$$##w@@@@w$dj.            .id$w@@kdw@@@@@@@@@@@@@
+@@@@@@@@@@@@@k#@#t.              id#@@w$dji.             .ijd$w@@wkj.             idw@d$@@@@@@@@@@@@
+@@@@@@@@@@@@@t@t              .dw@@$ti                         .tkw@@$j.            .k@t@@@@@@@@@@@@
+@@@@@@@@@@@@@d#@#di         i$@@kj.                                id#@wd.         ik@#k@@@@@@@@@@@@
+@@@@@@@@@@@@@@$k$@@wkti    .wwt.                                      ik@t    .itkw@@kk@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@#k@@@@@@w$dd@i                                          w#d$#w@@@@$k$@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@wd@@@@@@@@@@@.       ikw@@#d.            .kw@@wki       #@@@@@@@@@tw@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@d@@@@@@@@@@@i     .k@@@@@@@@t          t@@@@@@@@d.     w@@@@@@@@@t@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@d@@@@@@@@@@@i    .$@@@@@@@@@@t        d@@@@@@@@@@$     w@@@@@@@@@j@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@t@@@@@@@@@@@j    d@@@@@@@@@@@@i      j@@@@@@@@@@@@t    @@@@@@@@@@j@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@t@@@@@@@@@@@d   .@@@@@@@@@@@@@$      #@@@@@@@@@@@@w.  .@@@@@@@@@@j@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@t@@@@@@@@@@@$   t@@@@@@@@@@@@@@.    .@@@@@@@@@@@@@@j  t@@@@@@@@@wd@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@k#@@@@@@@@@@@   d@@@@@@@@@@@@@@j    j@@@@@@@@@@@@@@d  k@@@@@@@@@$k@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@#k@@@@@@@@@@@i  k@@@@@@@@@@@@@@t    t@@@@@@@@@@@@@@k .w@@@@@@@@@dw@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@@t@@@@@@@@@@@k  d@@@@@@@@@@@@@@j    j@@@@@@@@@@@@@@d j@@@@@@@@@@j@@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@@d@@@@@@@@@@@@. j@@@@@@@@@@@@@@.    .@@@@@@@@@@@@@@j $@@@@@@@@@wt@@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@@#$@@@@@@@@@@@k .@@@@@@@@@@@@@$      #@@@@@@@@@@@@w.i@@@@@@@@@@k#@@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@@@t@@@@@@@@@@@@. d@@@@@@@@@@@@i      j@@@@@@@@@@@@t $@@@@@@@@@@j@@@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@@@dw@@@@@@@@@@@$  $@@@@@@@@@@t        d@@@@@@@@@@k t@@@@@@@@@@#k@@@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@@@wd@@@@@@@@@@@@t .k@@@@@@@@t  .d$ki   t@@@@@@@@d.iw@@@@@@@@@@t@@@@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@@@@d@@@@@@@@@@@@@i  ikw@@#d.   $@@@@i   .d#@@wki .#@@@@@@@@@@wd@@@@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@@@@wd@@@@@@@@@@@@@i           j@@@@@k           .$@@@@@@@@@@@tw@@@@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@@@@@kw@@@@@@@@@@@@wi          j@@@@@$          .$@@@@@@@@@@@$d@@@@@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@@@@@@t@@@@@@@@@@@@@@j         .@@@@@t         i#@@@@@@@@@@@@j@@@@@@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@@@@@@#k@@@@@@@@@@@@@@k.        t@@@$.        tw@@@@@@@@@@@@d#@@@@@@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@@@@@@@k#@@@@@@@@@@@@@@wt        .ji        i$@@@@@@@@@@@@@$k@@@@@@@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@@@@@@@@t@@@@@@@@@@@@@@@@wd.             .j$@@@@@@@@@@@@@@wt@@@@@@@@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@@@@@@@#$@@@@@@@@@@@@@@@@@@w$ti.      .tkww@@@@@@@@@@@@@@@@kw@@@@@@@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@@@@@@#$@jj@@@@@@@@@@@@@@@$.j@#www#www#wk..@@@@@@@@@@@@@wid@kw@@@@@@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@@@@@#$@t  j@@@@@@@@@@@@@@t j$  kti.w. tk  $@@@@@@@@@@@wi  d@kw@@@@@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@@@@#$@t    iw@@@@@@@@@@@@. dd  $j  w. .w .k@@@@@@@@@@#.    d@kw@@@@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@@@@@#$@j      k@@@@@@@@@@@ww$#j  $i  #i iw#wk#@@@@@@@@@t      d@kw@@@@@@@@@@@@@@@@@@@
+@@@@@@@@@@@@w##@@@#$@t      d@dd@@@@@@@@@j.t$@w#wkkkw#w@#j. t@@@@@@@tk@t      d@kw@@@ww@@@@@@@@@@@@@
+@@@@@@@@@@#d#w#kdk$@j     .k@dwwt$@@@@@@w    #jijtwtji.j#   .w@@@@$tw#k@d      d@k$k$##$kw@@@@@@@@@@
+@@@@@@@@@#$@#k$w@w@t     .k@kw@@@$dw@@@@d   .w.   w.   .w.  .$@@#t$@@@#k@d      d@#@w$k#@kw@@@@@@@@@
+@@@@@@@@@d@t    jwt     .$@dw@@@@@@kd#@@$i  tk    w.    $j.tww#t$@@@@@@wk@d      dwj    d@d@@@@@@@@@
+@@@@@@@@w$#            .$@d@@@@@@@@@@#d$k#wk#t    w.    d#w$i#j@@@@@@@@@wk@d             wk@@@@@@@@@
+@@@@@@@@$@d           .$@d@@@@@@@@@@@@@tk it$ww$kdwddk$w#di j#d@@@@@@@@@@wk@k            k#$@@@@@@@@
+@@@@@@@@k@j          .$@d@@@@@@@@@@@@@@dwi    .jtddddti.   .wj@@@@@@@@@@@@wk@k           t@k@@@@@@@@
+@@@@@@@@k@t          .wk@@@@@@@@@@@@@@@wd$.               .$d$@@@@@@@@@@@@@w$w           kw$@@@@@@@@
+@@@@@@@@w$@d..        $##@@@@@@@@@@@@@@@k$k.             .#kk@@@@@@@@@@@@@@#wk         .d@kw@@@@@@@@
+@@@@@@@@@$k@@@@#.     d@$@@@@@@@@@@@@@@@@d$#i           jwdk@@@@@@@@@@@@@@@$@t     .#w@@@k$@@@@@@@@@
+@@@@@@@@@@wkkkk@.     t@k@@@@@@@@@@@@@@@@@kdwki       i$wj$@@@@@@@@@@@@@@@@k@j     i@kdddw@@@@@@@@@@
+@@@@@@@@@@@@@@k@.     d@$@@@@@@@@@@@@@@@@@@wtd#w$dddkw#td@@@@@@@@@@@@@@@@@@k@t     i@d@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@k@i     ##w@@@@@@@@@@@@@@@@@@@@wkttdddttkw@@@@@@@@@@@@@@@@@@@#wk     i@d@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@k@d   ik@d@@@@@@@@@@@@@@@@@@@@@@@@@@w@@@@@@@@@@@@@@@@@@@@@@@@@k@d.   k@k@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@wk@w#w@@dw@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@wk@@w$#@d@@@@@@@@@@@@@@@
+@@@@@@@@@@@@@@@#dk$kkk@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@wddk$$d#@@@@@@@@@@@@@@@
+         88               88
+         88               88
+         88               88
+ ,adPPYb,88   ,adPPYba,   88  8b       d8  8b      db      d8
+a8"    `Y88  a8"     "8a  88  `8b     d8'  `8b    d88b    d8'
+8b       88  8b       d8  88   `8b   d8'    `8b  d8'`8b  d8'
+"8a,   ,d88  "8a,   ,a8"  88    `8b,d8'      `8bd8'  `8bd8'
+ `"8bbdP"Y8   `"YbbdP"'   88      Y88'         YP      YP
+                                  d8'
+                                 d8'

BIN
src/main/resources/static/element-ui/fonts/element-icons.ttf


BIN
src/main/resources/static/element-ui/fonts/element-icons.woff


File diff suppressed because it is too large
+ 0 - 0
src/main/resources/static/element-ui/index.css


File diff suppressed because it is too large
+ 0 - 0
src/main/resources/static/element-ui/index.js


BIN
src/main/resources/static/favicon.ico


BIN
src/main/resources/static/img/baidu.png


BIN
src/main/resources/static/img/logo.png


File diff suppressed because it is too large
+ 1 - 0
src/main/resources/static/js/axios.min.js


File diff suppressed because it is too large
+ 0 - 0
src/main/resources/static/js/moment.min.js


File diff suppressed because it is too large
+ 5 - 0
src/main/resources/static/js/vue.min.js


+ 45 - 0
src/main/resources/templates/common/common.html

@@ -0,0 +1,45 @@
+<!DOCTYPE html>
+<html xmlns:th="http://www.thymeleaf.org">
+
+<head th:fragment="headJq(title)">
+    <meta charset="utf-8"/>
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+    <title th:text="${title}">加载中</title>
+    <link rel="shortcut icon" th:href="@{/favicon.ico}" type="image/x-icon"/>
+    <!-- 引入jquery,Moment,socket.io -->
+    <!--<script th:src="@{js/jquery.min.js}"></script>
+    <script th:src="@{js/moment.min.js}"></script>
+    <script th:src="@{js/socket.io.js}"></script>-->
+</head>
+
+<head th:fragment="headVue(title)">
+    <meta charset="utf-8"/>
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+    <title th:text="${title}">加载中</title>
+    <link rel="shortcut icon" th:href="@{/favicon.ico}" type="image/x-icon"/>
+    <link rel="stylesheet" th:href="@{element-ui/index.css}">
+    <style>
+        /* elementUI的确认弹出框时页面右侧缩小5px的解决方法 */
+        body {
+            padding-right:0 !important;
+        }
+        /* elementUI的Table表头错位的解决方法 */
+        body .el-table th.gutter {
+            display: table-cell!important;
+        }
+        body .el-table colgroup.gutter {
+            display: table-cell!important;
+        }
+        label {
+            font-weight: 700;
+        }
+    </style>
+    <!-- 引入Vue,Element UI,Axios,Moment,socket.io -->
+    <script th:src="@{js/vue.min.js}"></script>
+    <script th:src="@{element-ui/index.js}"></script>
+    <script th:src="@{js/axios.min.js}"></script>
+    <script th:src="@{js/moment.min.js}"></script>
+    <!--<script th:src="@{js/socket.io.js}"></script>-->
+</head>
+
+</html>

+ 395 - 0
src/main/resources/templates/index.html

@@ -0,0 +1,395 @@
+<!DOCTYPE html>
+<html xmlns:th="http://www.thymeleaf.org">
+
+<head th:include="common/common :: headVue('ES搜索服务')"></head>
+
+<style>
+	.clearfix:before,
+	.clearfix:after {
+		display: table;
+		content: "";
+	}
+	.clearfix:after {
+		clear: both
+	}
+
+	/* 谷歌浏览器滚动条美化 */
+	::-webkit-scrollbar {
+		width: 15px;
+		height: 15px;
+	}
+
+	::-webkit-scrollbar-track,
+	::-webkit-scrollbar-thumb {
+		border-radius: 999px;
+		border: 5px solid transparent;
+	}
+
+	::-webkit-scrollbar-track {
+		box-shadow: 1px 1px 5px rgba(143, 143, 143, 0.2) inset;
+	}
+
+	::-webkit-scrollbar-thumb {
+		min-height: 20px;
+		background-clip: content-box;
+		box-shadow: 0 0 0 5px rgba(143, 143, 143, 0.466) inset;
+	}
+
+	::-webkit-scrollbar-corner {
+		background: transparent;
+	}
+	.tabs{
+		display: flex;
+	}
+	.tabsn{
+		padding: 4px 20px;
+		border: 1px #e3e3e3 solid;
+		border-bottom: none;
+		cursor: pointer;
+	}
+	.tabshit{
+		background: #f5f7fa;
+		border-bottom: #78ba27 solid 4px
+	}
+
+	sapn{
+		color: #8c939d;
+		font-size: 12px;
+		overflow: hidden;
+		text-overflow:ellipsis;
+		white-space: nowrap;
+	}
+</style>
+
+<body>
+
+<div id="app">
+
+	<el-card>
+
+		<div slot="header" class="clearfix">
+			<img th:src="@{img/logo.png}"  width="100" />
+			<img th:src="@{img/baidu.png}"  width="150"/>
+		</div>
+        <div class="tabs">
+			<div v-for="(item,index) in tabList" @click="tabsck(item)" :class="{tabshit:item.type,tabsn:true}">
+				{{item.name}}
+			</div>
+		</div>
+		<!-- 查询表单 -->
+		<el-form :inline="true" :model="searchForm" label-width="90px" size="small">
+
+			<el-form-item>
+				<el-input placeholder="请输入查询关键字" @keyup.enter.native="list(searchForm)" v-model="searchForm.keyword" clearable>
+					<el-select v-model="select" slot="prepend" placeholder="请选择" style="width: 124px">
+						<el-option v-for="item in selectlist" :label="item" :value="item"></el-option>
+					</el-select>
+					<el-button slot="append" icon="el-icon-search" @click="list(searchForm)"></el-button>
+				</el-input>
+				<el-input v-show="false" placeholder="请输入查询关键字" @keyup.enter.native="list(searchForm)" v-model="searchForm.keyword" clearable></el-input>
+			</el-form-item>
+
+<!--			<el-form-item>-->
+<!--				<el-button icon="el-icon-search" plain @click="list(searchForm)">搜索</el-button>-->
+<!--			</el-form-item>-->
+
+			<el-form-item>
+<!--				<el-button type="info" plain icon="el-icon-plus" @click="preAdd" :loading="genLoading">添加</el-button>-->
+			</el-form-item>
+
+		</el-form>
+
+
+		<ol style="list-style: none">
+			<li v-for="site in tableData">
+				<div>
+					<h3><a :href="site.url" target="_blank" v-html="site.title"></a></h3>
+					<p v-html="site.content"></p>
+					<p v-html="site.type"></p>
+					<!--					<a :href="site.url" target="_blank">网址:{{site.url}}</a>-->
+					<p v-html="site.date"></p>
+					<a :href="site.url" target="_blank" style="text-decoration:none"><sapn>{{site.url}}	数据来源:{{site.source}}</sapn></a>
+				</div>
+		</ol>
+
+		<!-- 数据表格 -->
+		<el-table v-loading="tableLoading" :data="tableData" @selection-change="handleSelectionChange" border>
+			<!--<el-table-column type="selection" align="center" width="55"></el-table-column>-->
+<!--			<el-table-column type="index" align="center" min-width="60"></el-table-column> 索引-->
+
+
+<!--			<el-table-column prop="title" label="标题" align="center" min-width="100" show-overflow-tooltip></el-table-column>-->
+<!--			<el-table-column prop="type" label="类型" align="center" min-width="100" show-overflow-tooltip></el-table-column>-->
+<!--			<el-table-column prop="content" label="内容" align="center" min-width="80" show-overflow-tooltip></el-table-column>-->
+<!--			<el-table-column prop="url" label="url" align="center" min-width="80" show-overflow-tooltip></el-table-column>-->
+<!--			<el-table-column prop="date" label="日期" align="center" min-width="80" show-overflow-tooltip></el-table-column>-->
+
+			<!--<el-table-column prop="createTime" label="创建时间" align="center" min-width="100" show-overflow-tooltip>
+				<template slot-scope="scope">
+					{{ moment(scope.row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
+				</template>
+			</el-table-column>-->
+<!--			<el-table-column label="操作" align="center" fixed="right" min-width="60">-->
+<!--				<template slot-scope="scope">-->
+<!--&lt;!&ndash;					<el-button size="mini" icon="el-icon-edit" type="primary" plain @click="preById(scope.row)" :loading="genLoading">修改</el-button>&ndash;&gt;-->
+<!--&lt;!&ndash;					<el-button size="mini" icon="el-icon-delete" type="danger" plain @click="delById(scope.row)" :loading="genLoading">删除</el-button>&ndash;&gt;-->
+<!--&lt;!&ndash;					<el-button size="mini" icon="el-icon-edit" type="primary" :loading="genLoading">查看</el-button>&ndash;&gt;-->
+<!--				</template>-->
+<!--			</el-table-column>-->
+		</el-table>
+		<div align="right" style="margin-top: 20px;">
+			<el-pagination
+				:current-page="searchForm.page"
+				:page-sizes="[1, 8, 16, 32, 48]"
+				:page-size="searchForm.rows"
+				:total="totalCount"
+				layout="total, sizes, prev, pager, next, jumper"
+				@size-change="handleSizeChange"
+				@current-change="handleCurrentChange"
+			/>
+		</div>
+	</el-card>
+
+	<el-dialog :title="title" :visible.sync="dialogVisible" width="40%">
+		<el-form :model="bookDto" label-width="90px" style="width: 520px;">
+			<el-form-item label="ID">
+				<el-input v-model="bookDto.id" disabled="true" autocomplete="off" placeholder="ID自动生成"></el-input>
+			</el-form-item>
+			<el-form-item label="名称">
+				<el-input v-model="bookDto.name" autocomplete="off"></el-input>
+			</el-form-item>
+			<el-form-item label="描述">
+				<el-input v-model="bookDto.desc" autocomplete="off"></el-input>
+			</el-form-item>
+		</el-form>
+		<div slot="footer" class="dialog-footer">
+			<el-button :loading="genLoading" @click="dialogVisible = false">取 消</el-button>
+			<el-button type="primary" :loading="genLoading" @click="deal">确 定</el-button>
+		</div>
+	</el-dialog>
+
+</div>
+
+<script type="text/javascript" th:inline="javascript">
+    /*<![CDATA[*/
+    var myApp = new Vue({
+        el: '#app',
+        data: {
+            // 表格加载条控制
+            tableLoading: false,
+            // 按钮加载条控制
+            genLoading: false,
+            // Table数据
+            tableData: [],
+            // Table数据总条数
+            totalCount: 0,
+            // Table选择的数据
+            multipleSelection: [],
+            // 查询条件
+            searchForm: {
+                // 当前页
+                page: 1,
+                // 每页条数
+                rows: 8,
+                // 查询关键字
+                keyword: ''
+            },
+            // 表详细弹出框标题
+            title: '添加',
+            // 表详细弹出框是否显示
+            dialogVisible: false,
+            // 操作对象
+            bookDto: {
+                // ID
+                id: 1,
+                // 名称
+                name: '',
+                // 描述
+                desc: ''
+            },
+			tabList:[
+				{
+					name:"内网",
+					type:true
+				},
+				{
+					name:"外网",
+					type:false
+				}
+			],
+			selectlist:["政策","重燃","核电设备","核燃料","水电","火电","风电","光伏","储能","氢能","碳指标"],
+			select:""
+        },
+        // 启动时就执行
+        mounted: function() {
+            // ES信息查询
+            // this.queryES();
+            // 列表查询(页面加载查询...)
+            // this.list(this.searchForm);
+        },
+        methods: {
+			tabsck:function(item){
+				this.tabList.forEach((res)=>res.type=false)
+               item.type=!item.type
+			},
+            // 查询ES信息
+            queryES: function() {
+                axios.get('/high/es').then(res => {
+                    console.log(res);
+				}).catch(err => {
+					console.log(err);
+					this.$message.error('查询失败');
+				});
+            },
+            // 每页条数改变
+            handleSizeChange: function(rows) {
+                this.searchForm.rows = rows;
+                // console.log(this.searchForm.rows);
+                // 刷新列表
+                this.list(this.searchForm);
+            },
+            // 当前页数改变
+            handleCurrentChange: function(page) {
+                this.searchForm.page = page;
+                // 刷新列表
+                this.list(this.searchForm);
+            },
+            // 选择数据改变触发事件
+            handleSelectionChange(val) {
+                this.multipleSelection = val;
+            },
+            // 列表查询
+            list: function(searchForm) {
+				console.log(this.select)
+                // 加载显示
+                this.tableLoading = true;
+                axios.get('/high/book', {
+                    params: {
+                        'page': this.searchForm.page,
+                        'rows': this.searchForm.rows,
+						// 'keyword': this.searchForm.keyword
+                        'keyword': this.searchForm.keyword+this.select
+                    }
+                }).then(res => {
+                    // console.log(res);
+                    var data = res.data.data;
+                    this.tableData = data.data;
+                    this.totalCount = data.count;
+                }).catch(err => {
+					console.log(err);
+					this.$message.error('查询失败');
+                }).then(() => {
+                    this.tableLoading = false;
+            	});
+            },
+            // 添加
+            preAdd: function() {
+                this.genLoading = true;
+                // this.$nextTick Dom渲染完执行
+				this.$nextTick(() => {
+				    this.title = "添加";
+				    this.bookDto = {};
+				    this.dialogVisible = true;
+				    this.genLoading = false;
+				});
+            },
+            // 预修改
+            preById: function(row) {
+                this.genLoading = true;
+                this.title = "修改";
+                this.dialogVisible = true;
+                axios.get('/high/book/' + row.id).then(res => {
+                    // console.log(res);
+					this.bookDto = res.data.data;
+                }).catch(err => {
+                    console.log(err);
+                    this.$message.error('查询失败');
+                }).then(() => {
+                    this.genLoading = false;
+                });
+            },
+            // 添加或者修改
+            deal: function() {
+                this.genLoading = true;
+                if (this.bookDto.id) {
+                    // ID存在修改
+                    axios.put('/high/book', this.bookDto).then(res => {
+                        if (res.data.code == 200) {
+                            this.$message({
+								message: res.data.msg,
+								type: 'success'
+                            });
+                            this.dialogVisible = false;
+                            // 列表查询必须慢点,ES没有事务性,查询太快,数据还没更新
+                            this.tableLoading = true;
+                            setTimeout(() => {this.list(this.searchForm);}, 1000);
+                        } else {
+                            this.$message.error('修改失败');
+                        }
+                    }).catch(err => {
+                        console.log(err);
+                        this.$message.error('修改失败');
+                    }).then(() => {
+                        this.genLoading = false;
+                    });
+                } else {
+                    // ID不存在添加
+                    axios.post('/high/book', this.bookDto).then(res => {
+                        if (res.data.code == 200) {
+                            this.$message({
+								message: res.data.msg,
+								type: 'success'
+                            });
+                            this.dialogVisible = false;
+                            // 列表查询必须慢点,ES没有事务性,查询太快,数据还没更新
+                            this.tableLoading = true;
+                            setTimeout(() => {this.list(this.searchForm);}, 1000);
+                        } else {
+                            this.$message.error('添加失败');
+                        }
+                    }).catch(err => {
+                        console.log(err);
+                        this.$message.error('添加失败');
+                    }).then(() => {
+                        this.genLoading = false;
+                    });
+                }
+			},
+            // 删除
+            delById: function (row) {
+                this.genLoading = true;
+                this.$confirm('是否确定删除', '提示', {
+                    confirmButtonText: '确定',
+                    cancelButtonText: '取消',
+                    type: 'warning'
+                }).then(() => {
+                    axios.delete('/high/book/' + row.id).then(res => {
+                        if (res.data.code == 200) {
+                            this.$message({
+								message: res.data.msg,
+								type: 'success'
+                            });
+                            // 列表查询必须慢点,ES没有事务性,查询太快,数据还没更新
+                            this.tableLoading = true;
+                            setTimeout(() => {this.list(this.searchForm);}, 1000);
+                        } else {
+                            this.$message.error('删除失败');
+                        }
+                    }).catch(err => {
+                        console.log(err);
+                        this.$message.error('删除失败');
+                    }).then(() => {
+                        this.genLoading = false;
+                    });
+                }).catch(() => {
+                    this.genLoading = false;
+                });
+            }
+        }
+    });
+    /*]]>*/
+</script>
+
+</body>
+
+</html>

+ 16 - 0
src/test/java/com/example/ApplicationTests.java

@@ -0,0 +1,16 @@
+//package com.example;
+//
+//import org.junit.Test;
+//import org.junit.runner.RunWith;
+//import org.springframework.boot.test.context.SpringBootTest;
+//import org.springframework.test.context.junit4.SpringRunner;
+//
+//@RunWith(SpringRunner.class)
+//@SpringBootTest
+//public class ApplicationTests {
+//
+//    @Test
+//    public void contextLoads() {
+//    }
+//
+//}

Some files were not shown because too many files changed in this diff