Browse Source

1、京东搜索demo,前后端分离。

guanzi 3 years ago
parent
commit
2241edf1b4
32 changed files with 1679 additions and 391 deletions
  1. 6 5
      ghj-es-api/.mvn/wrapper/MavenWrapperDownloader.java
  2. 90 185
      ghj-es-api/pom.xml
  3. 4 4
      ghj-es-api/src/main/java/com/pavis/ghjesapi/GhjEsApiApplication.java
  4. 2 2
      ghj-es-api/src/main/java/com/pavis/ghjesapi/config/ElasticSearchConfig.java
  5. 1 1
      ghj-es-api/src/main/java/com/pavis/ghjesapi/service/EsService.java
  6. 14 14
      ghj-es-api/src/main/java/com/pavis/ghjesapi/service/impl/EsDemoServiceImpl.java
  7. 1 0
      ghj-es-api/src/main/resources/application.properties
  8. 180 180
      ghj-es-api/src/test/java/com/pavis/ghjesapi/GhjEsApiApplicationTests.java
  9. 13 0
      ghj-es-api/src/test/java/com/test/jdes/JdEsApplicationTests.java
  10. 33 0
      jd-es/.gitignore
  11. 118 0
      jd-es/.mvn/wrapper/MavenWrapperDownloader.java
  12. BIN
      jd-es/.mvn/wrapper/maven-wrapper.jar
  13. 2 0
      jd-es/.mvn/wrapper/maven-wrapper.properties
  14. 310 0
      jd-es/mvnw
  15. 182 0
      jd-es/mvnw.cmd
  16. 182 0
      jd-es/pom.xml
  17. 14 0
      jd-es/src/main/java/com/pavis/jdes/JdEsApplication.java
  18. 31 0
      jd-es/src/main/java/com/pavis/jdes/common/CorsFilterConfig.java
  19. 46 0
      jd-es/src/main/java/com/pavis/jdes/controller/IndexController.java
  20. 24 0
      jd-es/src/main/java/com/pavis/jdes/pojo/JdContent.java
  21. 29 0
      jd-es/src/main/java/com/pavis/jdes/service/JdContentService.java
  22. 118 0
      jd-es/src/main/java/com/pavis/jdes/service/impl/JdContentServiceImpl.java
  23. 70 0
      jd-es/src/main/java/com/pavis/jdes/utils/HtmlParseUtil.java
  24. 6 0
      jd-es/src/main/resources/application.yml
  25. 0 0
      jd-es/src/main/resources/static/css/style.css
  26. BIN
      jd-es/src/main/resources/static/images/jdlogo.png
  27. BIN
      jd-es/src/main/resources/static/images/wmyy.jpg
  28. 1 0
      jd-es/src/main/resources/static/js/axios.min.js
  29. 1 0
      jd-es/src/main/resources/static/js/jquery.min.js
  30. 5 0
      jd-es/src/main/resources/static/js/vue.min.js
  31. 183 0
      jd-es/src/main/resources/templates/index.html
  32. 13 0
      jd-es/src/test/java/com/pavis/jdes/JdEsApplicationTests.java

+ 6 - 5
ghj-es-api/.mvn/wrapper/MavenWrapperDownloader.java

@@ -13,6 +13,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 import java.net.*;
 import java.io.*;
 import java.nio.channels.*;
@@ -25,7 +26,7 @@ public class MavenWrapperDownloader {
      * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
      */
     private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
-        + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
+            + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
 
     /**
      * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
@@ -54,7 +55,7 @@ public class MavenWrapperDownloader {
         // wrapperUrl parameter.
         File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
         String url = DEFAULT_DOWNLOAD_URL;
-        if(mavenWrapperPropertyFile.exists()) {
+        if (mavenWrapperPropertyFile.exists()) {
             FileInputStream mavenWrapperPropertyFileInputStream = null;
             try {
                 mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
@@ -65,7 +66,7 @@ public class MavenWrapperDownloader {
                 System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
             } finally {
                 try {
-                    if(mavenWrapperPropertyFileInputStream != null) {
+                    if (mavenWrapperPropertyFileInputStream != null) {
                         mavenWrapperPropertyFileInputStream.close();
                     }
                 } catch (IOException e) {
@@ -76,8 +77,8 @@ public class MavenWrapperDownloader {
         System.out.println("- Downloading from: " + url);
 
         File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
-        if(!outputFile.getParentFile().exists()) {
-            if(!outputFile.getParentFile().mkdirs()) {
+        if (!outputFile.getParentFile().exists()) {
+            if (!outputFile.getParentFile().mkdirs()) {
                 System.out.println(
                         "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
             }

+ 90 - 185
ghj-es-api/pom.xml

@@ -1,189 +1,94 @@
 <?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 https://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.5.5</version>
-		<relativePath/> <!-- lookup parent from repository -->
-	</parent>
-	<groupId>com.pavis</groupId>
-	<artifactId>ghj-es-api</artifactId>
-	<version>0.0.1-SNAPSHOT</version>
-	<name>ghj-es-api</name>
-	<description>Demo project for Spring Boot es</description>
-	<properties>
-		<java.version>1.8</java.version>
-		<spring-cloud.version>2020.0.4</spring-cloud.version>
-		<elasticsearch.version>7.6.1</elasticsearch.version>
-	</properties>
-	<dependencies>
-		<dependency>
-			<groupId>org.springframework.boot</groupId>
-			<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
-		</dependency>
-		<dependency>
-			<groupId>org.springframework.boot</groupId>
-			<artifactId>spring-boot-starter-data-jdbc</artifactId>
-		</dependency>
-		<dependency>
-			<groupId>org.springframework.boot</groupId>
-			<artifactId>spring-boot-starter-web</artifactId>
-		</dependency>
-
-<!--		<dependency>-->
-<!--			<groupId>org.springframework.cloud</groupId>-->
-<!--			<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>-->
-<!--		</dependency>-->
-		<dependency>
-			<groupId>org.springframework.cloud</groupId>
-			<artifactId>spring-cloud-starter-openfeign</artifactId>
-		</dependency>
-
-		<dependency>
-			<groupId>org.springframework.boot</groupId>
-			<artifactId>spring-boot-devtools</artifactId>
-			<scope>runtime</scope>
-			<optional>true</optional>
-		</dependency>
-		<dependency>
-			<groupId>mysql</groupId>
-			<artifactId>mysql-connector-java</artifactId>
-			<scope>runtime</scope>
-		</dependency>
-		<dependency>
-			<groupId>com.baomidou</groupId>
-			<artifactId>mybatis-plus-boot-starter</artifactId>
-			<version>3.2.0</version>
-		</dependency>
-		<dependency>
-			<groupId>org.springframework.boot</groupId>
-			<artifactId>spring-boot-configuration-processor</artifactId>
-			<optional>true</optional>
-		</dependency>
-		<dependency>
-			<groupId>org.projectlombok</groupId>
-			<artifactId>lombok</artifactId>
-			<optional>true</optional>
-		</dependency>
-		<dependency>
-			<groupId>org.springframework.boot</groupId>
-			<artifactId>spring-boot-starter-test</artifactId>
-			<scope>test</scope>
-		</dependency>
-
-
-		<dependency>
-			<groupId>io.springfox</groupId>
-			<artifactId>springfox-swagger2</artifactId>
-			<version>2.9.2</version>
-		</dependency>
-		<dependency>
-			<groupId>io.springfox</groupId>
-			<artifactId>springfox-swagger-ui</artifactId>
-			<version>2.9.2</version>
-		</dependency>
-
-		<!-- https://mvnrepository.com/artifact/com.github.xiaoymin/knife4j-spring-ui -->
-		<dependency>
-			<groupId>com.github.xiaoymin</groupId>
-			<artifactId>knife4j-spring-ui</artifactId>
-			<version>2.0.2</version>
-		</dependency>
-
-		<dependency>
-			<groupId>com.github.xiaoymin</groupId>
-			<artifactId>knife4j-spring-boot-starter</artifactId>
-			<!--在引用时请在maven中央仓库搜索最新版本号-->
-			<version>2.0.2</version>
-		</dependency>
-
-		<dependency>
-			<groupId>com.google.guava</groupId>
-			<artifactId>guava</artifactId>
-			<version>27.0.1-jre</version>
-		</dependency>
-
-		<dependency>
-			<groupId>com.alibaba</groupId>
-			<artifactId>fastjson</artifactId>
-			<version>1.2.73</version>
-		</dependency>
-
-		<!--        <dependency>-->
-		<!--            <groupId>joda-time</groupId>-->
-		<!--            <artifactId>joda-time</artifactId>-->
-		<!--        </dependency>-->
-
-		<dependency>
-			<groupId>org.apache.commons</groupId>
-			<artifactId>commons-lang3</artifactId>
-		</dependency>
-
-		<dependency>
-			<groupId>commons-collections</groupId>
-			<artifactId>commons-collections</artifactId>
-			<version>3.2.2</version>
-		</dependency>
-
-		<dependency>
-			<groupId>commons-codec</groupId>
-			<artifactId>commons-codec</artifactId>
-			<version>1.14</version>
-		</dependency>
-
-		<dependency>
-			<groupId>org.apache.commons</groupId>
-			<artifactId>commons-text</artifactId>
-			<version>1.8</version>
-		</dependency>
-
-		<dependency>
-			<groupId>commons-beanutils</groupId>
-			<artifactId>commons-beanutils</artifactId>
-			<version>1.9.4</version>
-		</dependency>
-
-		<dependency>
-			<groupId>org.aspectj</groupId>
-			<artifactId>aspectjweaver</artifactId>
-			<version>1.8.8</version>
-		</dependency>
-		<dependency>
-			<groupId>com.alibaba</groupId>
-			<artifactId>druid-spring-boot-starter</artifactId>
-			<version>1.1.9</version>
-		</dependency>
-	</dependencies>
-
-	<dependencyManagement>
-		<dependencies>
-			<dependency>
-				<groupId>org.springframework.cloud</groupId>
-				<artifactId>spring-cloud-dependencies</artifactId>
-				<version>${spring-cloud.version}</version>
-				<type>pom</type>
-				<scope>import</scope>
-			</dependency>
-		</dependencies>
-	</dependencyManagement>
-
-	<build>
-		<plugins>
-			<plugin>
-				<groupId>org.springframework.boot</groupId>
-				<artifactId>spring-boot-maven-plugin</artifactId>
-				<configuration>
-					<excludes>
-						<exclude>
-							<groupId>org.projectlombok</groupId>
-							<artifactId>lombok</artifactId>
-						</exclude>
-					</excludes>
-				</configuration>
-			</plugin>
-		</plugins>
-	</build>
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://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.5.5</version>
+        <relativePath/> <!-- lookup parent from repository -->
+    </parent>
+    <groupId>com.test</groupId>
+    <artifactId>jd-es</artifactId>
+    <version>0.0.1</version>
+    <name>jd-es</name>
+    <description>Demo project for Spring Boot</description>
+    <properties>
+        <java.version>1.8</java.version>
+        <spring-cloud.version>2020.0.4</spring-cloud.version>
+    </properties>
+    <dependencies>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-data-jdbc</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-web</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.cloud</groupId>
+            <artifactId>spring-cloud-starter-openfeign</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-devtools</artifactId>
+            <scope>runtime</scope>
+            <optional>true</optional>
+        </dependency>
+        <dependency>
+            <groupId>mysql</groupId>
+            <artifactId>mysql-connector-java</artifactId>
+            <scope>runtime</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-configuration-processor</artifactId>
+            <optional>true</optional>
+        </dependency>
+        <dependency>
+            <groupId>org.projectlombok</groupId>
+            <artifactId>lombok</artifactId>
+            <optional>true</optional>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-test</artifactId>
+            <scope>test</scope>
+        </dependency>
+    </dependencies>
+    <dependencyManagement>
+        <dependencies>
+            <dependency>
+                <groupId>org.springframework.cloud</groupId>
+                <artifactId>spring-cloud-dependencies</artifactId>
+                <version>${spring-cloud.version}</version>
+                <type>pom</type>
+                <scope>import</scope>
+            </dependency>
+        </dependencies>
+    </dependencyManagement>
+
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.springframework.boot</groupId>
+                <artifactId>spring-boot-maven-plugin</artifactId>
+                <configuration>
+                    <excludes>
+                        <exclude>
+                            <groupId>org.projectlombok</groupId>
+                            <artifactId>lombok</artifactId>
+                        </exclude>
+                    </excludes>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
 
 </project>

+ 4 - 4
ghj-es-api/src/main/java/com/pavis/ghjesapi/GhjEsApiApplication.java

@@ -6,11 +6,11 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
 import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
 
 @MapperScan("com.pavis.ghjesapi.dao")
-@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
+@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
 public class GhjEsApiApplication {
 
-	public static void main(String[] args) {
-		SpringApplication.run(GhjEsApiApplication.class, args);
-	}
+    public static void main(String[] args) {
+        SpringApplication.run(GhjEsApiApplication.class, args);
+    }
 
 }

+ 2 - 2
ghj-es-api/src/main/java/com/pavis/ghjesapi/config/ElasticSearchConfig.java

@@ -17,10 +17,10 @@ public class ElasticSearchConfig {
 
     // 注册 rest高级客户端
     @Bean
-    public RestHighLevelClient restHighLevelClient(){
+    public RestHighLevelClient restHighLevelClient() {
         RestHighLevelClient client = new RestHighLevelClient(
                 RestClient.builder(
-                        new HttpHost("127.0.0.1",9200,"http")
+                        new HttpHost("127.0.0.1", 9200, "http")
                 )
         );
         return client;

+ 1 - 1
ghj-es-api/src/main/java/com/pavis/ghjesapi/service/EsService.java

@@ -6,5 +6,5 @@ import java.util.Map;
 
 public interface EsService {
 
-    Map<String,Object> importMysqlDataToEs() throws IOException;
+    Map<String, Object> importMysqlDataToEs() throws IOException;
 }

+ 14 - 14
ghj-es-api/src/main/java/com/pavis/ghjesapi/service/impl/EsDemoServiceImpl.java

@@ -92,17 +92,17 @@ public class EsDemoServiceImpl implements EsService {
         // SearchResponse searchUpResp = searchByParam("title", demos.get(0).getTitle());
         SearchResponse searchUpResp = searchByParam("title", "铁");
         for (SearchHit hit : searchUpResp.getHits()) {
-            Map<String,Object> map = hit.getSourceAsMap();
+            Map<String, Object> map = hit.getSourceAsMap();
             // System.out.println(JSON.toJSONString(map));
             // EsDemo esDemo = JSON.parseObject(JSON.toJSONString(map),EsDemo.class);
-            Map<String,Object> selMap = new HashMap<>();
-            selMap.put("title",map.get("title"));
+            Map<String, Object> selMap = new HashMap<>();
+            selMap.put("title", map.get("title"));
             System.out.println(map.get("content"));
             System.err.println(map.get("title"));
             List<EsObj> esObjLists = esObjMapper.selectByMap(selMap);
-            if (esObjLists.size() > 0){
+            if (esObjLists.size() > 0) {
                 System.out.println("2:" + esObjLists.get(0).getContent());
-                map.put("content","eeeeeeeeee" + esObjLists.get(0).getContent());
+                map.put("content", "eeeeeeeeee" + esObjLists.get(0).getContent());
                 System.out.println("2:" + map.get("content"));
             }
 
@@ -112,7 +112,7 @@ public class EsDemoServiceImpl implements EsService {
             // 批量更新
             bulkRequest.add(
                     new UpdateRequest()
-                    .index("es_test_demo")
+                            .index("es_test_demo")
                             .id(hit.getId())
                             .doc(XContentType.JSON, "content", map.get("content").toString()).upsert()
             );
@@ -132,17 +132,17 @@ public class EsDemoServiceImpl implements EsService {
         System.err.println(bulkResp.hasFailures()); // 是否失败,返回false 代表成功。
 
         // 返回信息。
-        Map<String,Object> map = new HashMap<>();
-        if (false == bulkResp.hasFailures()){
-            map.put("mes","SUCC");
-        }else {
-            map.put("mes","fail");
+        Map<String, Object> map = new HashMap<>();
+        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);
+    public SearchResponse searchByParam(String key, String val) throws IOException {
+        log.info("key:{},val:{}", key, val);
         SearchRequest searchRequest = new SearchRequest("es_test_demo");
         // SearchRequest searchRequest = new SearchRequest("es_dome");
         // 构建搜索条件
@@ -150,7 +150,7 @@ public class EsDemoServiceImpl implements EsService {
 
         // 查询条件,用QueryBuilders实现
         // QueryBuilders.termQuery 精确查找
-        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery(key,val);
+        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery(key, val);
 
         // QueryBuilders.matchAllQuery() 匹配所有。
         // MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();

+ 1 - 0
ghj-es-api/src/main/resources/application.properties

@@ -0,0 +1 @@
+

+ 180 - 180
ghj-es-api/src/test/java/com/pavis/ghjesapi/GhjEsApiApplicationTests.java

@@ -44,185 +44,185 @@ import java.util.concurrent.TimeUnit;
 @SpringBootTest
 class GhjEsApiApplicationTests {
 
-	@Autowired
-	@Qualifier("restHighLevelClient")
-	private RestHighLevelClient client;
-
-	// 创建索引
-	@Test
-	void createIndex() throws IOException {
-		// 1.创建索引
-		CreateIndexRequest request = new CreateIndexRequest(Constant.ES_INDEX);
-		// 2.执行客户端请求,获取响应。
-		CreateIndexResponse response = client.indices()
-				.create(request, RequestOptions.DEFAULT);
-		log.info("create index response:{}",response);
-	}
-
-	// 获取索引,判断是否存在。
-	@Test
-	void testEixstIndex() throws IOException {
-		GetIndexRequest request = new GetIndexRequest(Constant.ES_INDEX);
-		Boolean exists = client.indices().exists(request,RequestOptions.DEFAULT);
-		log.info("index exists:{}",exists);
-	}
-
-	// 删除索引
-	@Test
-	void delIndex() throws IOException {
-		DeleteIndexRequest request = new DeleteIndexRequest("table_tennis2");
-		// 删除
-		AcknowledgedResponse response = client.indices().delete(request,RequestOptions.DEFAULT);
-		log.info("del reponse:{}", JSON.toJSONString(response));
-		log.info("delete status:{}",response.isAcknowledged());
-	}
-
-	// 添加文档
-	@Test
-	void testAddDoc() throws IOException {
-		// 创建对象
-		Player player = new Player("wmy",21);
-		// 创建请求
-		IndexRequest request = new IndexRequest(Constant.ES_INDEX);
-		// 规则 put /table_tennis/_doc/1
-		request.id("1");
-		request.timeout(TimeValue.timeValueSeconds(1));
-		request.timeout("1s");
-
-		// 将我们得数据放入请求,json
-		request.source(JSON.toJSONString(player), XContentType.JSON);
-
-		// 客户端发送请求
-		IndexResponse response = client.index(request, RequestOptions.DEFAULT);
-		System.err.println(response.toString());
-		// 对应我们命令返回得状态
-		System.err.println(response.status());
-	}
-
-	// 获取文档前,先判断是否存在
-	@Test
-	void testExistDoc() throws IOException {
-		GetRequest getReq = new GetRequest(Constant.ES_INDEX, "1");
-		// 不获取返回得_source得上下文了。
-		getReq.fetchSourceContext(new FetchSourceContext(false));
-		getReq.storedFields("_none_");
-
-		boolean exists = client.exists(getReq, RequestOptions.DEFAULT);
-		System.err.println(exists);
-	}
-
-	// 获取文档
-	@Test
-	void testGetDoc() throws IOException {
-		GetRequest getReq = new GetRequest(Constant.ES_INDEX, "1");
-		GetResponse getResp = client.get(getReq, RequestOptions.DEFAULT);
-		// 打印文档得内容
-		System.err.println(getResp.getSourceAsString());
-		// 返回得内容和命令是一样得。
-		System.out.println(getResp);
-	}
-
-	// 更新文档信息
-	@Test
-	void testUpdateDoc() throws IOException {
-		UpdateRequest upReq = new UpdateRequest(Constant.ES_INDEX, "1");
-		upReq.timeout("1s");
-
-		Player player = new Player("wmyu",21);
-		upReq.doc(JSON.toJSONString(player),XContentType.JSON);
-
-		UpdateResponse upResp = client.update(upReq, RequestOptions.DEFAULT);
-		System.out.println(upResp);
-		System.out.println(upResp.status());
-	}
-
-	// 删除文档信息
-	@Test
-	void testDelDoc() throws IOException {
-		DeleteRequest delReq = new DeleteRequest(Constant.ES_INDEX, "1");
-		delReq.timeout("1s");
-		DeleteResponse delResp = client.delete(delReq, RequestOptions.DEFAULT);
-		System.out.println(delResp);
-		System.out.println(delResp.status());
-	}
-
-	// 批量添加
-	@Test
-	void testBulkReq() throws IOException {
-		BulkRequest bulkRequest = new BulkRequest();
-		bulkRequest.timeout("10s");
-
-		List<Player> players = new ArrayList<>();
-		players.add(new Player("wmy",21));
-		players.add(new Player("sys",20));
-		players.add(new Player("cm",23));
-		players.add(new Player("lsw",24));
-
-		// 批处理请求
-		for (int i = 0; i < players.size(); i++) {
-			bulkRequest.add(
-					new IndexRequest("table_tennis")
-							.id(""+(i+1))
-							.source(JSON.toJSONString(players.get(i)),XContentType.JSON)
-			);
-		}
-		BulkResponse bulkResp = client.bulk(bulkRequest, RequestOptions.DEFAULT);
-		System.err.println(bulkResp.hasFailures()); // 是否失败,返回false 代表成功。
-	}
-
-	// 查询
-	// SearchRequest 搜索请求
-	// SearchSourceBuilder 条件构造
-	// HighlightBuilder 构建高亮
-	// TermQueryBuilder 精确查询
-	// MatchAllQueryBuilder 匹配所有
-	// xxx QueryBuilder 对应我们得命令。
-	@Test
-	void testSearch() throws IOException {
-		SearchRequest searchRequest = new SearchRequest(Constant.ES_INDEX);
-		// 构建搜索条件
-		SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
-
-		// 查询条件,用QueryBuilders实现
-		// QueryBuilders.termQuery 精确查找
-		TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name","wmy");
-
-		// QueryBuilders.matchAllQuery() 匹配所有。
-		// MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
-
-		searchSourceBuilder.query(termQueryBuilder);
-		searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
-
-		searchRequest.source(searchSourceBuilder);
-
-		SearchResponse searchResp = client.search(searchRequest, RequestOptions.DEFAULT);
-		System.out.println(JSON.toJSONString(searchResp.getHits()));
-		System.out.println("=========================================");
-		for (SearchHit hit : searchResp.getHits()) {
-			System.out.println(hit.getSourceAsMap());
-		}
-
-
-	}
-
-	// 删除文档信息
-	@Test
-	void testDelDocByName() throws IOException {
-		DeleteRequest delReq = new DeleteRequest("table_tennis", "1");
-		delReq.timeout("1s");
-
-		SearchRequest searchRequest = new SearchRequest(Constant.ES_INDEX);
-		SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
-		TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name","wmy");
-		searchSourceBuilder.query(termQueryBuilder);
-		searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
-
-		searchRequest.source(searchSourceBuilder);
-
-		SearchResponse searchResp = client.search(searchRequest, RequestOptions.DEFAULT);
-		DeleteResponse delResp = client.delete(delReq, RequestOptions.DEFAULT);
-		System.out.println(delResp);
-		System.out.println(delResp.status());
-	}
+    @Autowired
+    @Qualifier("restHighLevelClient")
+    private RestHighLevelClient client;
+
+    // 创建索引
+    @Test
+    void createIndex() throws IOException {
+        // 1.创建索引
+        CreateIndexRequest request = new CreateIndexRequest(Constant.ES_INDEX);
+        // 2.执行客户端请求,获取响应。
+        CreateIndexResponse response = client.indices()
+                .create(request, RequestOptions.DEFAULT);
+        log.info("create index response:{}", response);
+    }
+
+    // 获取索引,判断是否存在。
+    @Test
+    void testEixstIndex() throws IOException {
+        GetIndexRequest request = new GetIndexRequest(Constant.ES_INDEX);
+        Boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
+        log.info("index exists:{}", exists);
+    }
+
+    // 删除索引
+    @Test
+    void delIndex() throws IOException {
+        DeleteIndexRequest request = new DeleteIndexRequest("table_tennis2");
+        // 删除
+        AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
+        log.info("del reponse:{}", JSON.toJSONString(response));
+        log.info("delete status:{}", response.isAcknowledged());
+    }
+
+    // 添加文档
+    @Test
+    void testAddDoc() throws IOException {
+        // 创建对象
+        Player player = new Player("wmy", 21);
+        // 创建请求
+        IndexRequest request = new IndexRequest(Constant.ES_INDEX);
+        // 规则 put /table_tennis/_doc/1
+        request.id("1");
+        request.timeout(TimeValue.timeValueSeconds(1));
+        request.timeout("1s");
+
+        // 将我们得数据放入请求,json
+        request.source(JSON.toJSONString(player), XContentType.JSON);
+
+        // 客户端发送请求
+        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
+        System.err.println(response.toString());
+        // 对应我们命令返回得状态
+        System.err.println(response.status());
+    }
+
+    // 获取文档前,先判断是否存在
+    @Test
+    void testExistDoc() throws IOException {
+        GetRequest getReq = new GetRequest(Constant.ES_INDEX, "1");
+        // 不获取返回得_source得上下文了。
+        getReq.fetchSourceContext(new FetchSourceContext(false));
+        getReq.storedFields("_none_");
+
+        boolean exists = client.exists(getReq, RequestOptions.DEFAULT);
+        System.err.println(exists);
+    }
+
+    // 获取文档
+    @Test
+    void testGetDoc() throws IOException {
+        GetRequest getReq = new GetRequest(Constant.ES_INDEX, "1");
+        GetResponse getResp = client.get(getReq, RequestOptions.DEFAULT);
+        // 打印文档得内容
+        System.err.println(getResp.getSourceAsString());
+        // 返回得内容和命令是一样得。
+        System.out.println(getResp);
+    }
+
+    // 更新文档信息
+    @Test
+    void testUpdateDoc() throws IOException {
+        UpdateRequest upReq = new UpdateRequest(Constant.ES_INDEX, "1");
+        upReq.timeout("1s");
+
+        Player player = new Player("wmyu", 21);
+        upReq.doc(JSON.toJSONString(player), XContentType.JSON);
+
+        UpdateResponse upResp = client.update(upReq, RequestOptions.DEFAULT);
+        System.out.println(upResp);
+        System.out.println(upResp.status());
+    }
+
+    // 删除文档信息
+    @Test
+    void testDelDoc() throws IOException {
+        DeleteRequest delReq = new DeleteRequest(Constant.ES_INDEX, "1");
+        delReq.timeout("1s");
+        DeleteResponse delResp = client.delete(delReq, RequestOptions.DEFAULT);
+        System.out.println(delResp);
+        System.out.println(delResp.status());
+    }
+
+    // 批量添加
+    @Test
+    void testBulkReq() throws IOException {
+        BulkRequest bulkRequest = new BulkRequest();
+        bulkRequest.timeout("10s");
+
+        List<Player> players = new ArrayList<>();
+        players.add(new Player("wmy", 21));
+        players.add(new Player("sys", 20));
+        players.add(new Player("cm", 23));
+        players.add(new Player("lsw", 24));
+
+        // 批处理请求
+        for (int i = 0; i < players.size(); i++) {
+            bulkRequest.add(
+                    new IndexRequest("table_tennis")
+                            .id("" + (i + 1))
+                            .source(JSON.toJSONString(players.get(i)), XContentType.JSON)
+            );
+        }
+        BulkResponse bulkResp = client.bulk(bulkRequest, RequestOptions.DEFAULT);
+        System.err.println(bulkResp.hasFailures()); // 是否失败,返回false 代表成功。
+    }
+
+    // 查询
+    // SearchRequest 搜索请求
+    // SearchSourceBuilder 条件构造
+    // HighlightBuilder 构建高亮
+    // TermQueryBuilder 精确查询
+    // MatchAllQueryBuilder 匹配所有
+    // xxx QueryBuilder 对应我们得命令。
+    @Test
+    void testSearch() throws IOException {
+        SearchRequest searchRequest = new SearchRequest(Constant.ES_INDEX);
+        // 构建搜索条件
+        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
+
+        // 查询条件,用QueryBuilders实现
+        // QueryBuilders.termQuery 精确查找
+        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "wmy");
+
+        // QueryBuilders.matchAllQuery() 匹配所有。
+        // MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
+
+        searchSourceBuilder.query(termQueryBuilder);
+        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
+
+        searchRequest.source(searchSourceBuilder);
+
+        SearchResponse searchResp = client.search(searchRequest, RequestOptions.DEFAULT);
+        System.out.println(JSON.toJSONString(searchResp.getHits()));
+        System.out.println("=========================================");
+        for (SearchHit hit : searchResp.getHits()) {
+            System.out.println(hit.getSourceAsMap());
+        }
+
+
+    }
+
+    // 删除文档信息
+    @Test
+    void testDelDocByName() throws IOException {
+        DeleteRequest delReq = new DeleteRequest("table_tennis", "1");
+        delReq.timeout("1s");
+
+        SearchRequest searchRequest = new SearchRequest(Constant.ES_INDEX);
+        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
+        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "wmy");
+        searchSourceBuilder.query(termQueryBuilder);
+        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
+
+        searchRequest.source(searchSourceBuilder);
+
+        SearchResponse searchResp = client.search(searchRequest, RequestOptions.DEFAULT);
+        DeleteResponse delResp = client.delete(delReq, RequestOptions.DEFAULT);
+        System.out.println(delResp);
+        System.out.println(delResp.status());
+    }
 
 }

+ 13 - 0
ghj-es-api/src/test/java/com/test/jdes/JdEsApplicationTests.java

@@ -0,0 +1,13 @@
+package com.test.jdes;
+
+import org.junit.jupiter.api.Test;
+import org.springframework.boot.test.context.SpringBootTest;
+
+@SpringBootTest
+class JdEsApplicationTests {
+
+    @Test
+    void contextLoads() {
+    }
+
+}

+ 33 - 0
jd-es/.gitignore

@@ -0,0 +1,33 @@
+HELP.md
+target/
+!.mvn/wrapper/maven-wrapper.jar
+!**/src/main/**/target/
+!**/src/test/**/target/
+
+### STS ###
+.apt_generated
+.classpath
+.factorypath
+.project
+.settings
+.springBeans
+.sts4-cache
+
+### IntelliJ IDEA ###
+.idea
+*.iws
+*.iml
+*.ipr
+
+### NetBeans ###
+/nbproject/private/
+/nbbuild/
+/dist/
+/nbdist/
+/.nb-gradle/
+build/
+!**/src/main/**/build/
+!**/src/test/**/build/
+
+### VS Code ###
+.vscode/

+ 118 - 0
jd-es/.mvn/wrapper/MavenWrapperDownloader.java

@@ -0,0 +1,118 @@
+/*
+ * Copyright 2007-present the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import java.net.*;
+import java.io.*;
+import java.nio.channels.*;
+import java.util.Properties;
+
+public class MavenWrapperDownloader {
+
+    private static final String WRAPPER_VERSION = "0.5.6";
+    /**
+     * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
+     */
+    private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+            + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
+
+    /**
+     * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
+     * use instead of the default one.
+     */
+    private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
+            ".mvn/wrapper/maven-wrapper.properties";
+
+    /**
+     * Path where the maven-wrapper.jar will be saved to.
+     */
+    private static final String MAVEN_WRAPPER_JAR_PATH =
+            ".mvn/wrapper/maven-wrapper.jar";
+
+    /**
+     * Name of the property which should be used to override the default download url for the wrapper.
+     */
+    private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
+
+    public static void main(String args[]) {
+        System.out.println("- Downloader started");
+        File baseDirectory = new File(args[0]);
+        System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
+
+        // If the maven-wrapper.properties exists, read it and check if it contains a custom
+        // wrapperUrl parameter.
+        File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
+        String url = DEFAULT_DOWNLOAD_URL;
+        if (mavenWrapperPropertyFile.exists()) {
+            FileInputStream mavenWrapperPropertyFileInputStream = null;
+            try {
+                mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
+                Properties mavenWrapperProperties = new Properties();
+                mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
+                url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
+            } catch (IOException e) {
+                System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
+            } finally {
+                try {
+                    if (mavenWrapperPropertyFileInputStream != null) {
+                        mavenWrapperPropertyFileInputStream.close();
+                    }
+                } catch (IOException e) {
+                    // Ignore ...
+                }
+            }
+        }
+        System.out.println("- Downloading from: " + url);
+
+        File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
+        if (!outputFile.getParentFile().exists()) {
+            if (!outputFile.getParentFile().mkdirs()) {
+                System.out.println(
+                        "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
+            }
+        }
+        System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
+        try {
+            downloadFileFromURL(url, outputFile);
+            System.out.println("Done");
+            System.exit(0);
+        } catch (Throwable e) {
+            System.out.println("- Error downloading");
+            e.printStackTrace();
+            System.exit(1);
+        }
+    }
+
+    private static void downloadFileFromURL(String urlString, File destination) throws Exception {
+        if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
+            String username = System.getenv("MVNW_USERNAME");
+            char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
+            Authenticator.setDefault(new Authenticator() {
+                @Override
+                protected PasswordAuthentication getPasswordAuthentication() {
+                    return new PasswordAuthentication(username, password);
+                }
+            });
+        }
+        URL website = new URL(urlString);
+        ReadableByteChannel rbc;
+        rbc = Channels.newChannel(website.openStream());
+        FileOutputStream fos = new FileOutputStream(destination);
+        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
+        fos.close();
+        rbc.close();
+    }
+
+}

BIN
jd-es/.mvn/wrapper/maven-wrapper.jar


+ 2 - 0
jd-es/.mvn/wrapper/maven-wrapper.properties

@@ -0,0 +1,2 @@
+distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.2/apache-maven-3.8.2-bin.zip
+wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar

+ 310 - 0
jd-es/mvnw

@@ -0,0 +1,310 @@
+#!/bin/sh
+# ----------------------------------------------------------------------------
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#    https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+# ----------------------------------------------------------------------------
+
+# ----------------------------------------------------------------------------
+# Maven Start Up Batch script
+#
+# Required ENV vars:
+# ------------------
+#   JAVA_HOME - location of a JDK home dir
+#
+# Optional ENV vars
+# -----------------
+#   M2_HOME - location of maven2's installed home dir
+#   MAVEN_OPTS - parameters passed to the Java VM when running Maven
+#     e.g. to debug Maven itself, use
+#       set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
+#   MAVEN_SKIP_RC - flag to disable loading of mavenrc files
+# ----------------------------------------------------------------------------
+
+if [ -z "$MAVEN_SKIP_RC" ] ; then
+
+  if [ -f /etc/mavenrc ] ; then
+    . /etc/mavenrc
+  fi
+
+  if [ -f "$HOME/.mavenrc" ] ; then
+    . "$HOME/.mavenrc"
+  fi
+
+fi
+
+# OS specific support.  $var _must_ be set to either true or false.
+cygwin=false;
+darwin=false;
+mingw=false
+case "`uname`" in
+  CYGWIN*) cygwin=true ;;
+  MINGW*) mingw=true;;
+  Darwin*) darwin=true
+    # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
+    # See https://developer.apple.com/library/mac/qa/qa1170/_index.html
+    if [ -z "$JAVA_HOME" ]; then
+      if [ -x "/usr/libexec/java_home" ]; then
+        export JAVA_HOME="`/usr/libexec/java_home`"
+      else
+        export JAVA_HOME="/Library/Java/Home"
+      fi
+    fi
+    ;;
+esac
+
+if [ -z "$JAVA_HOME" ] ; then
+  if [ -r /etc/gentoo-release ] ; then
+    JAVA_HOME=`java-config --jre-home`
+  fi
+fi
+
+if [ -z "$M2_HOME" ] ; then
+  ## resolve links - $0 may be a link to maven's home
+  PRG="$0"
+
+  # need this for relative symlinks
+  while [ -h "$PRG" ] ; do
+    ls=`ls -ld "$PRG"`
+    link=`expr "$ls" : '.*-> \(.*\)$'`
+    if expr "$link" : '/.*' > /dev/null; then
+      PRG="$link"
+    else
+      PRG="`dirname "$PRG"`/$link"
+    fi
+  done
+
+  saveddir=`pwd`
+
+  M2_HOME=`dirname "$PRG"`/..
+
+  # make it fully qualified
+  M2_HOME=`cd "$M2_HOME" && pwd`
+
+  cd "$saveddir"
+  # echo Using m2 at $M2_HOME
+fi
+
+# For Cygwin, ensure paths are in UNIX format before anything is touched
+if $cygwin ; then
+  [ -n "$M2_HOME" ] &&
+    M2_HOME=`cygpath --unix "$M2_HOME"`
+  [ -n "$JAVA_HOME" ] &&
+    JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
+  [ -n "$CLASSPATH" ] &&
+    CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
+fi
+
+# For Mingw, ensure paths are in UNIX format before anything is touched
+if $mingw ; then
+  [ -n "$M2_HOME" ] &&
+    M2_HOME="`(cd "$M2_HOME"; pwd)`"
+  [ -n "$JAVA_HOME" ] &&
+    JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
+fi
+
+if [ -z "$JAVA_HOME" ]; then
+  javaExecutable="`which javac`"
+  if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
+    # readlink(1) is not available as standard on Solaris 10.
+    readLink=`which readlink`
+    if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
+      if $darwin ; then
+        javaHome="`dirname \"$javaExecutable\"`"
+        javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
+      else
+        javaExecutable="`readlink -f \"$javaExecutable\"`"
+      fi
+      javaHome="`dirname \"$javaExecutable\"`"
+      javaHome=`expr "$javaHome" : '\(.*\)/bin'`
+      JAVA_HOME="$javaHome"
+      export JAVA_HOME
+    fi
+  fi
+fi
+
+if [ -z "$JAVACMD" ] ; then
+  if [ -n "$JAVA_HOME"  ] ; then
+    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+      # IBM's JDK on AIX uses strange locations for the executables
+      JAVACMD="$JAVA_HOME/jre/sh/java"
+    else
+      JAVACMD="$JAVA_HOME/bin/java"
+    fi
+  else
+    JAVACMD="`which java`"
+  fi
+fi
+
+if [ ! -x "$JAVACMD" ] ; then
+  echo "Error: JAVA_HOME is not defined correctly." >&2
+  echo "  We cannot execute $JAVACMD" >&2
+  exit 1
+fi
+
+if [ -z "$JAVA_HOME" ] ; then
+  echo "Warning: JAVA_HOME environment variable is not set."
+fi
+
+CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
+
+# traverses directory structure from process work directory to filesystem root
+# first directory with .mvn subdirectory is considered project base directory
+find_maven_basedir() {
+
+  if [ -z "$1" ]
+  then
+    echo "Path not specified to find_maven_basedir"
+    return 1
+  fi
+
+  basedir="$1"
+  wdir="$1"
+  while [ "$wdir" != '/' ] ; do
+    if [ -d "$wdir"/.mvn ] ; then
+      basedir=$wdir
+      break
+    fi
+    # workaround for JBEAP-8937 (on Solaris 10/Sparc)
+    if [ -d "${wdir}" ]; then
+      wdir=`cd "$wdir/.."; pwd`
+    fi
+    # end of workaround
+  done
+  echo "${basedir}"
+}
+
+# concatenates all lines of a file
+concat_lines() {
+  if [ -f "$1" ]; then
+    echo "$(tr -s '\n' ' ' < "$1")"
+  fi
+}
+
+BASE_DIR=`find_maven_basedir "$(pwd)"`
+if [ -z "$BASE_DIR" ]; then
+  exit 1;
+fi
+
+##########################################################################################
+# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
+# This allows using the maven wrapper in projects that prohibit checking in binary data.
+##########################################################################################
+if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
+    if [ "$MVNW_VERBOSE" = true ]; then
+      echo "Found .mvn/wrapper/maven-wrapper.jar"
+    fi
+else
+    if [ "$MVNW_VERBOSE" = true ]; then
+      echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
+    fi
+    if [ -n "$MVNW_REPOURL" ]; then
+      jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
+    else
+      jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
+    fi
+    while IFS="=" read key value; do
+      case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
+      esac
+    done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
+    if [ "$MVNW_VERBOSE" = true ]; then
+      echo "Downloading from: $jarUrl"
+    fi
+    wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
+    if $cygwin; then
+      wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
+    fi
+
+    if command -v wget > /dev/null; then
+        if [ "$MVNW_VERBOSE" = true ]; then
+          echo "Found wget ... using wget"
+        fi
+        if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
+            wget "$jarUrl" -O "$wrapperJarPath"
+        else
+            wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath"
+        fi
+    elif command -v curl > /dev/null; then
+        if [ "$MVNW_VERBOSE" = true ]; then
+          echo "Found curl ... using curl"
+        fi
+        if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
+            curl -o "$wrapperJarPath" "$jarUrl" -f
+        else
+            curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
+        fi
+
+    else
+        if [ "$MVNW_VERBOSE" = true ]; then
+          echo "Falling back to using Java to download"
+        fi
+        javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
+        # For Cygwin, switch paths to Windows format before running javac
+        if $cygwin; then
+          javaClass=`cygpath --path --windows "$javaClass"`
+        fi
+        if [ -e "$javaClass" ]; then
+            if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
+                if [ "$MVNW_VERBOSE" = true ]; then
+                  echo " - Compiling MavenWrapperDownloader.java ..."
+                fi
+                # Compiling the Java class
+                ("$JAVA_HOME/bin/javac" "$javaClass")
+            fi
+            if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
+                # Running the downloader
+                if [ "$MVNW_VERBOSE" = true ]; then
+                  echo " - Running MavenWrapperDownloader.java ..."
+                fi
+                ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
+            fi
+        fi
+    fi
+fi
+##########################################################################################
+# End of extension
+##########################################################################################
+
+export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
+if [ "$MVNW_VERBOSE" = true ]; then
+  echo $MAVEN_PROJECTBASEDIR
+fi
+MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
+
+# For Cygwin, switch paths to Windows format before running java
+if $cygwin; then
+  [ -n "$M2_HOME" ] &&
+    M2_HOME=`cygpath --path --windows "$M2_HOME"`
+  [ -n "$JAVA_HOME" ] &&
+    JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
+  [ -n "$CLASSPATH" ] &&
+    CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
+  [ -n "$MAVEN_PROJECTBASEDIR" ] &&
+    MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
+fi
+
+# Provide a "standardized" way to retrieve the CLI args that will
+# work with both Windows and non-Windows executions.
+MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
+export MAVEN_CMD_LINE_ARGS
+
+WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
+
+exec "$JAVACMD" \
+  $MAVEN_OPTS \
+  -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
+  "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
+  ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"

+ 182 - 0
jd-es/mvnw.cmd

@@ -0,0 +1,182 @@
+@REM ----------------------------------------------------------------------------
+@REM Licensed to the Apache Software Foundation (ASF) under one
+@REM or more contributor license agreements.  See the NOTICE file
+@REM distributed with this work for additional information
+@REM regarding copyright ownership.  The ASF licenses this file
+@REM to you under the Apache License, Version 2.0 (the
+@REM "License"); you may not use this file except in compliance
+@REM with the License.  You may obtain a copy of the License at
+@REM
+@REM    https://www.apache.org/licenses/LICENSE-2.0
+@REM
+@REM Unless required by applicable law or agreed to in writing,
+@REM software distributed under the License is distributed on an
+@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+@REM KIND, either express or implied.  See the License for the
+@REM specific language governing permissions and limitations
+@REM under the License.
+@REM ----------------------------------------------------------------------------
+
+@REM ----------------------------------------------------------------------------
+@REM Maven Start Up Batch script
+@REM
+@REM Required ENV vars:
+@REM JAVA_HOME - location of a JDK home dir
+@REM
+@REM Optional ENV vars
+@REM M2_HOME - location of maven2's installed home dir
+@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
+@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
+@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
+@REM     e.g. to debug Maven itself, use
+@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
+@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
+@REM ----------------------------------------------------------------------------
+
+@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
+@echo off
+@REM set title of command window
+title %0
+@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
+@if "%MAVEN_BATCH_ECHO%" == "on"  echo %MAVEN_BATCH_ECHO%
+
+@REM set %HOME% to equivalent of $HOME
+if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
+
+@REM Execute a user defined script before this one
+if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
+@REM check for pre script, once with legacy .bat ending and once with .cmd ending
+if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
+if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
+:skipRcPre
+
+@setlocal
+
+set ERROR_CODE=0
+
+@REM To isolate internal variables from possible post scripts, we use another setlocal
+@setlocal
+
+@REM ==== START VALIDATION ====
+if not "%JAVA_HOME%" == "" goto OkJHome
+
+echo.
+echo Error: JAVA_HOME not found in your environment. >&2
+echo Please set the JAVA_HOME variable in your environment to match the >&2
+echo location of your Java installation. >&2
+echo.
+goto error
+
+:OkJHome
+if exist "%JAVA_HOME%\bin\java.exe" goto init
+
+echo.
+echo Error: JAVA_HOME is set to an invalid directory. >&2
+echo JAVA_HOME = "%JAVA_HOME%" >&2
+echo Please set the JAVA_HOME variable in your environment to match the >&2
+echo location of your Java installation. >&2
+echo.
+goto error
+
+@REM ==== END VALIDATION ====
+
+:init
+
+@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
+@REM Fallback to current working directory if not found.
+
+set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
+IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
+
+set EXEC_DIR=%CD%
+set WDIR=%EXEC_DIR%
+:findBaseDir
+IF EXIST "%WDIR%"\.mvn goto baseDirFound
+cd ..
+IF "%WDIR%"=="%CD%" goto baseDirNotFound
+set WDIR=%CD%
+goto findBaseDir
+
+:baseDirFound
+set MAVEN_PROJECTBASEDIR=%WDIR%
+cd "%EXEC_DIR%"
+goto endDetectBaseDir
+
+:baseDirNotFound
+set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
+cd "%EXEC_DIR%"
+
+:endDetectBaseDir
+
+IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
+
+@setlocal EnableExtensions EnableDelayedExpansion
+for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
+@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
+
+:endReadAdditionalConfig
+
+SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
+set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
+set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
+
+set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
+
+FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
+    IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
+)
+
+@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
+@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
+if exist %WRAPPER_JAR% (
+    if "%MVNW_VERBOSE%" == "true" (
+        echo Found %WRAPPER_JAR%
+    )
+) else (
+    if not "%MVNW_REPOURL%" == "" (
+        SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
+    )
+    if "%MVNW_VERBOSE%" == "true" (
+        echo Couldn't find %WRAPPER_JAR%, downloading it ...
+        echo Downloading from: %DOWNLOAD_URL%
+    )
+
+    powershell -Command "&{"^
+		"$webclient = new-object System.Net.WebClient;"^
+		"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
+		"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
+		"}"^
+		"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
+		"}"
+    if "%MVNW_VERBOSE%" == "true" (
+        echo Finished downloading %WRAPPER_JAR%
+    )
+)
+@REM End of extension
+
+@REM Provide a "standardized" way to retrieve the CLI args that will
+@REM work with both Windows and non-Windows executions.
+set MAVEN_CMD_LINE_ARGS=%*
+
+%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
+if ERRORLEVEL 1 goto error
+goto end
+
+:error
+set ERROR_CODE=1
+
+:end
+@endlocal & set ERROR_CODE=%ERROR_CODE%
+
+if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
+@REM check for post script, once with legacy .bat ending and once with .cmd ending
+if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
+if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
+:skipRcPost
+
+@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
+if "%MAVEN_BATCH_PAUSE%" == "on" pause
+
+if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
+
+exit /B %ERROR_CODE%

+ 182 - 0
jd-es/pom.xml

@@ -0,0 +1,182 @@
+<?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 https://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.5.5</version>
+        <relativePath/> <!-- lookup parent from repository -->
+    </parent>
+    <groupId>com.pavis</groupId>
+    <artifactId>jd-es</artifactId>
+    <version>0.0.1</version>
+    <name>jd-es</name>
+    <description>Demo project for Spring Boot</description>
+    <properties>
+        <java.version>1.8</java.version>
+        <spring-cloud.version>2020.0.4</spring-cloud.version>
+        <elasticsearch.version>7.6.1</elasticsearch.version>
+    </properties>
+    <dependencies>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-data-jdbc</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-thymeleaf</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-web</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.cloud</groupId>
+            <artifactId>spring-cloud-starter-openfeign</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-devtools</artifactId>
+            <scope>runtime</scope>
+            <optional>true</optional>
+        </dependency>
+        <dependency>
+            <groupId>mysql</groupId>
+            <artifactId>mysql-connector-java</artifactId>
+            <scope>runtime</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-configuration-processor</artifactId>
+            <optional>true</optional>
+        </dependency>
+        <dependency>
+            <groupId>org.projectlombok</groupId>
+            <artifactId>lombok</artifactId>
+            <optional>true</optional>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-test</artifactId>
+            <scope>test</scope>
+        </dependency>
+
+        <dependency>
+            <groupId>com.baomidou</groupId>
+            <artifactId>mybatis-plus-boot-starter</artifactId>
+            <version>3.2.0</version>
+        </dependency>
+        <dependency>
+            <groupId>io.springfox</groupId>
+            <artifactId>springfox-swagger2</artifactId>
+            <version>2.9.2</version>
+        </dependency>
+        <dependency>
+            <groupId>io.springfox</groupId>
+            <artifactId>springfox-swagger-ui</artifactId>
+            <version>2.9.2</version>
+        </dependency>
+
+        <!-- https://mvnrepository.com/artifact/com.github.xiaoymin/knife4j-spring-ui -->
+        <dependency>
+            <groupId>com.github.xiaoymin</groupId>
+            <artifactId>knife4j-spring-ui</artifactId>
+            <version>2.0.2</version>
+        </dependency>
+
+        <dependency>
+            <groupId>com.github.xiaoymin</groupId>
+            <artifactId>knife4j-spring-boot-starter</artifactId>
+            <!--在引用时请在maven中央仓库搜索最新版本号-->
+            <version>2.0.2</version>
+        </dependency>
+
+        <dependency>
+            <groupId>com.google.guava</groupId>
+            <artifactId>guava</artifactId>
+            <version>27.0.1-jre</version>
+        </dependency>
+
+        <dependency>
+            <groupId>com.alibaba</groupId>
+            <artifactId>fastjson</artifactId>
+            <version>1.2.73</version>
+        </dependency>
+
+        <!--        <dependency>-->
+        <!--            <groupId>joda-time</groupId>-->
+        <!--            <artifactId>joda-time</artifactId>-->
+        <!--        </dependency>-->
+
+        <dependency>
+            <groupId>org.apache.commons</groupId>
+            <artifactId>commons-lang3</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>commons-collections</groupId>
+            <artifactId>commons-collections</artifactId>
+            <version>3.2.2</version>
+        </dependency>
+
+        <dependency>
+            <groupId>commons-codec</groupId>
+            <artifactId>commons-codec</artifactId>
+            <version>1.14</version>
+        </dependency>
+
+        <dependency>
+            <groupId>org.apache.commons</groupId>
+            <artifactId>commons-text</artifactId>
+            <version>1.8</version>
+        </dependency>
+
+        <dependency>
+            <groupId>commons-beanutils</groupId>
+            <artifactId>commons-beanutils</artifactId>
+            <version>1.9.4</version>
+        </dependency>
+
+        <!-- jsoup解析网页 -->
+        <dependency>
+            <groupId>org.jsoup</groupId>
+            <artifactId>jsoup</artifactId>
+            <version>1.10.2</version>
+        </dependency>
+    </dependencies>
+    <dependencyManagement>
+        <dependencies>
+            <dependency>
+                <groupId>org.springframework.cloud</groupId>
+                <artifactId>spring-cloud-dependencies</artifactId>
+                <version>${spring-cloud.version}</version>
+                <type>pom</type>
+                <scope>import</scope>
+            </dependency>
+        </dependencies>
+    </dependencyManagement>
+
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.springframework.boot</groupId>
+                <artifactId>spring-boot-maven-plugin</artifactId>
+                <configuration>
+                    <excludes>
+                        <exclude>
+                            <groupId>org.projectlombok</groupId>
+                            <artifactId>lombok</artifactId>
+                        </exclude>
+                    </excludes>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+
+</project>

+ 14 - 0
jd-es/src/main/java/com/pavis/jdes/JdEsApplication.java

@@ -0,0 +1,14 @@
+package com.pavis.jdes;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
+
+@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
+public class JdEsApplication {
+
+    public static void main(String[] args) {
+        SpringApplication.run(JdEsApplication.class, args);
+    }
+
+}

+ 31 - 0
jd-es/src/main/java/com/pavis/jdes/common/CorsFilterConfig.java

@@ -0,0 +1,31 @@
+package com.pavis.jdes.common;
+
+import org.springframework.core.Ordered;
+import org.springframework.core.annotation.Order;
+import org.springframework.stereotype.Component;
+
+import javax.servlet.*;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+@Component
+@Order(Ordered.HIGHEST_PRECEDENCE)
+public class CorsFilterConfig implements Filter {
+
+    @Override
+    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
+        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
+        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
+        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
+        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
+        httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
+        httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
+        httpServletResponse.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
+        if ("OPTIONS".equalsIgnoreCase(httpServletRequest.getMethod())) {
+            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
+        } else {
+            chain.doFilter(httpServletRequest, httpServletResponse);
+        }
+    }
+}

+ 46 - 0
jd-es/src/main/java/com/pavis/jdes/controller/IndexController.java

@@ -0,0 +1,46 @@
+package com.pavis.jdes.controller;
+
+import com.pavis.jdes.service.JdContentService;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RestController;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * @program: test-es
+ * @description:
+ * @author: Guanzi
+ * @created: 2021/10/08 13:35
+ */
+@RestController
+// @Controller
+@Slf4j
+public class IndexController {
+
+    @Autowired
+    private JdContentService jdContentService;
+
+    // @GetMapping({"/","/index"})
+    // public String index(){
+    //     return "index";
+    // }
+
+    @GetMapping("/parse/{keyword}")
+    public Boolean parse(@PathVariable("keyword") String keyword) throws IOException {
+        log.info("keyword:{}",keyword);
+        return jdContentService.parseContent(keyword);
+    }
+
+    @GetMapping("/search/{keyword}/{pageNo}/{pageSize}")
+    public List<Map<String,Object>> search(@PathVariable("keyword") String keyword,
+                                           @PathVariable("pageNo") int pageNo,
+                                           @PathVariable("pageSize") int pageSize) throws IOException {
+        log.info("keyword:{},pageNo:{},pageSize:{}",keyword,pageNo,pageSize);
+        return jdContentService.search(keyword,pageNo,pageSize);
+    }
+}

+ 24 - 0
jd-es/src/main/java/com/pavis/jdes/pojo/JdContent.java

@@ -0,0 +1,24 @@
+package com.pavis.jdes.pojo;
+
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+/**
+ * @program: test-es
+ * @description:
+ * @author: Guanzi
+ * @created: 2021/10/08 14:13
+ */
+@Data
+@AllArgsConstructor
+@NoArgsConstructor
+@Builder
+public class JdContent {
+    private String title;
+    private String img;
+    private String price;
+    private String commit;
+    private String shop;
+}

+ 29 - 0
jd-es/src/main/java/com/pavis/jdes/service/JdContentService.java

@@ -0,0 +1,29 @@
+package com.pavis.jdes.service;
+
+
+import org.springframework.web.bind.annotation.PathVariable;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+
+public interface JdContentService {
+
+    /**
+     * 解析内容。
+     * @param keywords
+     * @return
+     */
+    Boolean parseContent(String keywords) throws IOException;
+
+    /**
+     * 检索
+     * @param keyword
+     * @param pageNo
+     * @param pageSize
+     * @return
+     */
+    List<Map<String,Object>> search(@PathVariable("keyword") String keyword,
+                                    @PathVariable("pageNo") int pageNo,
+                                    @PathVariable("pageSize") int pageSize) throws IOException;
+}

+ 118 - 0
jd-es/src/main/java/com/pavis/jdes/service/impl/JdContentServiceImpl.java

@@ -0,0 +1,118 @@
+package com.pavis.jdes.service.impl;
+
+import com.alibaba.fastjson.JSON;
+import com.pavis.jdes.pojo.JdContent;
+import com.pavis.jdes.service.JdContentService;
+import com.pavis.jdes.utils.HtmlParseUtil;
+import lombok.extern.slf4j.Slf4j;
+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.text.Text;
+import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.common.xcontent.XContentType;
+import org.elasticsearch.index.query.QueryBuilders;
+import org.elasticsearch.index.query.TermQueryBuilder;
+import org.elasticsearch.search.SearchHit;
+import org.elasticsearch.search.builder.SearchSourceBuilder;
+import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
+import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * @program: test-es
+ * @description:
+ * @author: Guanzi
+ * @created: 2021/10/08 14:20
+ */
+@Slf4j
+@Service
+public class JdContentServiceImpl implements JdContentService {
+
+    @Autowired
+    private RestHighLevelClient restHighLevelClient;
+
+    @Override
+    public Boolean parseContent(String keywords) throws IOException {
+        List<JdContent> jdContents = new HtmlParseUtil().parseJd(keywords);
+        // 把查询到得数据放入es中
+        BulkRequest bulkRequest = new BulkRequest();
+        bulkRequest.timeout("2m");
+        for (int i = 0; i < jdContents.size(); i++) {
+            bulkRequest.add(
+                    new IndexRequest("jd_goods")
+                    .source(JSON.toJSONString(jdContents.get(i)), XContentType.JSON)
+            );
+
+        }
+        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
+        return !bulk.hasFailures();
+    }
+
+    @Override
+    public List<Map<String, Object>> search(String keyword, int pageNo, int pageSize) throws IOException {
+        if (pageNo <= 1){
+            pageNo = 1;
+        }
+        // 条件搜索
+        SearchRequest searchRequest = new SearchRequest("jd_goods");
+        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
+
+        // 分页
+        sourceBuilder.from(pageNo);
+        sourceBuilder.size(pageSize);
+
+        // 精准匹配
+        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title",keyword);
+        sourceBuilder.query(termQueryBuilder);
+        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
+
+        // 高亮
+        HighlightBuilder highlightBuilder = new HighlightBuilder();
+        highlightBuilder.field("title");
+        // highlightBuilder.field("commit");
+        highlightBuilder.requireFieldMatch(false); // 多个高亮显示
+        highlightBuilder.preTags("<span style='color:red'>");
+        highlightBuilder.postTags("</span>");
+        sourceBuilder.highlighter(highlightBuilder);
+
+
+        // 执行搜索
+        searchRequest.source(sourceBuilder);
+        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
+
+        // 解析结果
+        List<Map<String,Object>> mapList = new ArrayList<>();
+        for (SearchHit hit : searchResponse.getHits().getHits()) {
+
+            Map<String, HighlightField> highlightFieldMap = hit.getHighlightFields() ;
+            HighlightField title = highlightFieldMap.get("title");
+            Map<String,Object> sourceAsMap = hit.getSourceAsMap();
+            // 解析高亮字段,将原来得字段换为高亮字段。
+            if (null != title){
+                Text[] fragments = title.fragments();
+                String newTitle = "";
+                for (Text fragment : fragments) {
+                    newTitle += fragment;
+                }
+                sourceAsMap.put("title",newTitle);
+            }
+            // 不高亮
+            // mapList.add(hit.getSourceAsMap());
+            // 高亮。
+            mapList.add(sourceAsMap);
+        }
+        return mapList;
+    }
+}

+ 70 - 0
jd-es/src/main/java/com/pavis/jdes/utils/HtmlParseUtil.java

@@ -0,0 +1,70 @@
+package com.pavis.jdes.utils;
+
+import com.pavis.jdes.pojo.JdContent;
+import org.jsoup.Jsoup;
+import org.jsoup.nodes.Document;
+import org.jsoup.nodes.Element;
+import org.jsoup.select.Elements;
+import org.springframework.stereotype.Component;
+
+import java.io.IOException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * @program: test-es
+ * @description:
+ * @author: Guanzi
+ * @created: 2021/10/08 13:52
+ */
+@Component
+public class HtmlParseUtil {
+
+    public static void main(String[] args) throws IOException {
+        new HtmlParseUtil().parseJd("java").forEach(System.out::println);
+    }
+
+    public List<JdContent> parseJd(String keywords) throws IOException{
+        // https://search.jd.com/Search
+        String url = "https://search.jd.com/Search?keyword=" + keywords;
+        // 解析网页。(Jsoup 返回Document就是浏览器得Document对象)
+        Document document = Jsoup.parse(new URL(url),30000);
+        // js中可以使用得方法,这里都可用。
+        Element element = document.getElementById("J_goodsList");
+        System.out.println(element.html());
+
+        // 获取所有li元素
+        Elements elements = element.getElementsByTag("li");
+
+        // 初始化对象:
+        JdContent jdContent;
+        List<JdContent> jdContents = new ArrayList<>();
+
+        // 获取元素中得内容,这里el就是每一个li标签了。
+        for (Element el : elements) {
+            // 图片多的网站,是延迟加载的。source-data-lazy-img
+            String img = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
+            String price = el.getElementsByClass("p-price").eq(0).text();
+            String title = el.getElementsByClass("p-name").eq(0).text();
+            String commit = el.getElementsByClass("p-commit").eq(0).text();
+            String shop = el.getElementsByClass("p-shop").eq(0).text();
+
+            System.out.println("============================");
+            System.out.println(img);
+            System.out.println(price);
+            System.out.println(title);
+            System.out.println(commit);
+
+            jdContent = new JdContent().builder()
+                    .title(title)
+                    .price(price)
+                    .img(img)
+                    .commit(commit)
+                    .shop(shop)
+                    .build();
+            jdContents.add(jdContent);
+        }
+        return jdContents;
+    }
+}

+ 6 - 0
jd-es/src/main/resources/application.yml

@@ -0,0 +1,6 @@
+server:
+  port: 9083
+# ¹Ø±Õ thymeleafµÃ»º´æ¡£
+spring:
+  thymeleaf:
+    cache: false

File diff suppressed because it is too large
+ 0 - 0
jd-es/src/main/resources/static/css/style.css


BIN
jd-es/src/main/resources/static/images/jdlogo.png


BIN
jd-es/src/main/resources/static/images/wmyy.jpg


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


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


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


+ 183 - 0
jd-es/src/main/resources/templates/index.html

@@ -0,0 +1,183 @@
+<!DOCTYPE html>
+<html xmlns:th="http://www.thymeleaf.org" xmlns:v-on="http://www.w3.org/1999/xhtml"
+      xmlns:v-bind="http://www.w3.org/1999/xhtml">
+
+<head>
+    <meta charset="utf-8"/>
+    <title>狂神说Java-ES仿京东实战</title>
+    <link rel="stylesheet" th:href="@{/css/style.css}"/>
+    <script th:src="@{/js/axios.min.js}"></script>
+    <script th:src="@{/js/vue.min.js}"></script>
+</head>
+
+<body class="pg">
+<div class="page" id="app">
+    <div id="mallPage" class=" mallist tmall- page-not-market ">
+
+        <!-- 头部搜索 -->
+        <div id="header" class=" header-list-app">
+            <div class="headerLayout">
+                <div class="headerCon ">
+                    <!-- Logo-->
+                    <h1 id="mallLogo">
+                        <img th:src="@{/images/jdlogo.png}" alt="">
+                    </h1>
+
+                    <div class="header-extra">
+
+                        <!--搜索-->
+                        <div id="mallSearch" class="mall-search">
+                            <form name="searchTop" class="mallSearch-form clearfix">
+                                <fieldset>
+                                    <legend>天猫搜索</legend>
+                                    <div class="mallSearch-input clearfix">
+                                        <div class="s-combobox" id="s-combobox-685">
+                                            <div class="s-combobox-input-wrap">
+                                                <input v-model="keyword" type="text" autocomplete="off" value="dd" id="mq"
+                                                       class="s-combobox-input" aria-haspopup="true">
+                                            </div>
+                                        </div>
+                                        <button type="submit" @click.prevent="searchKey" id="searchbtn">搜索</button>
+                                    </div>
+                                </fieldset>
+                            </form>
+                            <ul class="relKeyTop">
+                                <li><a>狂神说Java</a></li>
+                                <li><a>狂神说前端</a></li>
+                                <li><a>狂神说Linux</a></li>
+                                <li><a>狂神说大数据</a></li>
+                                <li><a>狂神聊理财</a></li>
+                            </ul>
+                        </div>
+                    </div>
+                </div>
+            </div>
+        </div>
+
+        <!-- 商品详情页面 -->
+        <div id="content">
+            <div class="main">
+                <!-- 品牌分类 -->
+                <form class="navAttrsForm">
+                    <div class="attrs j_NavAttrs" style="display:block">
+                        <div class="brandAttr j_nav_brand">
+                            <div class="j_Brand attr">
+                                <div class="attrKey">
+                                    品牌
+                                </div>
+                                <div class="attrValues">
+                                    <ul class="av-collapse row-2">
+                                        <li><a href="#"> 狂神说 </a></li>
+                                        <li><a href="#"> Java </a></li>
+                                    </ul>
+                                </div>
+                            </div>
+                        </div>
+                    </div>
+                </form>
+
+                <!-- 排序规则 -->
+                <div class="filter clearfix">
+                    <a class="fSort fSort-cur">综合<i class="f-ico-arrow-d"></i></a>
+                    <a class="fSort">人气<i class="f-ico-arrow-d"></i></a>
+                    <a class="fSort">新品<i class="f-ico-arrow-d"></i></a>
+                    <a class="fSort">销量<i class="f-ico-arrow-d"></i></a>
+                    <a class="fSort">价格<i class="f-ico-triangle-mt"></i><i class="f-ico-triangle-mb"></i></a>
+                </div>
+
+                <!-- 商品详情 -->
+                <div class="view grid-nosku">
+
+                    <div class="product" v-for="result in results">
+                        <div class="product-iWrap">
+                            <!--商品封面-->
+                            <div class="productImg-wrap">
+                                <a class="productImg">
+<!--                                    <img src="https://img.alicdn.com/bao/uploaded/i1/3899981502/O1CN01q1uVx21MxxSZs8TVn_!!0-item_pic.jpg">-->
+<!--                                    <img th:src="@{/images/wmyy.jpg}">-->
+                                    <img :src="result.img">
+                                </a>
+                            </div>
+                            <!--价格-->
+                            <p class="productPrice">
+<!--                                <em><b>¥</b>2590.00</em>-->
+                                <em>{{result.price}}</em>
+                            </p>
+                            <!--标题-->
+                            <p class="productTitle">
+                                <a v-html="result.title"></a>
+                            </p>
+                            <!-- 评价 -->
+                            <div class="productCommit">
+                                <span>评价:<em v-html="result.commit"></em></span>
+                            </div>
+                            <!-- 店铺名 -->
+                            <div class="productShop">
+                                <span>{{result.shop}}</span>
+                            </div>
+                            <!-- 成交信息 -->
+                            <p class="productStatus">
+                                <span>月成交<em>999笔</em></span>
+                                <span>评价 <a>3</a></span>
+                            </p>
+                        </div>
+                    </div>
+                </div>
+            </div>
+        </div>
+    </div>
+</div>
+<template>
+    <div class="pager" id="pageee">
+        <a href="javascript:void(0);" v-show="showFirstPage" v-on:click="firstPage" >首页</a>
+        <a href="javascript:void(0);" v-show="showPrevPage" v-on:click="prevPage" >上一页</a>
+        <a href="javascript:void(0);" v-show="showNextPage" v-on:click="nextPage" >下一页</a>
+        <a href="javascript:void(0);" v-show="showLastPage" v-on:click="lastPage" >尾页</a>
+        <div>
+            <select v-model="rowNum">
+                <option value="10">10</option>
+                <option selected="selected" value="20">20</option>
+                <option value="50">50</option>
+                <option value="100">100</option>
+            </select>
+        </div>
+        <span>{{curPage}}/{{total}}</span>
+        <div class="goto">
+            <input type="text" v-model="gotoPage" />
+            <a href="javascript:void(0);" v-on:click="gotoNextPage" >跳转</a>
+        </div>
+    </div>
+</template>
+
+<script th:src="@{/js/axios.min.js}"></script>
+<script th:src="@{/js/vue.min.js}"></script>
+<!--<script th:src="@{/js/jquery.min.js}"></script>-->
+<script>
+    new Vue({
+        el: '#app',
+        data: {
+            keyword: '', // 搜索关键词
+            gotoPage: 1,
+            rowNum: 8,
+            results: [] // 搜索得结果
+        },
+        methods: {
+
+            searchKey(){
+                var keyword = this.keyword;
+                var pageNo = this.gotoPage;
+                var pageSize = this.rowNum;
+                console.log(keyword);
+                // 调用后端接口
+                // axios.get('search/' + keyword + "/1/10").then(response=>{
+                axios.get('search/' + keyword + "/"+ pageNo + "/" + pageSize).then(response=>{
+                    console.log(response);
+                    this.results = response.data; // 绑定数据。
+                })
+            }
+        }
+    })
+</script>
+
+</body>
+</html>

+ 13 - 0
jd-es/src/test/java/com/pavis/jdes/JdEsApplicationTests.java

@@ -0,0 +1,13 @@
+package com.pavis.jdes;
+
+import org.junit.jupiter.api.Test;
+import org.springframework.boot.test.context.SpringBootTest;
+
+@SpringBootTest
+class JdEsApplicationTests {
+
+    @Test
+    void contextLoads() {
+    }
+
+}

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