import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ElasticSearchClientConfig {
@Bean
public RestHighLevelClient restHighLevelClient(){
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("127.0.0.1",9200,"http"))
);
return client;
}
}
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Slf4j
@Component
public class ESUtil {
@Autowired
@Qualifier(value = "restHighLevelClient")
private RestHighLevelClient client;
public void creatIndex(String indexName) {
CreateIndexRequest indexRequest = new CreateIndexRequest(indexName);
GetIndexRequest getIndexRequest = new GetIndexRequest(indexName);
try {
if (!client.indices().exists(getIndexRequest, RequestOptions.DEFAULT)) {
CreateIndexResponse indexResponse = client.indices().create(indexRequest, RequestOptions.DEFAULT);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public Boolean deleteIndex(String indexName) {
DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(indexName);
try {
AcknowledgedResponse delete = client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
return delete.isAcknowledged();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
public String addDoc(String indexName, Object o, String id) {
IndexRequest request = new IndexRequest(indexName);
request.id(id);
request.timeout("6s");
request.source(JSON.toJSONString(o), XContentType.JSON);
IndexResponse index = null;
try {
index = client.index(request, RequestOptions.DEFAULT);
} catch (IOException e) {
e.printStackTrace();
log.error("添加addDoc失败");
}
return index.getId();
}
public GetResponse getDocByIdAndIndexName(String indexName, String id) {
GetRequest getRequest = new GetRequest(indexName, id);
boolean exists = false;
try {
exists = client.exists(getRequest, RequestOptions.DEFAULT);
if (exists) {
GetResponse documentFields = client.get(getRequest, RequestOptions.DEFAULT);
return documentFields;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public Boolean deleteDocByIndexNameAndId(String indexName, String id) {
DeleteRequest deleteRequest = new DeleteRequest(indexName, id);
DeleteResponse delete = null;
try {
delete = client.delete(deleteRequest, RequestOptions.DEFAULT);
} catch (IOException e) {
e.printStackTrace();
}
return "OK".equals(delete.status().toString());
}
public Boolean updateDocByIndexNameAndId(String indexName, String id, Object doc) {
UpdateRequest updateRequest = new UpdateRequest(indexName, id);
updateRequest.timeout("1s");
updateRequest.doc(JSONObject.toJSONString(doc), XContentType.JSON);
UpdateResponse update = null;
try {
update = client.update(updateRequest, RequestOptions.DEFAULT);
} catch (IOException e) {
e.printStackTrace();
}
return "OK".equals(update.status().toString());
}
public Boolean batchAddDoc(String Indexname, List list) {
BulkRequest bulkRequest = new BulkRequest();
for (int i = 0; i < list.size(); i++) {
bulkRequest.add(new IndexRequest(Indexname)
.source(JSONObject.toJSONString(list.get(i)), XContentType.JSON)
);
}
BulkResponse bulk = null;
try {
bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
} catch (IOException e) {
e.printStackTrace();
}
return "OK".equals(bulk.status().toString());
}
public List<Map<String, Object>> searchPage(String indexName, String name, String keyword, Integer pageNo, Integer pageSize) throws IOException {
pageNo = pageNo == null ? 1 : pageNo;
pageSize = pageSize == null ? 10 : pageSize;
if (pageNo == null) {
pageNo = 1;
}
SearchRequest searchRequest = new SearchRequest(indexName);
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.from(pageNo);
sourceBuilder.size(pageSize);
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery(name, keyword);
sourceBuilder.query(termQueryBuilder);
sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
searchRequest.source(sourceBuilder);
SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
ArrayList<Map<String, Object>> list = new ArrayList<>();
for (SearchHit hit : search.getHits().getHits()) {
hit.getSourceAsMap().put("id",hit.getId());
list.add(hit.getSourceAsMap());
}
return list;
}
public List<Map<String, Object>> searchHighPage(String indexName, String name, String keyword, Integer pageNo, Integer pageSize) throws IOException {
pageNo = pageNo == null ? 1 : pageNo;
pageSize = pageSize == null ? 10 : pageSize;
if (pageNo <= 1) {
pageNo = 1;
}
SearchRequest searchRequest = new SearchRequest(indexName);
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.from(pageNo);
sourceBuilder.size(pageSize);
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.field(name);
highlightBuilder.requireFieldMatch(false);
highlightBuilder.preTags("<span style='color:red'>");
highlightBuilder.postTags("</span>");
sourceBuilder.highlighter(highlightBuilder);
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery(name, keyword);
sourceBuilder.query(termQueryBuilder);
sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
searchRequest.source(sourceBuilder);
SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
ArrayList<Map<String, Object>> list = new ArrayList<>();
for (SearchHit hit : search.getHits().getHits()) {
Map<String, Object> sourceAsMap = hit.getSourceAsMap();
sourceAsMap.put("id",hit.getId());
Map<String, HighlightField> highlightFields = hit.getHighlightFields();
HighlightField title = highlightFields.get(name);
if (title != null) {
Text[] fragments = title.fragments();
String newTitle = "";
for (Text fragment : fragments) {
newTitle += fragment;
}
sourceAsMap.put(name, newTitle);
}
list.add(sourceAsMap);
}
return list;
}
}