From 03cb49cc0d5009efe0e32981a9cf95daedbfffb6 Mon Sep 17 00:00:00 2001 From: gyc <2649472510@qq.com> Date: Fri, 26 Apr 2024 14:55:25 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0es=E7=9A=84=E8=BF=9C=E7=A8=8B?= =?UTF-8?q?=E8=BF=9E=E6=8E=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bawei-base/base-es/base-es-common/pom.xml | 58 +--- .../es/config/InitEsRestHighLevelClient.java | 36 -- .../java/com/bawei/es/domain/CommonMap.java | 27 ++ .../com/bawei/es/domain/DocumentClass.java | 19 -- .../main/java/com/bawei/es/domain/Page.java | 21 -- .../main/java/com/bawei/es/domain/Sort.java | 15 - bawei-base/base-es/base-es-remote/pom.xml | 12 +- .../es/remote/api/RemoteDocumentService.java | 28 ++ .../es/remote/api/RemoteIndexService.java | 33 ++ .../RemoteDocumentFallbackFactory.java | 43 +++ .../factory/RemoteIndexFallbackFactory.java | 52 +++ ...ot.autoconfigure.AutoConfiguration.imports | 3 +- bawei-base/base-es/base-es-server/pom.xml | 49 ++- .../java/com/bawei/es/BaWeiEsApplication.java | 13 +- .../bawei/es/config/ElasticSearchConfig.java | 59 ++++ .../bawei/es/controller/DocController.java | 57 ---- .../es/controller/DocumentController.java | 49 +++ .../bawei/es/controller/IndexController.java | 55 +-- .../java/com/bawei/es/service/DocService.java | 19 -- .../com/bawei/es/service/DocumentService.java | 22 ++ .../com/bawei/es/service/IndexService.java | 20 +- .../bawei/es/service/impl/DocServiceImpl.java | 181 ---------- .../es/service/impl/DocumentServiceImpl.java | 320 ++++++++++++++++++ .../es/service/impl/IndexServiceImpl.java | 219 +++++++----- .../src/main/resources/bootstrap.yml | 4 +- bawei-base/base-file/base-file-remote/pom.xml | 3 +- .../file/remote/api/RemoteFileService.java | 6 +- .../core/constant/ServiceNameConstants.java | 3 + pom.xml | 6 + 29 files changed, 906 insertions(+), 526 deletions(-) delete mode 100644 bawei-base/base-es/base-es-common/src/main/java/com/bawei/es/config/InitEsRestHighLevelClient.java create mode 100644 bawei-base/base-es/base-es-common/src/main/java/com/bawei/es/domain/CommonMap.java delete mode 100644 bawei-base/base-es/base-es-common/src/main/java/com/bawei/es/domain/DocumentClass.java delete mode 100644 bawei-base/base-es/base-es-common/src/main/java/com/bawei/es/domain/Page.java delete mode 100644 bawei-base/base-es/base-es-common/src/main/java/com/bawei/es/domain/Sort.java create mode 100644 bawei-base/base-es/base-es-remote/src/main/java/com/bawei/es/remote/api/RemoteDocumentService.java create mode 100644 bawei-base/base-es/base-es-remote/src/main/java/com/bawei/es/remote/api/RemoteIndexService.java create mode 100644 bawei-base/base-es/base-es-remote/src/main/java/com/bawei/es/remote/factory/RemoteDocumentFallbackFactory.java create mode 100644 bawei-base/base-es/base-es-remote/src/main/java/com/bawei/es/remote/factory/RemoteIndexFallbackFactory.java create mode 100644 bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/config/ElasticSearchConfig.java delete mode 100644 bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/controller/DocController.java create mode 100644 bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/controller/DocumentController.java delete mode 100644 bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/DocService.java create mode 100644 bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/DocumentService.java delete mode 100644 bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/impl/DocServiceImpl.java create mode 100644 bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/impl/DocumentServiceImpl.java diff --git a/bawei-base/base-es/base-es-common/pom.xml b/bawei-base/base-es/base-es-common/pom.xml index ea954cf..6c6c50c 100644 --- a/bawei-base/base-es/base-es-common/pom.xml +++ b/bawei-base/base-es/base-es-common/pom.xml @@ -2,12 +2,12 @@ - 4.0.0 - com.bawei base-es + com.bawei 3.6.0 + 4.0.0 base-es-common @@ -16,53 +16,13 @@ 8 UTF-8 - - - - com.bawei - bawei-common-core - - - org.elasticsearch.client - elasticsearch-rest-high-level-client - - - - com.alibaba.cloud - spring-cloud-starter-alibaba-nacos-discovery - - - - com.alibaba.cloud - spring-cloud-starter-alibaba-nacos-config - + - - - com.alibaba.cloud - spring-cloud-starter-alibaba-sentinel - - - - - org.springframework.boot - spring-boot-starter-actuator - - - - - - io.minio - minio - ${minio.version} - - - - - com.bawei - bawei-common-swagger - - - + + + com.bawei + bawei-common-core + + diff --git a/bawei-base/base-es/base-es-common/src/main/java/com/bawei/es/config/InitEsRestHighLevelClient.java b/bawei-base/base-es/base-es-common/src/main/java/com/bawei/es/config/InitEsRestHighLevelClient.java deleted file mode 100644 index 942a775..0000000 --- a/bawei-base/base-es/base-es-common/src/main/java/com/bawei/es/config/InitEsRestHighLevelClient.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.bawei.es.config; - -import lombok.Data; -import lombok.extern.log4j.Log4j2; -import org.apache.http.HttpHost; -import org.elasticsearch.client.RestClient; -import org.elasticsearch.client.RestClientBuilder; -import org.elasticsearch.client.RestHighLevelClient; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * @BelongsProject: day20k-6.12 - * @BelongsPackage: com.bwie.es.conifg - * @Author: LiFan - * @CreateTime: 2023-06-12 14:33 - * @Description: //TODO - * @Version: 1.0 - */ -@Configuration -@ConfigurationProperties(prefix = "es") -@Data -@Log4j2 -public class InitEsRestHighLevelClient { - private String host; - private Integer port; - private String scheme; - - @Bean - public RestHighLevelClient RestHighLevelClient() { - return new RestHighLevelClient( - RestClient.builder(new HttpHost(host,port,scheme)) - ); - } -} diff --git a/bawei-base/base-es/base-es-common/src/main/java/com/bawei/es/domain/CommonMap.java b/bawei-base/base-es/base-es-common/src/main/java/com/bawei/es/domain/CommonMap.java new file mode 100644 index 0000000..ac3042e --- /dev/null +++ b/bawei-base/base-es/base-es-common/src/main/java/com/bawei/es/domain/CommonMap.java @@ -0,0 +1,27 @@ +package com.bawei.es.domain; + +import lombok.Data; + +import java.util.Map; + +/** + * @Author: 31966 + * @Project: mall-product + * @Package: com.bawei.es.domain + * @ClassName: CommonMap + * @Description: 请在此处填写具体描述 + * @Date: 2024/4/23 14:29 + */ +@Data +public class CommonMap { + + /** + * 个数 + */ + private long total; + + /** + * 查询数据 + */ + private Map objectMap; +} diff --git a/bawei-base/base-es/base-es-common/src/main/java/com/bawei/es/domain/DocumentClass.java b/bawei-base/base-es/base-es-common/src/main/java/com/bawei/es/domain/DocumentClass.java deleted file mode 100644 index 84e6956..0000000 --- a/bawei-base/base-es/base-es-common/src/main/java/com/bawei/es/domain/DocumentClass.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.bawei.es.domain; - -import lombok.Data; - -/** - * 文档类 - * - * @program: mall_cloud - * @ClassName: DocumentClass - * @author: Gyc - * @create: 2024-04-24 20:27 - **/ -@Data -public class DocumentClass { - private String indexName; - private String shopName; - private Page page; - private Sort sort; -} diff --git a/bawei-base/base-es/base-es-common/src/main/java/com/bawei/es/domain/Page.java b/bawei-base/base-es/base-es-common/src/main/java/com/bawei/es/domain/Page.java deleted file mode 100644 index f041a92..0000000 --- a/bawei-base/base-es/base-es-common/src/main/java/com/bawei/es/domain/Page.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.bawei.es.domain; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * 分页实体类 - * - * @program: mall_cloud - * @ClassName: Page - * @author: Gyc - * @create: 2024-04-24 19:41 - **/ -@Data -@AllArgsConstructor -@NoArgsConstructor -public class Page { - private Integer pageNum=1; - private Integer pageSize=5; -} diff --git a/bawei-base/base-es/base-es-common/src/main/java/com/bawei/es/domain/Sort.java b/bawei-base/base-es/base-es-common/src/main/java/com/bawei/es/domain/Sort.java deleted file mode 100644 index 0f3e80e..0000000 --- a/bawei-base/base-es/base-es-common/src/main/java/com/bawei/es/domain/Sort.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.bawei.es.domain; - -import lombok.Data; - -/** - * @program: mall_cloud - * @ClassName: Sort - * @author: Gyc - * @create: 2024-04-24 20:28 - **/ -@Data -public class Sort { - private String sortName; - private String sortOrder; -} diff --git a/bawei-base/base-es/base-es-remote/pom.xml b/bawei-base/base-es/base-es-remote/pom.xml index e0f0827..86a47cf 100644 --- a/bawei-base/base-es/base-es-remote/pom.xml +++ b/bawei-base/base-es/base-es-remote/pom.xml @@ -2,12 +2,12 @@ - 4.0.0 - com.bawei base-es + com.bawei 3.6.0 + 4.0.0 base-es-remote @@ -17,4 +17,12 @@ UTF-8 + + + + + com.bawei + base-es-common + + diff --git a/bawei-base/base-es/base-es-remote/src/main/java/com/bawei/es/remote/api/RemoteDocumentService.java b/bawei-base/base-es/base-es-remote/src/main/java/com/bawei/es/remote/api/RemoteDocumentService.java new file mode 100644 index 0000000..1f53003 --- /dev/null +++ b/bawei-base/base-es/base-es-remote/src/main/java/com/bawei/es/remote/api/RemoteDocumentService.java @@ -0,0 +1,28 @@ +package com.bawei.es.remote.api; + +import com.bawei.common.core.constant.ServiceNameConstants; +import com.bawei.common.core.domain.R; +import com.bawei.es.remote.factory.RemoteDocumentFallbackFactory; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.Map; + +/** + * 文件服务 + * + * @author bawei + */ +@FeignClient(contextId = "remoteDocumentService", value = ServiceNameConstants.ES_SERVICE, fallbackFactory = RemoteDocumentFallbackFactory.class) +public interface RemoteDocumentService +{ + @PostMapping("/doc/{indexName}") + R queryList(@PathVariable String indexName, @RequestBody Map conditions); + + @PutMapping("/doc/{indexName}") + R batchDocument(@PathVariable String indexName, @RequestBody List dataJson); + + @DeleteMapping("/doc/{indexName}") + R batchDeleteDocument(@PathVariable String indexName, @RequestBody List dataJson); +} diff --git a/bawei-base/base-es/base-es-remote/src/main/java/com/bawei/es/remote/api/RemoteIndexService.java b/bawei-base/base-es/base-es-remote/src/main/java/com/bawei/es/remote/api/RemoteIndexService.java new file mode 100644 index 0000000..5493c1a --- /dev/null +++ b/bawei-base/base-es/base-es-remote/src/main/java/com/bawei/es/remote/api/RemoteIndexService.java @@ -0,0 +1,33 @@ +package com.bawei.es.remote.api; + +import com.bawei.common.core.constant.ServiceNameConstants; +import com.bawei.common.core.domain.R; +import com.bawei.es.remote.factory.RemoteIndexFallbackFactory; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.*; + +import java.util.Map; + +/** + * 文件服务 + * + * @author bawei + */ +@FeignClient(contextId = "remoteIndexService", value = ServiceNameConstants.ES_SERVICE, fallbackFactory = RemoteIndexFallbackFactory.class) +public interface RemoteIndexService +{ + @GetMapping("/index/{indexName}") + public R exist(@PathVariable String indexName); + + @GetMapping("/index/getMapping/{indexName}") + public R getMapping(@PathVariable String indexName); + + @PostMapping("/index/{indexName}") + public R index(@PathVariable String indexName,@RequestBody Map mappings); + + @PutMapping("/index/{indexName}") + public R updateIndex(@PathVariable String indexName,@RequestBody Map mappings); + + @DeleteMapping("/index/{indexName}") + public R deleteIndex(@PathVariable String indexName); +} diff --git a/bawei-base/base-es/base-es-remote/src/main/java/com/bawei/es/remote/factory/RemoteDocumentFallbackFactory.java b/bawei-base/base-es/base-es-remote/src/main/java/com/bawei/es/remote/factory/RemoteDocumentFallbackFactory.java new file mode 100644 index 0000000..396d471 --- /dev/null +++ b/bawei-base/base-es/base-es-remote/src/main/java/com/bawei/es/remote/factory/RemoteDocumentFallbackFactory.java @@ -0,0 +1,43 @@ +package com.bawei.es.remote.factory; + +import com.bawei.common.core.domain.R; +import com.bawei.es.remote.api.RemoteDocumentService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.cloud.openfeign.FallbackFactory; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.Map; + +/** + * 文件服务降级处理 + * + * @author bawei + */ +@Component +public class RemoteDocumentFallbackFactory implements FallbackFactory +{ + private static final Logger log = LoggerFactory.getLogger(RemoteDocumentFallbackFactory.class); + + + @Override + public RemoteDocumentService create(Throwable cause) { + return new RemoteDocumentService() { + @Override + public R queryList(String indexName, Map conditions) { + return R.fail(); + } + + @Override + public R batchDocument(String indexName, List dataJson) { + return R.fail(); + } + + @Override + public R batchDeleteDocument(String indexName, List dataJson) { + return R.fail(); + } + }; + } +} diff --git a/bawei-base/base-es/base-es-remote/src/main/java/com/bawei/es/remote/factory/RemoteIndexFallbackFactory.java b/bawei-base/base-es/base-es-remote/src/main/java/com/bawei/es/remote/factory/RemoteIndexFallbackFactory.java new file mode 100644 index 0000000..469cd1c --- /dev/null +++ b/bawei-base/base-es/base-es-remote/src/main/java/com/bawei/es/remote/factory/RemoteIndexFallbackFactory.java @@ -0,0 +1,52 @@ +package com.bawei.es.remote.factory; + +import com.bawei.common.core.domain.R; +import com.bawei.es.remote.api.RemoteIndexService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.cloud.openfeign.FallbackFactory; +import org.springframework.stereotype.Component; + +import java.util.Map; + +/** + * 文件服务降级处理 + * + * @author bawei + */ +@Component +public class RemoteIndexFallbackFactory implements FallbackFactory +{ + private static final Logger log = LoggerFactory.getLogger(RemoteIndexFallbackFactory.class); + + + @Override + public RemoteIndexService create(Throwable cause) { + return new RemoteIndexService() { + @Override + public R exist(String indexName) { + return R.fail(); + } + + @Override + public R getMapping(String indexName) { + return R.fail(); + } + + @Override + public R index(String indexName, Map mappings) { + return R.fail(); + } + + @Override + public R updateIndex(String indexName, Map mappings) { + return R.fail(); + } + + @Override + public R deleteIndex(String indexName) { + return R.fail(); + } + }; + } +} diff --git a/bawei-base/base-es/base-es-remote/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/bawei-base/base-es/base-es-remote/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports index 8b13789..e80fcff 100644 --- a/bawei-base/base-es/base-es-remote/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports +++ b/bawei-base/base-es/base-es-remote/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -1 +1,2 @@ - +com.bawei.es.remote.factory.RemoteIndexFallbackFactory +com.bawei.es.remote.factory.RemoteDocumentFallbackFactory diff --git a/bawei-base/base-es/base-es-server/pom.xml b/bawei-base/base-es/base-es-server/pom.xml index 2bf800a..479410e 100644 --- a/bawei-base/base-es/base-es-server/pom.xml +++ b/bawei-base/base-es/base-es-server/pom.xml @@ -2,12 +2,12 @@ - 4.0.0 - com.bawei base-es + com.bawei 3.6.0 + 4.0.0 base-es-server @@ -16,15 +16,54 @@ 8 UTF-8 + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-config + + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-sentinel + + + + + org.springframework.boot + spring-boot-starter-actuator + + + + + com.bawei + bawei-common-swagger + + com.bawei - base-es-common - 3.6.0 - compile + bawei-common-security + + org.elasticsearch.client + elasticsearch-rest-high-level-client + + + + + com.bawei + base-es-common + diff --git a/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/BaWeiEsApplication.java b/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/BaWeiEsApplication.java index 700ebd8..e00aed4 100644 --- a/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/BaWeiEsApplication.java +++ b/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/BaWeiEsApplication.java @@ -5,20 +5,13 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; -/** - * es服务 - * - * @program: mall_cloud - * @ClassName: BaWeiEsApplication - * @author: Gyc - * @create: 2024-04-22 20:39 - **/ @EnableCustomSwagger2 @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class }) public class BaWeiEsApplication { - public static void main(String[] args) - { + + public static void main(String[] args) { SpringApplication.run(BaWeiEsApplication.class, args); System.out.println("(♥◠‿◠)ノ゙ es服务模块启动成功 ლ(´ڡ`ლ)゙ "); } + } diff --git a/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/config/ElasticSearchConfig.java b/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/config/ElasticSearchConfig.java new file mode 100644 index 0000000..a4b8d51 --- /dev/null +++ b/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/config/ElasticSearchConfig.java @@ -0,0 +1,59 @@ +package com.bawei.es.config; + +import org.apache.http.HttpHost; +import org.elasticsearch.client.RestClient; +import org.elasticsearch.client.RestHighLevelClient; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * @Author: 31966 + * @Project: mall-product + * @Package: com.bwie.es.config + * @ClassName: ElasticSearchConfig + * @Description: 请在此处填写具体描述 + * @Date: 2024/4/22 20:50 + */ +@Configuration +public class ElasticSearchConfig { + + @Value("${es.host}") + private String host; + + @Value("${es.port}") + private int port; + + @Value("${es.scheme}") + private String scheme; + + @Bean + public RestHighLevelClient restHighLevelClient(){ + return new RestHighLevelClient( + RestClient.builder(new HttpHost(host, port, scheme))); + } + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public int getPort() { + return port; + } + + public void setPort(int port) { + this.port = port; + } + + public String getScheme() { + return scheme; + } + + public void setScheme(String scheme) { + this.scheme = scheme; + } +} diff --git a/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/controller/DocController.java b/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/controller/DocController.java deleted file mode 100644 index 82d642c..0000000 --- a/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/controller/DocController.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.bawei.es.controller; - -import com.bawei.common.core.domain.R; -import com.bawei.es.domain.DocumentClass; -import com.bawei.es.service.DocService; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.util.CollectionUtils; -import org.springframework.util.StringUtils; -import org.springframework.web.bind.annotation.*; - -import java.util.Map; - -@RestController("/doc") -@Api(value = "es文档操作",tags = "首页") -public class DocController { - - @Autowired - private DocService docService; - - @ApiOperation(value = "文档查询接口") - @PostMapping("/search") - public R search(@RequestBody DocumentClass documentClass) { - return R.ok(docService.search(documentClass)); - } - - - @ApiOperation(value = "增加es文档") - @PostMapping("/createDoc/{indexName}") - public R createDoc(@PathVariable String indexName, @RequestBody Map document){ - if (document!=null && !CollectionUtils.isEmpty(document)){ - return R.ok(docService.createDoc(indexName,document)); - } - throw new RuntimeException("添加失败,文档不可为空"); - } - - - @ApiOperation(value = "修改es文档") - @PutMapping("/putDoc/{indexName}") - public R putDoc(@PathVariable String indexName,@RequestBody Map document){ - if (document!=null && !CollectionUtils.isEmpty(document)){ - return R.ok(docService.putDoc(indexName,document)); - } - throw new RuntimeException("修改失败,文档不可为空"); - } - - - @ApiOperation(value = "删除es文档") - @DeleteMapping("/deleteDoc/{indexName}/{id}") - public R deleteDoc(@PathVariable String indexName, @PathVariable String id){ - if (id!=null){ - return R.ok(docService.deleteDoc(indexName,id)); - } - throw new RuntimeException("文档ID不能为空"); - } -} diff --git a/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/controller/DocumentController.java b/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/controller/DocumentController.java new file mode 100644 index 0000000..452878d --- /dev/null +++ b/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/controller/DocumentController.java @@ -0,0 +1,49 @@ +package com.bawei.es.controller; + +import com.bawei.common.core.domain.R; +import com.bawei.es.service.DocumentService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.web.bind.annotation.*; + +import javax.annotation.Resource; +import java.util.List; +import java.util.Map; + +/** + * @Author: 31966 + * @Project: mall-product + * @Package: com.bwie.es.controller + * @ClassName: DocumentController + * @Description: 请在此处填写具体描述 + * @Date: 2024/4/22 20:57 + */ +@RestController +@RequestMapping("/doc") +@Api(tags = "es文档接口") +public class DocumentController { + + @Resource(name = "documentServiceImpl") + private DocumentService documentService; + + @PostMapping("/{indexName}") + @ApiOperation(value = "条件查询文档数据") + public R queryList(@PathVariable String indexName, @RequestBody Map conditions){ + return documentService.queryList(indexName,conditions); + } + + @PutMapping("/{indexName}") + @ApiOperation(value = "批量操作数据") + public R batchDocument(@PathVariable String indexName, @RequestBody Map dataJson){ + documentService.batchOperation(indexName,dataJson); + return R.ok(null, "批量操作成功"); + } + + @DeleteMapping("/{indexName}") + @ApiOperation(value = "批量删除") + public R batchDeleteDocument(@PathVariable String indexName, @RequestBody List dataJson){ + documentService.batchDeletion(indexName,dataJson); + return R.ok(null, "批量删除成功"); + } + +} diff --git a/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/controller/IndexController.java b/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/controller/IndexController.java index c6f52f8..7fca60b 100644 --- a/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/controller/IndexController.java +++ b/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/controller/IndexController.java @@ -4,44 +4,55 @@ import com.bawei.common.core.domain.R; import com.bawei.es.service.IndexService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; +import javax.annotation.Resource; import java.util.Map; /** - * @author gyc + * @Author: 31966 + * @Project: mall-product + * @Package: com.bwie.es.controller + * @ClassName: IndexController + * @Description: 请在此处填写具体描述 + * @Date: 2024/4/22 20:45 */ -@RestController("/index") -@Api(value = "es索引操作",tags = "首页") +@RestController +@RequestMapping("/index") +@Api(tags = "es索引接口") public class IndexController { - @Autowired + + @Resource(name = "indexServiceImpl") private IndexService indexService; - @ApiOperation(value = "根据索引名称查询该索引是否存在") - @GetMapping("/index/{indexName}") - public R index(@PathVariable String indexName){ - return R.ok(indexService.exits(indexName)); + @GetMapping("/{indexName}") + @ApiOperation(value = "查询es索引是否存在") + public R exist(@PathVariable String indexName){ + return R.ok(indexService.exist(indexName),"es索引存在"); } - - @ApiOperation(value = "创建索引") - @PostMapping("/create/{indexName}") - public R create(@PathVariable String indexName, @RequestBody Map mappings){ - return R.ok(indexService.create(indexName,mappings)); + @GetMapping("/getMapping/{indexName}") + @ApiOperation(value = "获取索引映射") + public R getMapping(@PathVariable String indexName){ + return R.ok(indexService.getMapping(indexName),"索引映射存在"); } - - @ApiOperation(value = "更新索引") - @PutMapping("/update/{indexName}") - public R update(@PathVariable String indexName,@RequestBody Map mappings){ - return R.ok(indexService.update(indexName,mappings)); + @PostMapping("/{indexName}") + @ApiOperation(value = "添加索引") + public R index(@PathVariable String indexName,@RequestBody Map mappings){ + return R.ok(indexService.index(indexName,mappings),"es索引添加成功"); } + @PutMapping("/{indexName}") + @ApiOperation(value = "修改索引") + public R updateIndex(@PathVariable String indexName,@RequestBody Map mappings){ + return R.ok(indexService.updataIndex(indexName,mappings),"es索引修改成功"); + } + @DeleteMapping("/{indexName}") @ApiOperation(value = "删除索引") - @DeleteMapping("/delete/{indexName}") - public R delete(@PathVariable String indexName){ - return R.ok(indexService.delete(indexName)); + public R deleteIndex(@PathVariable String indexName){ + return R.ok(indexService.deleteIndex(indexName),"es索引删除成功"); } + } diff --git a/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/DocService.java b/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/DocService.java deleted file mode 100644 index a4eb7fb..0000000 --- a/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/DocService.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.bawei.es.service; - -import com.bawei.common.core.domain.R; -import com.bawei.es.domain.DocumentClass; - -import java.util.HashMap; -import java.util.Map; - -public interface DocService { - R getDocByIndexName(String indexName, String id); - - R createDoc(String indexName, Map document); - - R putDoc(String indexName, Map document); - - R deleteDoc(String indexName, String id); - - HashMap search(DocumentClass documentClass); -} diff --git a/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/DocumentService.java b/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/DocumentService.java new file mode 100644 index 0000000..a3dfeb3 --- /dev/null +++ b/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/DocumentService.java @@ -0,0 +1,22 @@ +package com.bawei.es.service; + +import com.bawei.common.core.domain.R; + +import java.util.List; +import java.util.Map; + +/** + * @Author: 31966 + * @Project: mall-product + * @Package: com.bwie.es.service + * @ClassName: DocumentService + * @Description: 请在此处填写具体描述 + * @Date: 2024/4/22 20:58 + */ +public interface DocumentService { + R queryList(String indexName, Map conditions); + + void batchOperation(String indexName, Map dataJson); + + void batchDeletion(String indexName, List dataJson); +} diff --git a/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/IndexService.java b/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/IndexService.java index b69d033..20026e5 100644 --- a/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/IndexService.java +++ b/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/IndexService.java @@ -1,15 +1,23 @@ package com.bawei.es.service; -import com.bawei.common.core.domain.R; - import java.util.Map; +/** + * @Author: 31966 + * @Project: mall-product + * @Package: com.bwie.es.service + * @ClassName: EsService + * @Description: 请在此处填写具体描述 + * @Date: 2024/4/22 20:56 + */ public interface IndexService { - Boolean exits(String indexName); + boolean exist(String indexName); - R create(String indexName, Map mappings); + boolean index(String indexName, Map mappings); - R update(String indexName, Map mappings); + boolean updataIndex(String indexName, Map mappings); - R delete(String indexName); + boolean deleteIndex(String indexName); + + Map getMapping(String indexName); } diff --git a/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/impl/DocServiceImpl.java b/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/impl/DocServiceImpl.java deleted file mode 100644 index 2e9bdd5..0000000 --- a/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/impl/DocServiceImpl.java +++ /dev/null @@ -1,181 +0,0 @@ -package com.bawei.es.service.impl; - -import com.bawei.common.core.domain.R; -import com.bawei.common.core.utils.StringUtils; -import com.bawei.es.domain.DocumentClass; -import com.bawei.es.service.DocService; -import org.elasticsearch.action.DocWriteResponse; -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.client.RequestOptions; -import org.elasticsearch.client.RestHighLevelClient; -import org.elasticsearch.index.query.BoolQueryBuilder; -import org.elasticsearch.index.query.QueryBuilder; -import org.elasticsearch.index.query.QueryBuilders; -import org.elasticsearch.search.SearchHit; -import org.elasticsearch.search.SearchHits; -import org.elasticsearch.search.builder.SearchSourceBuilder; -import org.elasticsearch.xcontent.XContentType; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.w3c.dom.ranges.RangeException; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; - -@Service -public class DocServiceImpl implements DocService { - - @Autowired - private IndexServiceImpl indexServiceImpl; - - @Autowired - private RestHighLevelClient restHighLevelClient; - - /** - *根据索引名称和文档ID查询该索引文档 - * @param indexName 索引名称 - * @param id 文档ID - * @return 查询结果 - */ - @Override - public R getDocByIndexName(String indexName, String id) { - //判断索引是否存在 - if(!indexServiceImpl.exits(indexName)){ - throw new RuntimeException("该索引不存在"); - } - - //构造获取文档请求 - GetRequest getRequest = new GetRequest(indexName, id); - - try { - GetResponse getResponse = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT); - - //判断文档是否存在 - if (getResponse.isExists()){ - //获取文档内容 - Map source = getResponse.getSource(); - - return R.ok(source); - }else { - throw new RuntimeException("该文档不存在"); - } - } catch (Exception e) { - throw new RuntimeException("获取文档异常,异常信息为: "+e.getMessage(),e); - } - } - - /** - * 增加es文档 - * @param indexName 索引名称 - * @param document 文档内容 - * @return 添加结果 - */ - @Override - public R createDoc(String indexName, Map document) { - if(!indexServiceImpl.exits(indexName)){ - throw new RuntimeException("该索引不存在"); - } - - //构建一个索引请求,并指定索引名称 - IndexRequest indexRequest = new IndexRequest(indexName); - indexRequest.source(document, XContentType.JSON); - - try { - IndexResponse indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT); - if (indexResponse.getResult()== DocWriteResponse.Result.CREATED || indexResponse.getResult() == DocWriteResponse.Result.UPDATED){ - return R.ok("文档添加成功"); - }else { - throw new RuntimeException("文档添加失败"); - } - } catch (Exception e) { - throw new RuntimeException("索引请求处理异常,异常信息为: "+e.getMessage(),e); - } - } - - /** - * 修改es文档 - * @param indexName 索引名称 - * @param document 文档内容 - * @return 修改结果 - */ - @Override - public R putDoc(String indexName, Map document) { - if(!indexServiceImpl.exits(indexName)){ - throw new RuntimeException("该索引不存在"); - } - - R r = this.putDoc(indexName, document); - if (r.isSuccess()){ - return R.ok("修改成功"); - } - - throw new RuntimeException("修改失败"); - } - - /** - * 删除es文档 - * @param indexName 索引名称 - * @param id 文档ID - * @return 删除结果 - */ - @Override - public R deleteDoc(String indexName, String id) { - if(!indexServiceImpl.exits(indexName)){ - throw new RuntimeException("该索引不存在"); - } - - //构造删除文档请求 - DeleteRequest deleteRequest = new DeleteRequest(indexName, id); - - try { - DeleteResponse deleteResponse = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT); - if (deleteResponse.getResult() == DocWriteResponse.Result.DELETED){ - return R.ok("删除成功"); - }else { - throw new RuntimeException("删除失败"); - } - } catch (Exception e) { - throw new RuntimeException("索引请求处理异常,异常信息为: "+e.getMessage(),e); - } - } - - @Override - public HashMap search(DocumentClass documentClass) { - if (StringUtils.isEmpty(documentClass.getIndexName())){ - throw new RuntimeException("索引名称不能为空"); - } - if (StringUtils.isEmpty(documentClass.getSort().getSortName())){ - throw new RuntimeException("索引字段不能为空"); - } - if (StringUtils.isEmpty(documentClass.getSort().getSortOrder())){ - throw new RuntimeException("排序字段不能为空"); - } - try { - SearchRequest searchRequest = new SearchRequest(documentClass.getIndexName()); - SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); - searchSourceBuilder.from((documentClass.getPage().getPageNum()-1)*documentClass.getPage().getPageSize()); - searchSourceBuilder.size(documentClass.getPage().getPageSize()); - searchSourceBuilder.sort(documentClass.getSort().getSortName()); - searchRequest.source(searchSourceBuilder); - SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT); - SearchHits hits = searchResponse.getHits(); - SearchHit[] hits1 = hits.getHits(); - Map map = new HashMap<>(); - for (SearchHit documentFields : hits1) { - map = documentFields.getSourceAsMap(); - } - } catch (IOException e) { - throw new RuntimeException("网络超时"); - } - return new HashMap<>(); - } -} diff --git a/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/impl/DocumentServiceImpl.java b/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/impl/DocumentServiceImpl.java new file mode 100644 index 0000000..4851072 --- /dev/null +++ b/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/impl/DocumentServiceImpl.java @@ -0,0 +1,320 @@ +package com.bawei.es.service.impl; + +import com.alibaba.fastjson2.JSONObject; +import com.bawei.common.core.domain.R; +import com.bawei.common.core.exception.ServiceException; +import com.bawei.common.core.utils.StringUtils; +import com.bawei.es.domain.CommonMap; +import com.bawei.es.service.DocumentService; +import org.elasticsearch.action.bulk.BulkRequest; +import org.elasticsearch.action.bulk.BulkResponse; +import org.elasticsearch.action.delete.DeleteRequest; +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.index.query.BoolQueryBuilder; +import org.elasticsearch.index.query.QueryBuilder; +import org.elasticsearch.index.query.QueryBuilders; +import org.elasticsearch.index.query.RangeQueryBuilder; +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.elasticsearch.search.sort.SortOrder; +import org.elasticsearch.xcontent.XContentType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; +import org.springframework.util.CollectionUtils; + +import javax.annotation.Resource; +import java.io.IOException; +import java.util.*; + +/** + * @Author: 31966 + * @Project: mall-product + * @Package: com.bwie.es.service.impl + * @ClassName: DocumentServiceImpl + * @Description: Elasticsearch 文档服务实现类 + * @Date: 2024/4/22 20:58 + */ +@Service +public class DocumentServiceImpl implements DocumentService { + + private static final Logger log = LoggerFactory.getLogger(DocumentServiceImpl.class); + + @Resource(name = "restHighLevelClient") + private RestHighLevelClient restHighLevelClient; + + @Override + public R queryList(String indexName, Map conditions) { + // 验证索引名 + validateIndexName(indexName); + + // 构建搜索请求 + SearchRequest searchRequest = buildSearchRequest(indexName, conditions); + + // 执行搜索 + SearchResponse searchResponse; + try { + searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT); + } catch (IOException e) { + log.error("Failed to execute search request", e); + return R.fail("Query failed: " + e.getMessage()); + } + + // 解析搜索结果 + CommonMap result = processSearchResponse(searchResponse); + + return R.ok(result); + } + + private SearchRequest buildSearchRequest(String indexName, Map conditions) { + SearchRequest searchRequest = new SearchRequest(indexName); + SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); + + // 构造查询条件 + QueryBuilder queryBuilder = buildQueryBuilder(conditions); + sourceBuilder.query(queryBuilder); + + // 设置分页参数 + setPaginationParameters(conditions, sourceBuilder); + + // 设置排序参数 + setSortParameters(conditions, sourceBuilder); + + // 设置高亮参数 + setHighlightParameters(conditions, sourceBuilder); + + searchRequest.source(sourceBuilder); + + // 记录搜索请求的详细信息(仅用于调试) + log.debug("ES search request DDL: {}", sourceBuilder.toString()); + + return searchRequest; + } + + @Override + public void batchOperation(String indexName, Map dataJson) { + BulkRequest bulkRequest = new BulkRequest(); + + // 根据dataJson中的key,进行批量操作 + for (Map.Entry entry : dataJson.entrySet()) { + String id = entry.getKey(); + Map document = (Map) entry.getValue(); + + // 示例代码仅处理索引(index)和删除(delete)操作 + IndexRequest indexRequest = new IndexRequest(indexName).id(id).source(document, XContentType.JSON); + bulkRequest.add(indexRequest); + } + + try { + BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT); + + // 检查批量操作结果,返回R对象 + if (bulkResponse.hasFailures()) { + throw new ServiceException("Bulk operation failed: " + bulkResponse.buildFailureMessage()); + } + } catch (IOException e) { + throw new ServiceException("批量操作失败: " + e.getMessage()); + } + } + + @Override + public void batchDeletion(String indexName, List ids) { + // 参数校验 + validateIndexName(indexName); + if (CollectionUtils.isEmpty(ids)) { + throw new IllegalArgumentException("请输入需要删除的文档ID集合"); + } + + BulkRequest bulkRequest = new BulkRequest(); + // 构建批量删除请求 + for (String id : ids) { + bulkRequest.add(new DeleteRequest(indexName, id)); + } + + try { + // 执行批量删除操作 + BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT); + // 检查批量删除结果 + if (bulkResponse.hasFailures()) { + throw new RuntimeException("批量删除失败: " + bulkResponse.buildFailureMessage()); + } + } catch (IOException e) { + throw new RuntimeException("执行批量删除操作时发生错误: " + e.getMessage(), e); + } + } + + /** + * 校验索引名称是否为空 + * @param indexName 索引名称 + */ + private void validateIndexName(String indexName) { + if (StringUtils.isBlank(indexName)) { + throw new ServiceException("索引名为空,请重试!"); + } + } + + private void setPaginationParameters(Map conditions, SearchSourceBuilder sourceBuilder) { + // 从条件中获取分页信息 + Map pagination = (Map) conditions.get("pagination"); + if (pagination == null) { + // 如果没有分页信息,则不设置分页参数 + return; + } + + // 校验并获取分页参数 + int page; + int limit; + try { + page = Integer.parseInt(pagination.getOrDefault("page", "1").toString()); + limit = Integer.parseInt(pagination.getOrDefault("limit", "10").toString()); + } catch (NumberFormatException e) { + // 如果分页参数不是整数,则抛出异常 + throw new IllegalArgumentException("Invalid pagination parameters: page and limit must be integers", e); + } + + // 设置分页参数 + int from = (page - 1) * limit; + sourceBuilder.from(from).size(limit); + + // 记录日志(可选,根据实际需求决定是否记录) + log.debug("Pagination parameters set: page={}, limit={}, from={}", page, limit, from); + } + + private void setSortParameters(Map conditions, SearchSourceBuilder sourceBuilder) { + Map sort = (Map) conditions.get("sort"); + if (sort != null) { + Object sortOrderObject = sort.get("sortOrder"); + Object fieldObject = sort.get("field"); + + if (sortOrderObject instanceof String && fieldObject instanceof String) { + String sortOrder = (String) sortOrderObject; + String field = (String) fieldObject; + + if ("asc".equalsIgnoreCase(sortOrder) || "desc".equalsIgnoreCase(sortOrder)) { + SortOrder sortOrderEnum = "asc".equalsIgnoreCase(sortOrder) ? SortOrder.ASC : SortOrder.DESC; + log.info("Applying sort: field={}, sortOrder={}", field, sortOrder); + sourceBuilder.sort(field, sortOrderEnum); + } else { + SortOrder sortOrderEnum = SortOrder.ASC; + log.info("Applying sort: field={}, sortOrder={}", field, sortOrder); + sourceBuilder.sort(field, sortOrderEnum); + } + } else { + throw new IllegalArgumentException("Invalid sort parameters. Both 'sortOrder' and 'field' must be strings."); + } + } + } + private void setHighlightParameters(Map conditions, SearchSourceBuilder sourceBuilder) { + Map highlightParams = (Map) conditions.get("highlight"); + if (highlightParams != null) { + HighlightBuilder highlightBuilder = new HighlightBuilder(); + List fieldNames = (List) highlightParams.getOrDefault("fields", Collections.emptyList()); + String preTag = (String) highlightParams.getOrDefault("preTag", ""); + String postTag = (String) highlightParams.getOrDefault("postTag", ""); + + for (String fieldName : fieldNames) { + highlightBuilder.field(fieldName); + } + + highlightBuilder.preTags(preTag); + highlightBuilder.postTags(postTag); + + sourceBuilder.highlighter(highlightBuilder); + } + } + + private CommonMap processSearchResponse(SearchResponse searchResponse) { + CommonMap result = new CommonMap(); + long totalHits = searchResponse.getHits().getTotalHits().value; + result.setTotal(totalHits); + + LinkedHashMap objectMap = new LinkedHashMap<>(); + for (SearchHit hit : searchResponse.getHits().getHits()) { + String sourceAsString = hit.getSourceAsString(); + HashMap parsedObject = JSONObject.parseObject(sourceAsString, HashMap.class); + String id = hit.getId(); + // 添加高亮信息到解析后的文档 + addHighlightedFields(hit.getHighlightFields(), parsedObject); + + objectMap.put(id, parsedObject); + log.info("查询出来的数据为:{}",JSONObject.toJSONString(parsedObject)); + } + log.info("查询出来的数据为:{}",JSONObject.toJSONString(objectMap)); + result.setObjectMap(objectMap); + + return result; + } + + private void addHighlightedFields(Map highlightFields, Map parsedObject) { + if (!highlightFields.isEmpty()) { + for (Map.Entry entry : highlightFields.entrySet()) { + String fieldName = entry.getKey(); + Text[] fragments = entry.getValue().fragments(); + StringBuilder highlightedValue = new StringBuilder(); + for (Text fragment : fragments) { + highlightedValue.append(fragment); + } + parsedObject.put(fieldName, highlightedValue); + } + } + } + + /** + * 根据条件构建Elasticsearch查询构建器 + * + * @param conditions 查询条件(键值对形式) + * @return Elasticsearch查询构建器 + */ + private QueryBuilder buildQueryBuilder(Map conditions) { + BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); + + if (conditions != null && !conditions.isEmpty()) { + for (Map.Entry entry : conditions.entrySet()) { + String field = entry.getKey(); + Object value = entry.getValue(); + + // 处理范围查询条件 + if (value instanceof Map && ((Map) value).containsKey("range")) { + Map rangeParams = (Map) value; + RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery(field); + + String gt = (String) rangeParams.get("gt"); + if (gt != null) { + rangeQueryBuilder.gt(gt); + } + + String gte = (String) rangeParams.get("gte"); + if (gte != null) { + rangeQueryBuilder.gte(gte); + } + + String lt = (String) rangeParams.get("lt"); + if (lt != null) { + rangeQueryBuilder.lt(lt); + } + + String lte = (String) rangeParams.get("lte"); + if (lte != null) { + rangeQueryBuilder.lte(lte); + } + + boolQueryBuilder.filter(rangeQueryBuilder); + } + // 处理其他查询条件(如 match 查询) + else if (value instanceof String) { + boolQueryBuilder.filter(QueryBuilders.matchQuery(field, value)); + } + } + } + + return boolQueryBuilder; + } + +} \ No newline at end of file diff --git a/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/impl/IndexServiceImpl.java b/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/impl/IndexServiceImpl.java index 3e332cf..5599053 100644 --- a/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/impl/IndexServiceImpl.java +++ b/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/impl/IndexServiceImpl.java @@ -1,127 +1,194 @@ package com.bawei.es.service.impl; -import com.bawei.common.core.domain.R; +import com.bawei.common.core.exception.ServiceException; import com.bawei.es.service.IndexService; import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; -import org.elasticsearch.action.support.master.AcknowledgedResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.client.indices.CreateIndexRequest; import org.elasticsearch.client.indices.CreateIndexResponse; import org.elasticsearch.client.indices.GetIndexRequest; +import org.elasticsearch.client.indices.GetIndexResponse; +import org.elasticsearch.cluster.metadata.MappingMetadata; +import org.elasticsearch.common.settings.Settings; import org.elasticsearch.xcontent.XContentBuilder; import org.elasticsearch.xcontent.XContentFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.io.IOException; import java.util.Map; +/** + * @Author: 31966 + * @Project: mall-product + * @Package: com.bwie.es.service.impl + * @ClassName: EsServiceImpl + * @Description: 请在此处填写具体描述 + * @Date: 2024/4/22 20:56 + */ @Service public class IndexServiceImpl implements IndexService { @Autowired private RestHighLevelClient restHighLevelClient; - /** - * 根据索引名称查询该索引是否存在 - * @param indexName 索引名称 - * @return 是/否 - */ @Override - public Boolean exits(String indexName) { - GetIndexRequest indexRequest = new GetIndexRequest(indexName); + public boolean exist(String indexName) { + if (indexName == null || indexName.isEmpty()){ + throw new ServiceException("索引名称不能为空"); + } try { - boolean exists = restHighLevelClient.indices().exists(indexRequest, RequestOptions.DEFAULT); - if (exists){ - return true; - }else { - throw new RuntimeException("该索引不存在"); + GetIndexRequest request = new GetIndexRequest(indexName); + GetIndexResponse response = restHighLevelClient.indices().get(request, RequestOptions.DEFAULT); + // 检查响应中是否包含指定的索引 + for (String index : response.getIndices()) { + if (index.equals(indexName)){ + return true; + } } } catch (Exception e) { - throw new RuntimeException("查找索引异常,异常信息为: "+e.getMessage(),e); + // 处理异常,例如记录日志或返回false表示索引不存在 + e.printStackTrace(); + } + return false; + } + + @Override + public boolean index(String indexName, Map mappings) { + // 参数校验 + if (indexName == null || indexName.isEmpty()) { + throw new ServiceException("Index name cannot be null or empty"); + } + // 判断索引是否存在 + boolean indexExists = exist(indexName); + if (indexExists) { + throw new ServiceException("索引 " + indexName + " 已存在"); + } + // 创建索引并设置映射(根据mappings非空情况) + try { + Settings.Builder settingsBuilder = Settings.builder(); + XContentBuilder mappingBuilder = null; + + if (mappings != null && !mappings.isEmpty()) { + // 设置映射 + mappingBuilder = createMapping(mappings); + } + + CreateIndexRequest request = new CreateIndexRequest(indexName) + .settings(settingsBuilder); + if (mappingBuilder!=null){ + request.mapping(mappingBuilder); + } + CreateIndexResponse response = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT); + return response.isAcknowledged(); + } catch (IOException e) { + System.err.println("创建索引时发生错误: " + e.getMessage()); + throw new ServiceException("创建索引时发生错误"); } } - /** - * 创建索引 - * @param indexName 索引名称 - * @param mappings 参数对象 - * @return 是/否 - */ @Override - public R create(String indexName, Map mappings) { - Boolean exits = this.exits(indexName); - if (exits){ - throw new RuntimeException("该索引已存在"); - } - CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName); - - // 将映射参数转换为 JSON 字符串并设置到索引请求中 + public boolean updataIndex(String indexName, Map mappings) { try { - XContentBuilder xContentBuilder = XContentFactory.jsonBuilder(); - xContentBuilder.map(mappings); - createIndexRequest.mapping(xContentBuilder); - } catch (Exception e) { - throw new RuntimeException("构建映射失败,失败原因: "+e.getMessage(),e); - } - - try { - CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT); - if (createIndexResponse.isAcknowledged()){ - return R.ok("创建成功"); + if (indexName!=null && !indexName.isEmpty()){ + if (Boolean.FALSE.equals(exist(indexName))) { + index(indexName,mappings); + return true; + }else { + deleteIndex(indexName); + index(indexName,mappings); + return true; + } }else { - throw new RuntimeException("创建索引失败"); + throw new ServiceException("索引名字为空,请重试!!!"); } } catch (Exception e) { - throw new RuntimeException("创建索引异常,异常信息为:"+e.getMessage(),e); + throw new RuntimeException(e); } } - /** - * 更新索引 - * @param indexName 索引名称 - * @param mappings 参数对象 - * @return - */ @Override - public R update(String indexName, Map mappings) { - Boolean exits = this.exits(indexName); - if (!exits){ - throw new RuntimeException("该索引不存在"); - } - - R delete = delete(indexName); - if (delete.isSuccess()){ - create(indexName,mappings); - return R.ok("更新成功"); - }else { - throw new RuntimeException("更新失败"); + public boolean deleteIndex(String indexName) { + // 删除索引 + try { + restHighLevelClient.indices().delete(new DeleteIndexRequest(indexName), RequestOptions.DEFAULT); + return true; + } catch (Exception e) { + System.err.println("Error deleting index: " + e.getMessage()); + throw new ServiceException("Error deleting index"); } } - /** - * 删除索引 - * @param indexName 索引名称 - * @return 是/否 - */ @Override - public R delete(String indexName) { - Boolean exits = this.exits(indexName); - if (!exits){ - throw new RuntimeException("该索引不存在"); + public Map getMapping(String indexName) { + if (indexName == null || indexName.isEmpty()) { + throw new ServiceException("索引名称不能为空"); } try { - DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(indexName); - AcknowledgedResponse delete = restHighLevelClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT); - if (delete.isAcknowledged()){ - return R.ok("删除成功"); - }else { - throw new RuntimeException("删除失败"); + GetIndexRequest request = new GetIndexRequest(indexName); + GetIndexResponse response = restHighLevelClient.indices().get(request, RequestOptions.DEFAULT); + + // 检查响应中是否包含指定的索引 + for (String index : response.getIndices()) { + if (index.equals(indexName)) { + Map mappings = response.getMappings(); + + // 提取并返回指定索引的映射结构 + MappingMetadata mappingMetadata = mappings.get(indexName); + if (mappingMetadata != null) { + Map map = (Map) mappingMetadata.getSourceAsMap().get("properties"); + if (map==null){ + throw new ServiceException("索引映射为空"); + } + return map; + } + } } } catch (Exception e) { - throw new RuntimeException("删除索引异常,异常信息为: "+e.getMessage(),e); + // 处理异常,例如记录日志 + e.printStackTrace(); } + + // 索引不存在或获取映射失败,返回null + throw new ServiceException("索引不存在,请重试"); } + /** + * 根据给定的映射创建XContentBuilder + */ + private XContentBuilder createMapping(Map mappings) throws IOException { + XContentBuilder builder = XContentFactory.jsonBuilder() + .startObject() + .startObject("properties"); + + for (Map.Entry entry : mappings.entrySet()) { + String fieldName = entry.getKey(); + Object fieldConfig = entry.getValue(); + + builder.startObject(fieldName); // Start field mapping + + if (fieldConfig instanceof Map) { + @SuppressWarnings("unchecked") + Map nestedMapping = (Map) fieldConfig; + + for (Map.Entry nestedEntry : nestedMapping.entrySet()) { + String nestedFieldName = nestedEntry.getKey(); + Object nestedFieldConfig = nestedEntry.getValue(); + + builder.field(nestedFieldName, nestedFieldConfig); + } + } else { + builder.field("type", fieldConfig.toString()); // Add field type + } + + builder.endObject(); // End field mapping + } + + builder.endObject() // End "properties" + .endObject(); // End root object + + return builder; + } } diff --git a/bawei-base/base-es/base-es-server/src/main/resources/bootstrap.yml b/bawei-base/base-es/base-es-server/src/main/resources/bootstrap.yml index 79ec75c..36c2ac4 100644 --- a/bawei-base/base-es/base-es-server/src/main/resources/bootstrap.yml +++ b/bawei-base/base-es/base-es-server/src/main/resources/bootstrap.yml @@ -1,6 +1,6 @@ # Tomcat server: - port: 9003 + port: 9204 # Spring spring: @@ -19,9 +19,9 @@ spring: config: # 配置中心地址 server-addr: 127.0.0.1:8848 - namespace: 12345678 # 配置文件格式 file-extension: yml # 共享配置 shared-configs: - application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension} + namespace: 12345678 diff --git a/bawei-base/base-file/base-file-remote/pom.xml b/bawei-base/base-file/base-file-remote/pom.xml index ba5312b..0d1823d 100644 --- a/bawei-base/base-file/base-file-remote/pom.xml +++ b/bawei-base/base-file/base-file-remote/pom.xml @@ -22,7 +22,8 @@ com.bawei - base-file-common + base-es-common + 3.6.0 diff --git a/bawei-base/base-file/base-file-remote/src/main/java/com/bawei/file/remote/api/RemoteFileService.java b/bawei-base/base-file/base-file-remote/src/main/java/com/bawei/file/remote/api/RemoteFileService.java index 78e1930..43429a0 100644 --- a/bawei-base/base-file/base-file-remote/src/main/java/com/bawei/file/remote/api/RemoteFileService.java +++ b/bawei-base/base-file/base-file-remote/src/main/java/com/bawei/file/remote/api/RemoteFileService.java @@ -1,6 +1,4 @@ package com.bawei.file.remote.api; - -import com.bawei.file.domain.SysFile; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PostMapping; @@ -24,6 +22,6 @@ public interface RemoteFileService * @param file 文件信息 * @return 结果 */ - @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) - public R upload(@RequestPart(value = "file") MultipartFile file); + @PostMapping(value = "/upload") + public R upload(); } diff --git a/bawei-common/bawei-common-core/src/main/java/com/bawei/common/core/constant/ServiceNameConstants.java b/bawei-common/bawei-common-core/src/main/java/com/bawei/common/core/constant/ServiceNameConstants.java index 09ead75..52a8546 100644 --- a/bawei-common/bawei-common-core/src/main/java/com/bawei/common/core/constant/ServiceNameConstants.java +++ b/bawei-common/bawei-common-core/src/main/java/com/bawei/common/core/constant/ServiceNameConstants.java @@ -22,6 +22,9 @@ public class ServiceNameConstants */ public static final String FILE_SERVICE = "bawei-file"; + + public static final String ES_SERVICE = "bawei-es"; + /** * 商品服务的serviceid */ diff --git a/pom.xml b/pom.xml index 7e60288..6646147 100644 --- a/pom.xml +++ b/pom.xml @@ -304,6 +304,12 @@ 3.6.0 + + com.bawei + base-es-common + 3.6.0 + + com.google.guava