pom:
<properties><elasticsearch.version>5.4.1</elasticsearch.version><transport.version>5.4.1</transport.version></properties><!--elasticsearch相关依赖--><dependency><groupId>org.elasticsearch</groupId><artifactId>elasticsearch</artifactId><version>${elasticsearch.version}</version></dependency><dependency><groupId>org.elasticsearch.client</groupId><artifactId>transport</artifactId><version>${transport.version}</version></dependency><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-core</artifactId><version>2.7</version></dependency></dependencies>
复制代码
config:
@Configuration
public class ElasticsearchConfig {@Beanpublic TransportClient transportClient() throws UnknownHostException {// 一定要注意,9300为elasticsearch的tcp端口InetSocketTransportAddress master = new InetSocketTransportAddress(InetAddress.getByName("47.104.160.160"), 9300);// 集群名称Settings settings = Settings.builder().put("cluster.name", "es-cluster").build();TransportClient client = new PreBuiltTransportClient(settings);// 添加client.addTransportAddresses(master);return client;}
}
复制代码
utils:
@Component
public class ElasticsearchUtils {private static final Logger LOGGER = LoggerFactory.getLogger(ElasticsearchUtils.class);@Autowiredprivate TransportClient transportClient;private static TransportClient client;@PostConstructpublic void init() {client = this.transportClient;}public static void searchModel(Integer pageNo, Integer pageSize) throws Exception {SearchResponse searchResponse = client.prepareSearch(EsConstants.INDEX)//指定索引库.setTypes(EsConstants.TYPE)//指定类型// .setQuery(QueryBuilders.matchQuery("name", "tom"))//指定查询条件,这里不支持通配符 * ?.setQuery(QueryBuilders.matchAllQuery())//查询所有.setQuery(QueryBuilders.multiMatchQuery("tom", "name", "title"))//支持一个值同时匹配多个字段.setQuery(QueryBuilders.queryStringQuery("name:to?"))//支持lucene的语法 AND OR,通配符 * ? 如果对lucene比较熟悉,或者是想用通配符,可以使用这个.setQuery(QueryBuilders.boolQuery().must(QueryBuilders.matchQuery("name", "tom")).mustNot(QueryBuilders.matchQuery("age", 16)))//组合查询,支持多个查询条件,并且可以给查询条件设置权重.setQuery(QueryBuilders.boolQuery().should(QueryBuilders.matchQuery("name", "zs").boost(8.0f)).should(QueryBuilders.matchQuery("age", 19).boost(1.0f)))//组合查询,支持多个查询条件,并且可以给查询条件设置权重.setQuery(QueryBuilders.termQuery("name", "tom zhang"))//精确查询 主要针对人名 还有地名//注意:一般需要精确查询的字段,在存储的时候都不建议分词。但是已经分词了,还想精确精确查询,使用queryStringQuery,在需要精确查询的词语外面使用双引号引起来.setQuery(QueryBuilders.queryStringQuery("name:\"tom zhang\"")).setQuery(QueryBuilders.matchQuery("name", "tom zhang").operator(Operator.AND))//AND的意思是 返回的数据中必须包含 你好 和 中国这两个词 OR的意思是只包含一个词即可/*** lt:小于* lte:小于等于* gt:大于* gte:大于等于*///过滤,默认是闭区间// .setPostFilter(QueryBuilders.rangeQuery("age").from(18).to(19).includeLower(true).includeUpper(true))// 10=<x<=20这个过滤条件可以缓存,多次查询效率高// .setPostFilter(QueryBuilders.rangeQuery("age").gte(18).lte(19))// .setPostFilter(QueryBuilders.rangeQuery("age").gte(18).lt(19)).setPostFilter(QueryBuilders.rangeQuery("age").gt(17).lt(19))// .setPostFilter(FilterBuilders.rangeFilter("age").gte(10).lt(18))//实现分页,分页参数.setFrom(0).setSize(10).addSort("age", SortOrder.DESC)//ASC是升序,DESC是倒序.get();SearchHits hits = searchResponse.getHits();Long total = hits.getTotalHits();Long pages = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;Integer currentNo = pageNo;//获取满足条件数据的详细内容List<String> datas = new ArrayList<>();SearchHit[] hits2 = hits.getHits();for (SearchHit searchHit : hits2) {datas.add(searchHit.getSourceAsString());}}public static Map<String, Object> searchDefault(Integer pageNo, Integer pageSize) throws Exception {Integer startIndex = (pageNo - 1) * pageSize;SearchResponse searchResponse = client.prepareSearch(EsConstants.INDEX)//指定索引库.setTypes(EsConstants.TYPE)//指定类型.setQuery(QueryBuilders.matchAllQuery())//查询所有//实现分页,分页参数.setFrom(startIndex).setSize(pageSize).addSort(EsConstants.FIELD_PAYMANCOUNTS, SortOrder.DESC)//ASC是升序,DESC是倒序.get();SearchHits hits = searchResponse.getHits();Long total = hits.getTotalHits();Long pages = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;Integer currentNo = pageNo;SearchHit[] hits2 = hits.getHits();return getResultList(hits2, currentNo, pages, total);}// public static Map<String, Object> searchByShopOrPrice(Integer pageNo, Integer pageSize, String sortBy, String str) throws Exception {
// Integer startIndex = (pageNo - 1) * pageSize;
// SearchResponse searchResponse = null;
// if (str == null) {
// str = "*";
// } else {
// str = "*" + str + "*";
// }
// if (sortBy != null) {
// if ("DESC".equals(sortBy)) {
// searchResponse = client.prepareSearch(EsConstants.INDEX)//指定索引库
// .setTypes(EsConstants.TYPE)//指定类型
// .setQuery(QueryBuilders.queryStringQuery(EsConstants.FIELD_GOODSNAME + ":" + str))
// //实现分页,分页参数
// .setFrom(startIndex)
// .setSize(pageSize)
// .addSort(EsConstants.FIELD_PRICE, SortOrder.DESC)//ASC是升序,DESC是倒序
// .get();
// } else {
// searchResponse = client.prepareSearch(EsConstants.INDEX)//指定索引库
// .setTypes(EsConstants.TYPE)//指定类型
// .setQuery(QueryBuilders.queryStringQuery(EsConstants.FIELD_GOODSNAME + ":" + str))
// //实现分页,分页参数
// .setFrom(startIndex)
// .setSize(pageSize)
// .addSort(EsConstants.FIELD_PRICE, SortOrder.ASC)//ASC是升序,DESC是倒序
// .get();
// }
// } else {
// searchResponse = client.prepareSearch(EsConstants.INDEX)//指定索引库
// .setTypes(EsConstants.TYPE)//指定类型
// .setQuery(QueryBuilders.queryStringQuery(EsConstants.FIELD_GOODSNAME + ":" + str))
// //实现分页,分页参数
// .setFrom(startIndex)
// .setSize(pageSize)
// .get();
// }
// SearchHits hits = searchResponse.getHits();
// Long total = hits.getTotalHits();
// Long pages = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
// Integer currentNo = pageNo;
// SearchHit[] hits2 = hits.getHits();
// return getResultList(hits2, currentNo, pages, total);
//
// }public static Map<String, Object> searchByAll(Integer pageNo, Integer pageSize, String sortBy, String sortColumn, String str, Integer isOnSale, Integer isOnlyFamily, Integer isInStore, BigDecimal minPrice, BigDecimal maxPrice, Long catId, Long brandId) throws Exception {Integer startIndex = (pageNo - 1) * pageSize;SearchResponse searchResponse = null;SearchRequestBuilder searchRequestBuilder = client.prepareSearch(EsConstants.INDEX)//指定索引库.setTypes(EsConstants.TYPE);//指定类型if (str == null) {searchRequestBuilder.setQuery(QueryBuilders.matchAllQuery());//查询所有} else {searchRequestBuilder.setQuery(QueryBuilders.boolQuery().should(QueryBuilders.matchQuery(EsConstants.FIELD_SHOPGOODSNAME, str).boost(8.0f)).should(QueryBuilders.matchQuery(EsConstants.FIELD_CATEGORYNAME, str).boost(8.0f)).should(QueryBuilders.matchQuery(EsConstants.FIELD_MARKETINGACTIVITIESLIST, str).boost(8.0f)));}if (brandId != null) {searchRequestBuilder.setQuery(QueryBuilders.termQuery(EsConstants.FIELD_BRANDID, brandId));//精确查询 品牌Id}if (catId != null) {searchRequestBuilder.setQuery(QueryBuilders.termQuery(EsConstants.FIELD_CATID, catId));//精确查询 类目ID}if (minPrice != null) {searchRequestBuilder.setPostFilter(QueryBuilders.rangeQuery(EsConstants.FIELD_PRICE).gte(minPrice.toString()));//过滤查询 价格高于低价}if (maxPrice != null) {searchRequestBuilder.setPostFilter(QueryBuilders.rangeQuery(EsConstants.FIELD_PRICE).lte(minPrice.toString()));//过滤查询 价格低于高价}if (isOnSale != null && isOnSale == 1 ) {searchRequestBuilder.setPostFilter(QueryBuilders.rangeQuery(EsConstants.FIELD_ISMARKETINGACTIVITIES).gt("0"));//过滤查询 促销中商品}if (isInStore != null && isInStore == 1 ) {searchRequestBuilder.setPostFilter(QueryBuilders.rangeQuery(EsConstants.FIELD_ISHAVESTORE).gt("0"));//过滤查询 有货商品}if (isOnlyFamily != null && isOnlyFamily == 1) {searchRequestBuilder.setQuery(QueryBuilders.termQuery(EsConstants.FIELD_ISFAMILYONLY, "1"));//精确查询 家庭会员专享}if(sortColumn!=null){if (sortBy != null ) {if ("DESC".equals(sortBy)) {searchRequestBuilder.addSort(sortColumn, SortOrder.DESC);//ASC是升序,DESC是倒序}if ("ASC".equals(sortBy)) {searchRequestBuilder.addSort(sortColumn, SortOrder.ASC);//ASC是升序,DESC是倒序}}}//实现分页,分页参数searchRequestBuilder.setFrom(startIndex).setSize(pageSize);searchResponse = searchRequestBuilder.get();SearchHits hits = searchResponse.getHits();Long total = hits.getTotalHits();Long pages = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;Integer currentNo = pageNo;SearchHit[] hits2 = hits.getHits();return getResultList(hits2, currentNo, pages, total);}private static Map<String, Object> getResultList(SearchHit[] hits, Integer currentNo, Long pages, Long total) {List<Map<String, Object>> datas = new ArrayList<>();for (SearchHit searchHit : hits) {JSONObject json = JSON.parseObject(searchHit.getSourceAsString());System.out.println(json.toString());Map<String, Object> map = new HashMap<>();map.put("alterempl", json.getString("alterempl"));map.put("altertime", json.getString("altertime"));map.put("categoryid", json.getString("categoryid"));map.put("categoryname", json.getString("categoryname"));map.put("createempl", json.getString("createempl"));map.put("createtime", json.getString("createtime"));map.put("esid", json.getString("esid"));map.put("goodsid", json.getString("goodsid"));map.put("id", json.getLong("id"));map.put("isfamilyonly", json.getByte("isfamilyonly"));map.put("ishavestore", json.getByte("ishavestore"));map.put("ismarketingactivities", json.getByte("ismarketingactivities"));map.put("marketingactivitieslist", json.getString("marketingactivitieslist"));map.put("paymancounts", json.getLong("paymancounts"));map.put("price", json.getBigDecimal("price"));map.put("remark", json.getString("remark"));map.put("shopgoodsname", json.getString("shopgoodsname"));map.put("shopid", json.getString("shopid"));map.put("shopname", json.getString("shopname"));map.put("shopphotourl", json.getString("shopphotourl"));map.put("shopscore", json.getBigDecimal("shopscore"));map.put("timestamp", json.getString("timestamp"));map.put("validstatus", json.getByte("validstatus"));datas.add(map);}Map<String, Object> resultMap = new HashMap<>();resultMap.put("currPageNo", currentNo);resultMap.put("pageNos", pages);resultMap.put("total", total);resultMap.put("datas", datas);return resultMap;}//添加索引public static void addIndex(String index, String type, String id) throws Exception {IndexResponse response = client.prepareIndex(index, type, id).setSource(jsonBuilder().startObject().field("user", "kimchy").field("postDate", new Date()).field("message", "trying out Elasticsearch").endObject()).get();System.out.println(response.getId());}//删除索引public static void deleteIndex(String index, String type, String id) throws Exception {DeleteResponse response = client.prepareDelete(index, type, id).get();}```复制代码