packagecom.demo.elasticsearch.service;importcom.alibaba.fastjson.JSON;importcom.demo.elasticsearch.bean.FileBean;importcom.demo.elasticsearch.bean.FileBeanQuery;importcom.demo.elasticsearch.bean.FileMapping;importcom.demo.elasticsearch.util.AttachmentReader;importorg.apache.http.HttpHost;importorg.elasticsearch.action.admin.indices.create.CreateIndexRequest;importorg.elasticsearch.action.admin.indices.create.CreateIndexResponse;importorg.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;importorg.elasticsearch.action.admin.indices.mapping.get.GetMappingsRequest;importorg.elasticsearch.action.admin.indices.mapping.get.GetMappingsResponse;importorg.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;importorg.elasticsearch.action.delete.DeleteRequest;importorg.elasticsearch.action.delete.DeleteResponse;importorg.elasticsearch.action.get.GetRequest;importorg.elasticsearch.action.get.GetResponse;importorg.elasticsearch.action.index.IndexRequest;importorg.elasticsearch.action.index.IndexResponse;importorg.elasticsearch.action.search.MultiSearchRequest;importorg.elasticsearch.action.search.MultiSearchResponse;importorg.elasticsearch.action.search.SearchRequest;importorg.elasticsearch.action.search.SearchResponse;importorg.elasticsearch.action.support.master.AcknowledgedResponse;importorg.elasticsearch.client.RequestOptions;importorg.elasticsearch.client.RestClient;importorg.elasticsearch.client.RestHighLevelClient;importorg.elasticsearch.client.core.CountRequest;importorg.elasticsearch.client.core.CountResponse;importorg.elasticsearch.common.text.Text;importorg.elasticsearch.common.xcontent.XContentType;importorg.elasticsearch.index.query.QueryBuilders;importorg.elasticsearch.search.SearchHit;importorg.elasticsearch.search.SearchHits;importorg.elasticsearch.search.builder.SearchSourceBuilder;importorg.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;importorg.elasticsearch.search.fetch.subphase.highlight.HighlightField;importorg.elasticsearch.search.suggest.Suggest;importorg.elasticsearch.search.suggest.SuggestBuilder;importorg.elasticsearch.search.suggest.SuggestBuilders;importorg.elasticsearch.search.suggest.SuggestionBuilder;importorg.elasticsearch.search.suggest.completion.CompletionSuggestion;importorg.springframework.stereotype.Service;importjava.io.File;importjava.io.IOException;importjava.lang.reflect.Field;importjava.util.ArrayList;importjava.util.List;importjava.util.Map;/*** @Author: ln
* @Date: 2019/2/22 15:37
* @Description:*/@Servicepublic class ElasticsearchServiceImpl implementsElasticsearchService {
RestHighLevelClient client;
@Overridepublic String createIndex(String index, FileMapping mapping) throwsIOException {
client= newRestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
CreateIndexRequest request= newCreateIndexRequest(index);//索引配置
request.mapping("doc","keywordName", "type=keyword", "keywordAuthor", "type=keyword","suggestName", "type=completion", "suggestAuthor", "type=completion");
CreateIndexResponse createIndexResponse=client.indices().create(request, RequestOptions.DEFAULT);
client.close();returnJSON.toJSONString(createIndexResponse);
}
@Overridepublic String delIndex(String index) throwsIOException {
client= newRestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
DeleteIndexRequest request= newDeleteIndexRequest(index);
AcknowledgedResponse deleteIndexResponse=client.indices().delete(request, RequestOptions.DEFAULT);
System.out.println(JSON.toJSONString(deleteIndexResponse));
client.close();returnJSON.toJSONString(deleteIndexResponse.isAcknowledged());
}
@Overridepublic String putDocument(String index, FileBean fileBean) throwsIOException {
client= newRestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
File file= newFile(fileBean.getFilePath());
String content=AttachmentReader.reader(fileBean.getFilePath());
fileBean.setContent(content);
fileBean.setName(file.getName());
IndexRequest indexRequest= new IndexRequest(index, "doc", fileBean.getId());
indexRequest.source(JSON.toJSONString(fileBean), XContentType.JSON);
IndexResponse response=client.index(indexRequest, RequestOptions.DEFAULT);
System.out.println(JSON.toJSONString(response));
client.close();returnJSON.toJSONString(response.status());
}
@Overridepublic String delDocument(String index, String id) throwsIOException {
client= newRestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
DeleteRequest request= new DeleteRequest(index,"doc", id );
DeleteResponse deleteResponse=client.delete(request, RequestOptions.DEFAULT);
System.out.println(JSON.toJSONString(deleteResponse));
client.close();returnJSON.toJSONString(deleteResponse.status());
}
@Overridepublic String getDocument(String index, String id) throwsIOException {
client= newRestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
GetRequest getRequest= new GetRequest(index,"doc", id );
GetResponse getResponse=client.get(getRequest, RequestOptions.DEFAULT);
System.out.println(JSON.toJSONString(getResponse));
client.close();returnJSON.toJSONString(getResponse);
}
@OverridepublicString keywordSearch(String index, String value,int current, int size) throwsIOException {
client= newRestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
SearchRequest searchRequest= newSearchRequest();
searchRequest.indices(index);
SearchSourceBuilder searchSourceBuilder= newSearchSourceBuilder();//支持全词搜索的字段有:keywordName,keywordAuthor"
searchSourceBuilder.query(QueryBuilders.multiMatchQuery(value, "keywordName", "keywordAuthor"));
searchSourceBuilder.from(current);
searchSourceBuilder.size(size);
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse=client.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(JSON.toJSONString(searchResponse));//处理返回结果
List> result =dealResult(searchResponse.getHits());
client.close();returnJSON.toJSONString(result);
}
@OverridepublicString multiSearch(String index, FileBeanQuery query,int current, int size) throwsIOException, IllegalAccessException {
client= newRestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
MultiSearchRequest request= newMultiSearchRequest();for(Field field : query.getClass().getDeclaredFields()) {
field.setAccessible(true);if(field.get(query) != null){
SearchRequest searchRequest= newSearchRequest(index);
SearchSourceBuilder searchSourceBuilder= newSearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.boolQuery().must(
QueryBuilders.matchQuery(field.getName(), field.get(query))));
searchRequest.source(searchSourceBuilder);
request.add(searchRequest);
}
}
MultiSearchResponse response=client.msearch(request, RequestOptions.DEFAULT);
System.out.println(JSON.toJSONString(response));//返回结果处理
List> result = new ArrayList<>();
MultiSearchResponse.Item[] multiSearchResponses=response.getResponses();for(MultiSearchResponse.Item multiSearchRespons : multiSearchResponses) {
SearchHits hits=multiSearchRespons.getResponse().getHits();for(SearchHit hit : hits.getHits()) {
Map map =hit.getSourceAsMap();if(!result.contains(map)){
result.add(map);
}
}
}
client.close();returnJSON.toJSONString(result);
}
@Overridepublic String highlightSearch(String index, String value, int current, int size) throwsIOException {
client= newRestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
SearchRequest searchRequest= newSearchRequest();
searchRequest.indices(index);
SearchSourceBuilder searchSourceBuilder= newSearchSourceBuilder();//高亮,支持所有FileBean实体的字段
HighlightBuilder highlightBuilder = newHighlightBuilder();
FileBean fileBean= newFileBean();
String[] fieldNames= newString[fileBean.getClass().getDeclaredFields().length];int i = 0;for(Field f : fileBean.getClass().getDeclaredFields()) {
HighlightBuilder.Field highlight= newHighlightBuilder.Field(f.getName());
highlight.highlighterType("unified");
highlightBuilder.field(highlight);
fieldNames[i]=f.getName();
i++;
}//设置高亮样式
highlightBuilder.preTags("");
highlightBuilder.postTags("");//添加查询条件
searchSourceBuilder.highlighter(highlightBuilder);
searchSourceBuilder.query(QueryBuilders.multiMatchQuery(value, fieldNames));//搜索也支持所有FileBean实体的字段
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse=client.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(JSON.toJSONString(searchResponse));//获取高亮字段
List> result = new ArrayList<>();
SearchHits hits=searchResponse.getHits();for(SearchHit hit : hits.getHits()) {
Map highlightFields =hit.getHighlightFields();for(String fieldName : fieldNames) {
HighlightField highlight=highlightFields.get(fieldName);
System.out.println(fieldName);if(highlight != null){
Text[] fragments=highlight.fragments();
String fragmentString= fragments[0].string();
System.out.println("高亮值:" +fragmentString);
Map map =hit.getSourceAsMap();
map.put(fieldName, fragmentString);if(!result.contains(map)){
result.add(map);
}
}
}
}
client.close();returnJSON.toJSONString(result);
}
@Overridepublic String suggestSearch(String index, String value) throwsIOException {
client= newRestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
SearchRequest searchRequest= newSearchRequest(index);
SearchSourceBuilder searchSourceBuilder= newSearchSourceBuilder();//查询补全词语
SuggestionBuilder completionName = SuggestBuilders.completionSuggestion("suggestName").text(value);
SuggestBuilder suggestBuilder= newSuggestBuilder();
suggestBuilder.addSuggestion("suggestName", completionName);
SuggestionBuilder completionAuthor= SuggestBuilders.completionSuggestion("suggestAuthor").text(value);
suggestBuilder.addSuggestion("suggestAuthor", completionAuthor);
searchSourceBuilder.suggest(suggestBuilder);
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse=client.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(JSON.toJSONString(searchResponse));//处理返回结果
Suggest suggest =searchResponse.getSuggest();//支持自动补全搜索的字段有suggestName,suggestAuthor
CompletionSuggestion termSuggestion = suggest.getSuggestion("suggestName");
CompletionSuggestion termSuggestionAuthor= suggest.getSuggestion("suggestAuthor");
List list =termSuggestion.getEntries();
list.addAll(termSuggestionAuthor.getEntries());
List suggestList = new ArrayList<>();for(CompletionSuggestion.Entry entry : list) {for(CompletionSuggestion.Entry.Option option : entry) {
String suggestText=option.getText().string();
System.out.println("补全的词语:" +suggestText);if(!suggestList.contains(suggestText)){
suggestList.add(suggestText);
}
}
}
client.close();returnJSON.toJSONString(suggestList);
}
@Overridepublic String searchAll(String index, int current, int size) throwsIOException {
client= newRestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
SearchRequest searchRequest= newSearchRequest(index);
SearchSourceBuilder searchSourceBuilder= newSearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
searchSourceBuilder.from(current);
searchSourceBuilder.size(size);
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse=client.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(JSON.toJSONString(searchResponse));//处理返回结果
SearchHits hits =searchResponse.getHits();
client.close();returnJSON.toJSONString(hits);
}@Overridepublic String countQuery(String index) throwsIOException {
client= newRestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
CountRequest countRequest= newCountRequest(index);
SearchSourceBuilder searchSourceBuilder= newSearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
countRequest.source(searchSourceBuilder);
SearchSourceBuilder sourceBuilder= newSearchSourceBuilder();
sourceBuilder.query(QueryBuilders.termQuery("user", "kimchy"));
countRequest.source(sourceBuilder);
CountResponse countResponse=client.count(countRequest, RequestOptions.DEFAULT);long count =countResponse.getCount();return count + "";
}private List>dealResult(SearchHits hits){
List> result = new ArrayList<>();for(SearchHit hit : hits.getHits()) {
Map map =hit.getSourceAsMap();
result.add(map);
}returnresult;
}
}