1.首先在pom导入jar
<dependency><groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>7.6.0</version> <exclusions> <exclusion> <groupId>org.elasticsearch</groupId> <artifactId>elasticsearch</artifactId> </exclusion> </exclusions></dependency><!-- https://mvnrepository.com/artifact/org.elasticsearch/elasticsearch --><dependency> <groupId>org.elasticsearch</groupId> <artifactId>elasticsearch</artifactId> <version>7.6.0</version></dependency>
2.配置类
package com.hw.ydy.drugstore.h5.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.Value;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configurationpublic class EsConfig { @Value("${spring.elasticsearch.config}") private String config; @Bean(value = "getClient") public RestHighLevelClient getClient(){ String[] conStr = config.split(":"); HttpHost[] httpHosts = new HttpHost[1]; httpHosts[0] = new HttpHost(conStr[0], Integer.parseInt(conStr[1])); RestClientBuilder restClientBuilder = RestClient.builder(httpHosts); RestHighLevelClient client = new RestHighLevelClient(restClientBuilder); return client; }}
3.搜索工具类
package com.hw.ydy.drugstore.h5.util;import com.hw.ydy.drugstore.h5api.dto.request.EsSearchRequest;import lombok.extern.slf4j.Slf4j;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.unit.TimeValue;import org.elasticsearch.index.query.BoolQueryBuilder;import org.elasticsearch.index.query.MatchQueryBuilder;import org.elasticsearch.index.query.QueryBuilders;import org.elasticsearch.search.builder.SearchSourceBuilder;import org.elasticsearch.search.sort.FieldSortBuilder;import org.elasticsearch.search.sort.SortOrder;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.stereotype.Component;import java.util.ArrayList;import java.util.List;import java.util.concurrent.CompletableFuture;import java.util.concurrent.TimeUnit;@Slf4j@Componentpublic class EsUtil { @Qualifier("getClient") @Autowired private RestHighLevelClient client; public List<String> search(EsSearchRequest request) { SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery(request.getColumn(), request.getValue());//这里可以根据字段进行搜索,must表示符合条件的,相反的mustnot表示不符合条件的// MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery("YunZhiHui", "address", "company");// TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("interest", "game steak");// RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("birthday");// rangeQueryBuilder.gte("2018-01-26");// rangeQueryBuilder.lte("2019-01-26"); BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery(); //must 相当于 与 & = ;must not 相当于 非 ~ !=;should 相当于 或 | or ;filter 过滤 boolBuilder.must(matchQueryBuilder);// boolBuilder.must(termQueryBuilder);// boolBuilder.must(rangeQueryBuilder);// boolBuilder.should(multiMatchQueryBuilder); if(request.getExcludeFields()==null && request.getIncludeFields()==null){// sourceBuilder.fetchSource(false); }else{ sourceBuilder.fetchSource(request.getIncludeFields(), request.getExcludeFields());//第一个参数查询,第二个参数过滤 } if(request.getFrom()!=0) { sourceBuilder.from(request.getFrom()); } if(request.getSize()!=0) { sourceBuilder.size(request.getSize()); } if(request.getTimeout()!=0){ sourceBuilder.timeout(new TimeValue(request.getTimeout(), TimeUnit.SECONDS)); }// sourceBuilder.sort(new ScoreSortBuilder().order(SortOrder.DESC)); //按_score降序排序(默认值)。 if(request.getSort()!=0){ sourceBuilder.sort(new FieldSortBuilder(request.getSortWord()).order(request.getSort()>0 ? SortOrder.ASC : SortOrder.DESC));//也可以按_id字段进行升序排序 } sourceBuilder.query(boolBuilder); SearchRequest searchRequest = new SearchRequest(request.getIndex()); searchRequest.source(sourceBuilder); List<String> list = new ArrayList<>(); try { SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT); searchResponse.getHits().forEach(message ->{ CompletableFuture.runAsync(() -> { log.info(message.getSourceAsString()); }); String item = message.getSourceAsString(); list.add(item); }); }catch (Exception e){ log.error("ES搜索出错", e); } return list; }}
查询入参类
package com.hw.ydy.drugstore.h5api.dto.request;import io.swagger.annotations.ApiModelProperty;import lombok.Data;@Datapublic class EsSearchRequest { @ApiModelProperty(value = "索引") private String index; @ApiModelProperty(value = "根据某个字段搜索") private String column; @ApiModelProperty(value = "搜索关键词") private String value; @ApiModelProperty(value = "查询起始索引") private int from; @ApiModelProperty(value = "查询条数,不设置就所有") private int size; @ApiModelProperty(value = "超时时间,单位秒") private int timeout; @ApiModelProperty(value = "排序字段") private String sortWord; @ApiModelProperty(value = "排序方式,0:不排序,1:升序,-1降序") private int sort; @ApiModelProperty(value = "需要查询的字段") private String[] includeFields; @ApiModelProperty(value = "不查询需要排除的字段") private String[] excludeFields;}