diff --git a/pom.xml b/pom.xml index a0064742674cd153d2f103e75ba5ffc8c570aefd..8019c7b439fabe6811f2adcf40b50967c3ceac94 100644 --- a/pom.xml +++ b/pom.xml @@ -82,6 +82,12 @@ runtime + + com.alibaba + fastjson + 1.2.60 + + tk.mybatis diff --git a/src/main/java/com/hxtec/polaris/commons/es/ElasticsearchTemplate.java b/src/main/java/com/hxtec/polaris/commons/es/ElasticsearchTemplate.java new file mode 100644 index 0000000000000000000000000000000000000000..fca5096702c9c212fcf66d22551b94f4fb3c908e --- /dev/null +++ b/src/main/java/com/hxtec/polaris/commons/es/ElasticsearchTemplate.java @@ -0,0 +1,335 @@ +package com.hxtec.polaris.commons.es; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.hxtec.polaris.commons.utils.RestUtil; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; + +/** + * 关于 ElasticSearch 的一些方法(创建索引、添加数据、查询等) + * + * @author sunjianlei + */ +@Slf4j +@Component +public class ElasticsearchTemplate { + + @Value("${spring.elasticsearch.jest.uris}") + private String baseUrl; + + private final String FORMAT_JSON = "format=json"; + + public StringBuilder getBaseUrl(String indexName, String typeName) { + typeName = typeName.trim().toLowerCase(); + return this.getBaseUrl(indexName).append("/").append(typeName); + } + + public StringBuilder getBaseUrl(String indexName) { + indexName = indexName.trim().toLowerCase(); + return this.getBaseUrl().append("/").append(indexName); + } + + public StringBuilder getBaseUrl() { + return new StringBuilder(this.baseUrl); + } + + /** + * cat 查询ElasticSearch系统数据,返回json + */ + public ResponseEntity _cat(String urlAfter, Class responseType) { + String url = this.getBaseUrl().append("/_cat").append(urlAfter).append("?").append(FORMAT_JSON).toString(); + return RestUtil.request(url, HttpMethod.GET, null, null, null, responseType); + } + + /** + * 查询所有索引 + *

+ * 查询地址:GET http://{baseUrl}/_cat/indices + */ + public JSONArray getIndices() { + return getIndices(null); + } + + + /** + * 查询单个索引 + *

+ * 查询地址:GET http://{baseUrl}/_cat/indices/{indexName} + */ + public JSONArray getIndices(String indexName) { + StringBuilder urlAfter = new StringBuilder("/indices"); + if (!StringUtils.isEmpty(indexName)) { + urlAfter.append("/").append(indexName.trim().toLowerCase()); + } + return _cat(urlAfter.toString(), JSONArray.class).getBody(); + } + + /** + * 索引是否存在 + */ + public boolean indexExists(String indexName) { + try { + JSONArray array = getIndices(indexName); + return array != null; + } catch (org.springframework.web.client.HttpClientErrorException ex) { + if (HttpStatus.NOT_FOUND == ex.getStatusCode()) { + return false; + } else { + throw ex; + } + } + } + + /** + * 创建索引 + *

+ * 查询地址:PUT http://{baseUrl}/{indexName} + */ + public boolean createIndex(String indexName) { + String url = this.getBaseUrl(indexName).toString(); + + /* 返回结果 (仅供参考) + "createIndex": { + "shards_acknowledged": true, + "acknowledged": true, + "index": "hello_world" + } + */ + try { + return RestUtil.put(url).getBoolean("acknowledged"); + } catch (org.springframework.web.client.HttpClientErrorException ex) { + if (HttpStatus.BAD_REQUEST == ex.getStatusCode()) { + log.warn("索引创建失败:" + indexName + " 已存在,无需再创建"); + } else { + ex.printStackTrace(); + } + } + return false; + } + + /** + * 删除索引 + *

+ * 查询地址:DELETE http://{baseUrl}/{indexName} + */ + public boolean removeIndex(String indexName) { + String url = this.getBaseUrl(indexName).toString(); + try { + return RestUtil.delete(url).getBoolean("acknowledged"); + } catch (org.springframework.web.client.HttpClientErrorException ex) { + if (HttpStatus.NOT_FOUND == ex.getStatusCode()) { + log.warn("索引删除失败:" + indexName + " 不存在,无需删除"); + } else { + ex.printStackTrace(); + } + } + return false; + } + + /** + * 保存数据,详见:saveOrUpdate + */ + public boolean save(String indexName, String typeName, String dataId, JSONObject data) { + return this.saveOrUpdate(indexName, typeName, dataId, data); + } + + /** + * 更新数据,详见:saveOrUpdate + */ + public boolean update(String indexName, String typeName, String dataId, JSONObject data) { + return this.saveOrUpdate(indexName, typeName, dataId, data); + } + + /** + * 保存或修改索引数据 + *

+ * 查询地址:PUT http://{baseUrl}/{indexName}/{typeName}/{dataId} + * + * @param indexName 索引名称 + * @param typeName type,一个任意字符串,用于分类 + * @param dataId 数据id + * @param data 要存储的数据 + * @return + */ + public boolean saveOrUpdate(String indexName, String typeName, String dataId, JSONObject data) { + String url = this.getBaseUrl(indexName, typeName).append("/").append(dataId).toString(); + /* 返回结果(仅供参考) + "createIndexA2": { + "result": "created", + "_shards": { + "total": 2, + "successful": 1, + "failed": 0 + }, + "_seq_no": 0, + "_index": "test_index_1", + "_type": "test_type_1", + "_id": "a2", + "_version": 1, + "_primary_term": 1 + } + */ + + try { + // 去掉 data 中为空的值 + for (String key : data.keySet()) { + String value = data.getString(key); + if (StringUtils.isEmpty(value)) { + data.remove(key); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + + String result = RestUtil.put(url, data).getString("result"); + return "created".equals(result) || "updated".equals(result); + } + + /** + * 删除索引数据 + *

+ * 请求地址:DELETE http://{baseUrl}/{indexName}/{typeName}/{dataId} + */ + public boolean delete(String indexName, String typeName, String dataId) { + String url = this.getBaseUrl(indexName, typeName).append("/").append(dataId).toString(); + /* 返回结果(仅供参考) + { + "_index": "es_demo", + "_type": "docs", + "_id": "001", + "_version": 3, + "result": "deleted", + "_shards": { + "total": 1, + "successful": 1, + "failed": 0 + }, + "_seq_no": 28, + "_primary_term": 18 + } + */ + try { + return "deleted".equals(RestUtil.delete(url).getString("result")); + } catch (org.springframework.web.client.HttpClientErrorException ex) { + if (HttpStatus.NOT_FOUND == ex.getStatusCode()) { + return false; + } else { + throw ex; + } + } + } + + + /* = = = 以下关于查询和查询条件的方法 = = =*/ + + /** + * 查询数据 + *

+ * 请求地址:POST http://{baseUrl}/{indexName}/{typeName}/_search + */ + public JSONObject search(String indexName, String typeName, JSONObject queryObject) { + String url = this.getBaseUrl(indexName, typeName).append("/_search").toString(); + + log.info("search: " + queryObject.toJSONString()); + + return RestUtil.post(url, queryObject); + } + + /** + * @return { "query": query } + */ + public JSONObject buildQuery(JSONObject query) { + JSONObject json = new JSONObject(); + json.put("query", query); + return json; + } + + /** + * @return { "bool" : { "must": must, "must_not": mustNot, "should": should } } + */ + public JSONObject buildBoolQuery(JSONArray must, JSONArray mustNot, JSONArray should) { + JSONObject bool = new JSONObject(); + if (must != null) { + bool.put("must", must); + } + if (mustNot != null) { + bool.put("must_not", mustNot); + } + if (should != null) { + bool.put("should", should); + } + JSONObject json = new JSONObject(); + json.put("bool", bool); + return json; + } + + /** + * @param field 要查询的字段 + * @param args 查询参数,参考: *哈哈* OR *哒* NOT *呵* OR *啊* + * @return + */ + public JSONObject buildQueryString(String field, String... args) { + if (field == null) { + return null; + } + StringBuilder sb = new StringBuilder(field).append(":("); + if (args != null) { + for (String arg : args) { + sb.append(arg).append(" "); + } + } + sb.append(")"); + return this.buildQueryString(sb.toString()); + } + + /** + * @return { "query_string": { "query": query } } + */ + public JSONObject buildQueryString(String query) { + JSONObject queryString = new JSONObject(); + queryString.put("query", query); + JSONObject json = new JSONObject(); + json.put("query_string", queryString); + return json; + } + + /** + * @param field 查询字段 + * @param min 最小值 + * @param max 最大值 + * @param containMin 范围内是否包含最小值 + * @param containMax 范围内是否包含最大值 + * @return { "range" : { field : { 『 "gt『e』?containMin" : min 』?min!=null , 『 "lt『e』?containMax" : max 』}} } + */ + public JSONObject buildRangeQuery(String field, Object min, Object max, boolean containMin, boolean containMax) { + JSONObject inner = new JSONObject(); + if (min != null) { + if (containMin) { + inner.put("gte", min); + } else { + inner.put("gt", min); + } + } + if (max != null) { + if (containMax) { + inner.put("lte", max); + } else { + inner.put("lt", max); + } + } + JSONObject range = new JSONObject(); + range.put(field, inner); + JSONObject json = new JSONObject(); + json.put("range", range); + return json; + } + +} + diff --git a/src/main/java/com/hxtec/polaris/commons/utils/RestUtil.java b/src/main/java/com/hxtec/polaris/commons/utils/RestUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..c3d834435b41028921306518b698d0dd77fe2836 --- /dev/null +++ b/src/main/java/com/hxtec/polaris/commons/utils/RestUtil.java @@ -0,0 +1,213 @@ +package com.hxtec.polaris.commons.utils; + +import com.alibaba.fastjson.JSONObject; +import org.apache.commons.lang3.StringUtils; +import org.springframework.http.*; +import org.springframework.web.client.RestTemplate; + +import java.util.Iterator; +import java.util.Map; + +/** + * 调用 Restful 接口 Util + * + * @author sunjianlei + */ +public class RestUtil { + + /** + * RestAPI 调用器 + */ + private final static RestTemplate RT = new RestTemplate(); + + public static RestTemplate getRestTemplate() { + return RT; + } + + /** + * 发送 get 请求 + */ + public static JSONObject get(String url) { + return getNative(url, null, null).getBody(); + } + + /** + * 发送 get 请求 + */ + public static JSONObject get(String url, JSONObject variables) { + return getNative(url, variables, null).getBody(); + } + + /** + * 发送 get 请求 + */ + public static JSONObject get(String url, JSONObject variables, JSONObject params) { + return getNative(url, variables, params).getBody(); + } + + /** + * 发送 get 请求,返回原生 ResponseEntity 对象 + */ + public static ResponseEntity getNative(String url, JSONObject variables, JSONObject params) { + return request(url, HttpMethod.GET, variables, params); + } + + /** + * 发送 Post 请求 + */ + public static JSONObject post(String url) { + return postNative(url, null, null).getBody(); + } + + /** + * 发送 Post 请求 + */ + public static JSONObject post(String url, JSONObject params) { + return postNative(url, null, params).getBody(); + } + + /** + * 发送 Post 请求 + */ + public static JSONObject post(String url, JSONObject variables, JSONObject params) { + return postNative(url, variables, params).getBody(); + } + + /** + * 发送 POST 请求,返回原生 ResponseEntity 对象 + */ + public static ResponseEntity postNative(String url, JSONObject variables, JSONObject params) { + return request(url, HttpMethod.POST, variables, params); + } + + /** + * 发送 put 请求 + */ + public static JSONObject put(String url) { + return putNative(url, null, null).getBody(); + } + + /** + * 发送 put 请求 + */ + public static JSONObject put(String url, JSONObject params) { + return putNative(url, null, params).getBody(); + } + + /** + * 发送 put 请求 + */ + public static JSONObject put(String url, JSONObject variables, JSONObject params) { + return putNative(url, variables, params).getBody(); + } + + /** + * 发送 put 请求,返回原生 ResponseEntity 对象 + */ + public static ResponseEntity putNative(String url, JSONObject variables, JSONObject params) { + return request(url, HttpMethod.PUT, variables, params); + } + + /** + * 发送 delete 请求 + */ + public static JSONObject delete(String url) { + return deleteNative(url, null, null).getBody(); + } + + /** + * 发送 delete 请求 + */ + public static JSONObject delete(String url, JSONObject variables, JSONObject params) { + return deleteNative(url, variables, params).getBody(); + } + + /** + * 发送 delete 请求,返回原生 ResponseEntity 对象 + */ + public static ResponseEntity deleteNative(String url, JSONObject variables, JSONObject params) { + return request(url, HttpMethod.DELETE, null, variables, params, JSONObject.class); + } + + /** + * 发送请求 + */ + public static ResponseEntity request(String url, HttpMethod method, JSONObject variables, JSONObject params) { + return request(url, method, getHeaderApplicationJson(), variables, params, JSONObject.class); + } + + /** + * 发送请求 + * + * @param url 请求地址 + * @param method 请求方式 + * @param headers 请求头 可空 + * @param variables 请求url参数 可空 + * @param params 请求body参数 可空 + * @param responseType 返回类型 + * @return ResponseEntity + */ + public static ResponseEntity request(String url, HttpMethod method, HttpHeaders headers, JSONObject variables, JSONObject params, Class responseType) { + if (StringUtils.isEmpty(url)) { + throw new RuntimeException("url 不能为空"); + } + if (method == null) { + throw new RuntimeException("method 不能为空"); + } + if (headers == null) { + headers = new HttpHeaders(); + } + // 请求体 + String body = ""; + if (params != null) { + body = params.toJSONString(); + } + // 拼接 url 参数 + if (variables != null) { + url += ("?" + asUrlVariables(variables)); + } + // 发送请求 + HttpEntity request = new HttpEntity<>(body, headers); + return RT.exchange(url, method, request, responseType); + } + + /** + * 获取JSON请求头 + */ + private static HttpHeaders getHeaderApplicationJson() { + return getHeader(MediaType.APPLICATION_JSON_UTF8_VALUE); + } + + /** + * 获取请求头 + */ + private static HttpHeaders getHeader(String mediaType) { + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.parseMediaType(mediaType)); + headers.add("Accept", mediaType); + return headers; + } + + /** + * 将 JSONObject 转为 a=1&b=2&c=3...&n=n 的形式 + */ + public static String asUrlVariables(JSONObject variables) { + Map source = variables.getInnerMap(); + Iterator it = source.keySet().iterator(); + StringBuilder urlVariables = new StringBuilder(); + while (it.hasNext()) { + String key = it.next(); + String value = ""; + Object object = source.get(key); + if (object != null) { + if (!StringUtils.isEmpty(object.toString())) { + value = object.toString(); + } + } + urlVariables.append("&").append(key).append("=").append(value); + } + // 去掉第一个& + return urlVariables.substring(1); + } + +} diff --git a/src/main/java/com/hxtec/polaris/controller/ElkController.java b/src/main/java/com/hxtec/polaris/controller/ElkController.java new file mode 100644 index 0000000000000000000000000000000000000000..06869ff9f0a9327b8947448cd71f160601ccf803 --- /dev/null +++ b/src/main/java/com/hxtec/polaris/controller/ElkController.java @@ -0,0 +1,43 @@ +package com.hxtec.polaris.controller; + +import com.hxtec.polaris.commons.api.vo.Result; +import com.hxtec.polaris.service.SearchService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiImplicitParams; +import io.swagger.annotations.ApiOperation; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.annotation.Resource; + +@RestController +@RequestMapping("elk") +@Api(value = "/elk", tags = "elk") +public class ElkController { + + @Resource + private SearchService searchService; + + @GetMapping("executeSpuElkScyn") + @ApiOperation(value = "同步商品") + private Result executeSpuElkScyn(){ + return Result.ok(searchService.executeSpuElkScyn()); + } + + + @GetMapping("resetSpu") + @ApiOperation(value = "重置elk") + private Result resetSpu(){ + return Result.ok(searchService.resetSpu()); + } + + + @GetMapping("list") + @ApiOperation(value = "从elk获取spu列表") + private Result spuList(){ + return Result.ok(searchService.list()); + } + +} diff --git a/src/main/java/com/hxtec/polaris/controller/ProductController.java b/src/main/java/com/hxtec/polaris/controller/ProductController.java index baac317a287829a88eb0614394a5c76bfddd9307..269824b8b66df4b032b687ce3f6d3e14af88f29d 100644 --- a/src/main/java/com/hxtec/polaris/controller/ProductController.java +++ b/src/main/java/com/hxtec/polaris/controller/ProductController.java @@ -14,14 +14,7 @@ import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.CrossOrigin; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.*; import java.util.HashMap; import java.util.List; @@ -97,4 +90,5 @@ public class ProductController { skuService.saveSkuInfo(skuInfo); return Result.ok("success"); } + } diff --git a/src/main/java/com/hxtec/polaris/controller/ProductManageController.java b/src/main/java/com/hxtec/polaris/controller/ProductManageController.java index 911526640389631cb791fa4837800159a10e5b55..004f421f5b26fe015749c1f8108ea7faaecf7661 100644 --- a/src/main/java/com/hxtec/polaris/controller/ProductManageController.java +++ b/src/main/java/com/hxtec/polaris/controller/ProductManageController.java @@ -8,6 +8,8 @@ import com.hxtec.polaris.service.CategoryService; import com.hxtec.polaris.service.ProductBaseService; import com.hxtec.polaris.service.ProductService; import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.apache.commons.lang3.StringUtils; import org.springframework.web.bind.annotation.*; @@ -143,4 +145,13 @@ public class ProductManageController { return Result.ok(spuList); } + @GetMapping ("getSkuListBySpuId/{spuId}") + @ApiOperation(value="获取spu下的sku列表", notes="获取spu下的sku列表") + @ApiImplicitParams({ + @ApiImplicitParam(name = "spu", value = "商品的spu", required = true, dataType = "String"), + }) + public Result getSkuList(@PathVariable int spuId){ + return Result.ok(skuService.getSkuBySkuId(spuId)); + } + } diff --git a/src/main/java/com/hxtec/polaris/service/ProductService.java b/src/main/java/com/hxtec/polaris/service/ProductService.java index fe07f1835e8d4d718a39986bf16a6cb7d32c548b..2408eac707fcc2c1500d4e8ad2d315b0cb615541 100644 --- a/src/main/java/com/hxtec/polaris/service/ProductService.java +++ b/src/main/java/com/hxtec/polaris/service/ProductService.java @@ -27,4 +27,6 @@ public interface ProductService { void saveSkuInfo(ShopProductVariant skuInfo); + List getSkuBySkuId(Integer spuId); + } diff --git a/src/main/java/com/hxtec/polaris/service/SearchService.java b/src/main/java/com/hxtec/polaris/service/SearchService.java index bcfe645f8aae7351448248550521b3c771028462..56d1f5ff37d93a8ad4549be6f2f20b9963460cb9 100644 --- a/src/main/java/com/hxtec/polaris/service/SearchService.java +++ b/src/main/java/com/hxtec/polaris/service/SearchService.java @@ -1,18 +1,18 @@ -/* package com.hxtec.polaris.service; -import com.hxtec.polaris.commons.dto.PmsSearchParam; -import com.hxtec.polaris.commons.dto.PmsSearchSkuInfo; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; -import java.util.List; - -*/ /** - * @author Caps - * @date 2019/12/5 - *//* - + * caps + * + */ public interface SearchService { - List list(PmsSearchParam pmsSearchParam); + JSONObject list(); + + Integer executeSpuElkScyn(); + + boolean resetSpu(); + + } -*/ diff --git a/src/main/java/com/hxtec/polaris/service/impl/ProductServiceImpl.java b/src/main/java/com/hxtec/polaris/service/impl/ProductServiceImpl.java index 0361460e89326d9ffb1f482aaa98fac2badc668e..71ee9bc823db599ae96fab573fb9981dbfd9cd3e 100644 --- a/src/main/java/com/hxtec/polaris/service/impl/ProductServiceImpl.java +++ b/src/main/java/com/hxtec/polaris/service/impl/ProductServiceImpl.java @@ -125,4 +125,11 @@ public class ProductServiceImpl implements ProductService { }); } + + @Override + public List getSkuBySkuId(Integer spuId) { + ShopProductVariant sku=new ShopProductVariant(); + sku.setSpu(spuId); + return skuMapper.select(sku); + } } diff --git a/src/main/java/com/hxtec/polaris/service/impl/SearchServiceImpl.java b/src/main/java/com/hxtec/polaris/service/impl/SearchServiceImpl.java index e0600903246c673d4ed287e270a9a214e2e86b07..6258c2315168e63a80a1828ac40a48afdaec8163 100644 --- a/src/main/java/com/hxtec/polaris/service/impl/SearchServiceImpl.java +++ b/src/main/java/com/hxtec/polaris/service/impl/SearchServiceImpl.java @@ -1,8 +1,10 @@ -/* package com.hxtec.polaris.service.impl; +import com.alibaba.fastjson.JSONObject; import com.hxtec.polaris.commons.dto.PmsSearchParam; -import com.hxtec.polaris.commons.dto.PmsSearchSkuInfo; +import com.hxtec.polaris.commons.dto.PmsSearchSpuInfo; +import com.hxtec.polaris.commons.es.ElasticsearchTemplate; +import com.hxtec.polaris.mapper.ShopProductBaseMapper; import com.hxtec.polaris.service.SearchService; import io.searchbox.client.JestClient; import io.searchbox.core.Search; @@ -17,103 +19,69 @@ import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder; import org.elasticsearch.search.sort.SortOrder; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import javax.annotation.Resource; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; - +@Service public class SearchServiceImpl implements SearchService { - @Autowired - private JestClient jestClient; + private final JestClient jestClient; - @Override - public List list(PmsSearchParam pmsSearchParam) { - String dslStr = getSearchDsl(pmsSearchParam); - System.err.println(dslStr); - // 用api执行复杂查询 - List pmsSearchSkuInfos = new ArrayList<>(); - Search search = new Search.Builder(dslStr).addIndex("hxtec").addType("PmsSkuInfo").build(); - SearchResult execute = null; - try { - execute = jestClient.execute(search); - } catch (IOException e) { - e.printStackTrace(); - } - List> hits = execute.getHits(PmsSearchSkuInfo.class); - for (SearchResult.Hit hit : hits) { - PmsSearchSkuInfo source = hit.source; - - Map> highlight = hit.highlight; - if(highlight!=null){ - String skuName = highlight.get("skuName").get(0); - source.setSkuName(skuName); - } - pmsSearchSkuInfos.add(source); - } + private final ShopProductBaseMapper spuMapper; - System.out.println(pmsSearchSkuInfos.size()); - return pmsSearchSkuInfos; - } + private final ElasticsearchTemplate elasticsearchTemplate; - private String getSearchDsl(PmsSearchParam pmsSearchParam) { - - String[] skuAttrValueList = pmsSearchParam.getValueId(); - String keyword = pmsSearchParam.getKeyword(); - String catalog3Id = pmsSearchParam.getCatalogId(); + public SearchServiceImpl(JestClient jestClient, ShopProductBaseMapper spuMapper, ElasticsearchTemplate elasticsearchTemplate) { + this.jestClient = jestClient; + this.spuMapper = spuMapper; + this.elasticsearchTemplate = elasticsearchTemplate; + } - // jest的dsl工具 - SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); - // bool - BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder(); - // filter - if(StringUtils.isNotBlank(catalog3Id)){ - TermQueryBuilder termQueryBuilder = new TermQueryBuilder("catalog3Id",catalog3Id); - boolQueryBuilder.filter(termQueryBuilder); - } - if(skuAttrValueList!=null){ - for (String pmsSkuAttrValue : skuAttrValueList) { - TermQueryBuilder termQueryBuilder = new TermQueryBuilder("skuAttrValueList.valueId",pmsSkuAttrValue); - boolQueryBuilder.filter(termQueryBuilder); + @Override + public Integer executeSpuElkScyn(){ + List spuList = spuMapper.getSpuInfo(); + List list=new ArrayList(); + spuList.forEach(spu->{ + boolean isSuccess = elasticsearchTemplate.save("hxtec", "spuList", spu.getSpu(), JSONObject.parseObject(JSONObject.toJSON(spu).toString())); + if(isSuccess){ + list.add("success"); } - } - - // must - if(StringUtils.isNotBlank(keyword)){ - MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("skuName",keyword); - boolQueryBuilder.must(matchQueryBuilder); - } - - // query - searchSourceBuilder.query(boolQueryBuilder); + }); + return list.size(); + } - // highlight - HighlightBuilder highlightBuilder = new HighlightBuilder(); - highlightBuilder.preTags(""); - highlightBuilder.field("skuName"); - highlightBuilder.postTags(""); - searchSourceBuilder.highlighter(highlightBuilder); - // sort - searchSourceBuilder.sort("id", SortOrder.DESC); - // from - searchSourceBuilder.from(0); - // size - searchSourceBuilder.size(20); + @Override + public boolean resetSpu(){ + List spuInfoList = spuMapper.getSpuInfo(); + List list=new ArrayList(); + spuInfoList.forEach(spu->{ + boolean isSuccess = elasticsearchTemplate.delete("hxtec", "spuList", spu.getSpu()); + if (isSuccess){ + list.add("success"); + } + }); + if (list.size() == spuInfoList.size()){ + return true; + } + return false; + } - // aggs - TermsAggregationBuilder groupby_attr = AggregationBuilders.terms("groupby_attr").field("skuAttrValueList.valueId"); - searchSourceBuilder.aggregation(groupby_attr); + @Override + public JSONObject list() { + JSONObject jsonObject = elasticsearchTemplate.buildQueryString("skuName", "女"); + return elasticsearchTemplate.search("hxtec","spuList",jsonObject); + } - return searchSourceBuilder.toString(); - } } -*/ diff --git a/src/test/java/com/hxtec/polaris/com/hxtec/polaris/service/elasticSearchTest.java b/src/test/java/com/hxtec/polaris/com/hxtec/polaris/service/elasticSearchTest.java index ba96c8e78ef39f3285b51964c164c1d0199d39fe..67753ce504d5ecea49c6f51320f1df30aa7cd164 100644 --- a/src/test/java/com/hxtec/polaris/com/hxtec/polaris/service/elasticSearchTest.java +++ b/src/test/java/com/hxtec/polaris/com/hxtec/polaris/service/elasticSearchTest.java @@ -1,26 +1,20 @@ package com.hxtec.polaris.com.hxtec.polaris.service; import com.hxtec.polaris.commons.dto.PmsSearchSpuInfo; -import com.hxtec.polaris.entity.ShopProductBase; -import com.hxtec.polaris.entity.ShopProductVariant; import com.hxtec.polaris.mapper.ShopProductBaseMapper; -import com.hxtec.polaris.mapper.ShopProductVariantMapper; import io.searchbox.client.JestClient; import io.searchbox.core.Index; import io.searchbox.core.Search; import io.searchbox.core.SearchResult; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.MatchQueryBuilder; -import org.elasticsearch.index.query.TermQueryBuilder; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.junit.jupiter.api.Test; import org.junit.runner.RunWith; -import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; -import javax.annotation.Resource; import java.io.IOException; import java.util.ArrayList; import java.util.List; @@ -49,8 +43,8 @@ public class elasticSearchTest { // 导入es - for (PmsSearchSpuInfo pmsSearchSkuInfo : pmsSpuInfoList) { - Index put = new Index.Builder(pmsSearchSkuInfo).index("hxtec").type("PmsSkuInfo").id(pmsSearchSkuInfo.getSpu()+"").build(); + for (PmsSearchSpuInfo pmsSearchSpuInfo : pmsSpuInfoList) { + Index put = new Index.Builder(pmsSearchSpuInfo).index("hxtec").type("PmsSpuList").id(pmsSearchSpuInfo.getSpu()+"").build(); jestClient.execute(put); } @@ -58,7 +52,7 @@ public class elasticSearchTest { - /* @Test + @Test public void get() throws IOException { // jest的dsl工具 @@ -66,26 +60,20 @@ public class elasticSearchTest { // bool BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder(); // must - MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("spu","女"); + MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("skuName","女"); boolQueryBuilder.must(matchQueryBuilder); // query searchSourceBuilder.query(boolQueryBuilder); - // from - searchSourceBuilder.from(0); - // size - searchSourceBuilder.size(20); - // highlight - searchSourceBuilder.highlighter(null); String dslStr = searchSourceBuilder.toString(); - System.err.println(dslStr); + System.out.println(dslStr); // 用api执行复杂查询 List pmsSearchSkuInfos = new ArrayList<>(); - Search search = new Search.Builder(dslStr).addIndex("hxtec").addType("PmsSkuInfo").build(); + Search search = new Search.Builder(dslStr).addIndex("hxtec").addType("PmsSpuList").build(); SearchResult execute = jestClient.execute(search); @@ -97,6 +85,6 @@ public class elasticSearchTest { pmsSearchSkuInfos.add(source); } - System.out.println(pmsSearchSkuInfos.size()); - }*/ + System.out.println(pmsSearchSkuInfos.toString()); + } }