最近项目要使用elasticsearch,研究了一下,官方文档说7.0版本后将放弃transportClient,故采用RestHighLevelClient方式连接,使用的版本为elasticsearch6.4.3
- maven依赖
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>6.4.3</version>
</dependency>
<!-- Java High Level REST Client -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>6.4.3</version>
</dependency>
- application.yml文件
elasticsearch:
ip: 192.168.244.128:9200
- ElasticsearchRestClient客户端配置,注意版本号,低版本使用不了,会报错
@Slf4j
@Configuration
public class ElasticsearchRestClient {
private static final int ADDRESS_LENGTH = 2;
private static final String HTTP_SCHEME = "http";
/**
* 使用冒号隔开ip和端口1
*/
@Value("${elasticsearch.ip}")
String[] ipAddress;
@Bean
public RestClientBuilder restClientBuilder() {
HttpHost[] hosts = Arrays.stream(ipAddress)
.map(this::makeHttpHost)
.filter(Objects::nonNull)
.toArray(HttpHost[]::new);
log.debug("hosts:{}", Arrays.toString(hosts));
return RestClient.builder(hosts);
}
@Bean(name = "highLevelClient")
public RestHighLevelClient highLevelClient(@Autowired RestClientBuilder restClientBuilder) {
restClientBuilder.setMaxRetryTimeoutMillis(60000);
return new RestHighLevelClient(restClientBuilder);
}
private HttpHost makeHttpHost(String s) {
assert StringUtils.isNotEmpty(s);
String[] address = s.split(":");
if (address.length == ADDRESS_LENGTH) {
String ip = address[0];
int port = Integer.parseInt(address[1]);
return new HttpHost(ip, port, HTTP_SCHEME);
} else {
return null;
}
}
}
- 增加数据和查询数据方法
@Service
@Slf4j
public class RestCompamyService {
@Autowired
RestHighLevelClient highLevelClient;
public void add() throws IOException {
Map map = Maps.newHashMap();
map.put("companyid", 1);
map.put("companyName", "阿里巴巴");
map.put("companyInfo", "国内著名电商公司");
map.put("order", 3);
Map map2 = Maps.newHashMap();
map2.put("companyid", 2);
map2.put("companyName", "京东");
map2.put("companyInfo", "国内知名电商公司");
map2.put("order", 2);
Map map3 = Maps.newHashMap();
map3.put("companyid", 3);
map3.put("companyName", "亚马逊");
map3.put("companyInfo", "国外著名电商公司");
map3.put("order", 1);
Map map4 = Maps.newHashMap();
map4.put("companyid", 4);
map4.put("companyName", "腾讯");
map4.put("companyInfo", "国内著名社交游戏公司");
map4.put("order", 6);
Map map5 = Maps.newHashMap();
map5.put("companyid", 5);
map5.put("companyName", "谷歌");
map5.put("companyInfo", "世界顶级科技公司");
map5.put("order", 4);
Map map6 = Maps.newHashMap();
map6.put("companyid", 6);
map6.put("companyName", "百度");
map6.put("companyInfo", "国内知名搜索公司");
map6.put("order", 5);
IndexRequest indexRequest = new IndexRequest("paic", "company", "1").source(map);
highLevelClient.index(indexRequest);
IndexRequest indexRequest2 = new IndexRequest("paic", "company", "2").source(map2);
highLevelClient.index(indexRequest2);
IndexRequest indexRequest3 = new IndexRequest("paic", "company", "3").source(map3);
highLevelClient.index(indexRequest3);
IndexRequest indexRequest4 = new IndexRequest("paic", "company", "4").source(map4);
highLevelClient.index(indexRequest4);
IndexRequest indexRequest5 = new IndexRequest("paic", "company", "5").source(map5);
highLevelClient.index(indexRequest5);
IndexRequest indexRequest6 = new IndexRequest("paic", "company", "6").source(map6);
highLevelClient.index(indexRequest6);
}
public Object searchByQuery() {
SearchRequest searchRequest = new SearchRequest("paic");
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("companyInfo", "电商");
// TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("companyInfo.keyword", "电商");
BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
boolBuilder.must(matchQueryBuilder);
// boolBuilder.must(termQueryBuilder);
sourceBuilder.query(boolBuilder);
//分页
sourceBuilder.from(0);
sourceBuilder.size(10);
//
// 排序
FieldSortBuilder fsb = SortBuilders.fieldSort("order");
fsb.order(SortOrder.DESC);
sourceBuilder.sort(fsb);
//构建高亮体
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.preTags("<span style='color:red'>");
highlightBuilder.postTags("</span>");
//高亮字段
highlightBuilder.field("companyInfo").field("companyName");
sourceBuilder.highlighter(highlightBuilder);
searchRequest.source(sourceBuilder);
List<Map<String, Object>> result = Lists.newLinkedList();
try {
SearchResponse response = highLevelClient.search(searchRequest);
SearchHit[] searchHits = response.getHits().getHits();
if (searchHits != null && searchHits.length > 0) {
for (SearchHit searchHit : searchHits) {
Map<String, Object> map = searchHit.getSourceAsMap();
//替换高亮
Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
HighlightField highlightField = highlightFields.get("companyInfo");
String highlightCompanyInfo = highlightField.fragments()[0].toString();
map.put("companyInfo", highlightCompanyInfo);
result.add(map);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}