feat(商城): 添加elasticsearch

master
wayn 4 years ago
parent 605a86ac22
commit 95e15ee4ef

@ -52,7 +52,6 @@
<version>7.4.2</version>
</dependency>
<dependency>
<groupId>com.wayn</groupId>
<artifactId>waynboot-common</artifactId>

@ -3,15 +3,16 @@ package com.wayn.admin.api.controller.shop;
import com.wayn.admin.framework.manager.elastic.service.BaseElasticService;
import com.wayn.common.base.ElasticEntity;
import com.wayn.common.core.domain.shop.Goods;
import com.wayn.common.core.service.shop.IGoodsService;
import com.wayn.common.util.R;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ -23,24 +24,32 @@ public class ElasticController {
@Autowired
private BaseElasticService baseElasticService;
@Autowired
private IGoodsService iGoodsService;
@GetMapping("insert")
public R insert() {
ElasticEntity elasticEntity = new ElasticEntity();
elasticEntity.setId("2");
Map<String, Object> map = new HashMap<>();
map.put("name", "书本2");
map.put("price", 1000D);
map.put("date", new Date());
elasticEntity.setData(map);
baseElasticService.insertOrUpdateOne("store", elasticEntity);
List<Goods> list = iGoodsService.list();
List<ElasticEntity> entities = new ArrayList<>();
for (Goods goods : list) {
ElasticEntity elasticEntity = new ElasticEntity();
Map<String, Object> map = new HashMap<>();
elasticEntity.setId(goods.getId().toString());
map.put("name", goods.getName());
map.put("keyword", goods.getKeywords());
map.put("isOnSale", goods.getIsOnSale());
elasticEntity.setData(map);
entities.add(elasticEntity);
}
baseElasticService.insertBatch("goods", entities);
return R.success();
}
@GetMapping("search")
public R search() {
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchQuery("name", "沃尔玛"));
List<Object> list = baseElasticService.search("store", searchSourceBuilder, Object.class);
// searchSourceBuilder.query(QueryBuilders.matchQuery("name", "沃尔玛"));
List<Object> list = baseElasticService.search("goods", searchSourceBuilder, Object.class);
return R.success().add("data", list);
}
}

@ -26,6 +26,32 @@
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.4.2</version>
<exclusions>
<exclusion>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
</exclusion>
<exclusion>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.4.2</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>7.4.2</version>
</dependency>
<dependency>
<groupId>com.wayn</groupId>
<artifactId>waynboot-common</artifactId>

@ -1,6 +1,7 @@
package com.wayn.mobile.api.controller;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wayn.common.base.BaseController;
import com.wayn.common.core.domain.shop.Goods;
@ -9,8 +10,11 @@ import com.wayn.common.core.service.shop.IGoodsService;
import com.wayn.common.util.R;
import com.wayn.mobile.api.domain.SearchHistory;
import com.wayn.mobile.api.service.ISearchHistoryService;
import com.wayn.mobile.framework.manager.service.BaseElasticService;
import com.wayn.mobile.framework.security.util.SecurityUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@ -37,13 +41,16 @@ public class SearchController extends BaseController {
@Autowired
private ISearchHistoryService iSearchHistoryService;
@Autowired
private BaseElasticService baseElasticService;
@GetMapping("result")
public R list(SearchVO searchVO) {
Long memberId = SecurityUtils.getUserId();
String keyword = searchVO.getKeyword();
Integer categoryId = searchVO.getCategoryId();
Boolean isHot = searchVO.getIsHot();
Boolean isNew = searchVO.getIsNew();
// Integer categoryId = searchVO.getCategoryId();
// Boolean isHot = searchVO.getIsHot();
// Boolean isNew = searchVO.getIsNew();
if (memberId != null && StringUtils.isNotEmpty(keyword)) {
SearchHistory searchHistory = new SearchHistory();
searchHistory.setCreateTime(LocalDateTime.now());
@ -51,6 +58,18 @@ public class SearchController extends BaseController {
searchHistory.setKeyword(keyword);
iSearchHistoryService.save(searchHistory);
}
// matchQuery
MatchQueryBuilder matchQuery = QueryBuilders.matchQuery(keyword, "name").analyzer("standard");
// TermQuery
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("keyword", keyword);
// 布尔查询
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.should(matchQuery);
boolQueryBuilder.should(termQueryBuilder);
// 设置布尔查询对象
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(boolQueryBuilder);
List<JSONObject> objectList = baseElasticService.search("goods", searchSourceBuilder, JSONObject.class);
Page<SearchVO> page = getPage();
List<Goods> goods = iGoodsService.searchResult(page, searchVO);
return R.success().add("goods", goods);

@ -0,0 +1,39 @@
package com.wayn.mobile.framework.config;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ElasticConfig {
@Value("${es.host}")
public String host;
@Value("${es.port}")
public int port;
@Value("${es.scheme}")
public String scheme;
@Bean
public RestClientBuilder restClientBuilder() {
return RestClient.builder(makeHttpHost());
}
@Bean
public RestClient elasticsearchRestClient() {
return RestClient.builder(new HttpHost(host, port, scheme)).build();
}
private HttpHost makeHttpHost() {
return new HttpHost(host, port, scheme);
}
@Bean
public RestHighLevelClient restHighLevelClient(@Autowired RestClientBuilder restClientBuilder) {
return new RestHighLevelClient(restClientBuilder);
}
}

@ -0,0 +1,210 @@
package com.wayn.mobile.framework.manager.service;
import com.alibaba.fastjson.JSON;
import com.wayn.common.base.ElasticEntity;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
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.action.support.IndicesOptions;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@Slf4j
@Component
public class BaseElasticService {
@Autowired
RestHighLevelClient restHighLevelClient;
/**
*
*
* @param idxName
* @param idxSQL
*/
public void createIndex(String idxName, String idxSQL) {
try {
if (this.indexExist(idxName)) {
log.error(" idxName={} 已经存在,idxSql={}", idxName, idxSQL);
return;
}
CreateIndexRequest request = new CreateIndexRequest(idxName);
buildSetting(request);
request.mapping(idxSQL, XContentType.JSON);
// request.settings() 手工指定Setting
CreateIndexResponse res = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
if (!res.isAcknowledged()) {
throw new RuntimeException("初始化失败");
}
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
}
/**
* index
*
* @param idxName
* @return boolean
* @throws Exception
*/
public boolean indexExist(String idxName) throws Exception {
GetIndexRequest request = new GetIndexRequest(idxName);
request.local(false);
request.humanReadable(true);
request.includeDefaults(false);
request.indicesOptions(IndicesOptions.lenientExpandOpen());
return !restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
}
/**
* index
*
* @param idxName index
* @return boolean
*/
public boolean isExistsIndex(String idxName) throws Exception {
return restHighLevelClient.indices().exists(new GetIndexRequest(idxName), RequestOptions.DEFAULT);
}
/**
*
*
* @param request
*/
public void buildSetting(CreateIndexRequest request) {
request.settings(Settings.builder().put("index.number_of_shards", 3)
.put("index.number_of_replicas", 2));
}
/**
* @param idxName index
* @param entity
*/
public void insertOrUpdateOne(String idxName, ElasticEntity entity) {
IndexRequest request = new IndexRequest(idxName);
log.error("Data : id={},entity={}", entity.getId(), JSON.toJSONString(entity.getData()));
request.id(entity.getId());
request.source(entity.getData(), XContentType.JSON);
// request.source(JSON.toJSONString(entity.getData()), XContentType.JSON);
try {
restHighLevelClient.index(request, RequestOptions.DEFAULT);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
*
*
* @param idxName index
* @param list
*/
public void insertBatch(String idxName, List<ElasticEntity> list) {
BulkRequest request = new BulkRequest();
list.forEach(item -> request.add(new IndexRequest(idxName).id(item.getId())
.source(item.getData(), XContentType.JSON)));
try {
restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
*
*
* @param idxName index
* @param idList
*/
public <T> void deleteBatch(String idxName, Collection<T> idList) {
BulkRequest request = new BulkRequest();
idList.forEach(item -> request.add(new DeleteRequest(idxName, item.toString())));
try {
restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* @param idxName index
* @param builder
* @param c
* @return java.util.List<T>
*/
public <T> List<T> search(String idxName, SearchSourceBuilder builder, Class<T> c) {
SearchRequest request = new SearchRequest(idxName);
request.source(builder);
try {
SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
SearchHit[] hits = response.getHits().getHits();
List<T> res = new ArrayList<>(hits.length);
for (SearchHit hit : hits) {
res.add(JSON.parseObject(hit.getSourceAsString(), c));
}
return res;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* index
*
* @param idxName
*/
public void deleteIndex(String idxName) {
try {
if (this.indexExist(idxName)) {
log.error(" idxName={} 已经存在", idxName);
return;
}
restHighLevelClient.indices().delete(new DeleteIndexRequest(idxName), RequestOptions.DEFAULT);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
*
*
* @param idxName
* @param builder
*/
public void deleteByQuery(String idxName, QueryBuilder builder) {
DeleteByQueryRequest request = new DeleteByQueryRequest(idxName);
request.setQuery(builder);
//设置批量操作数量,最大为10000
request.setBatchSize(10000);
request.setConflicts("proceed");
try {
restHighLevelClient.deleteByQuery(request, RequestOptions.DEFAULT);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
Loading…
Cancel
Save