先把需要用的类注入进来
这两个类在meaven导入的时候就注入到spring了
@Autowired
private TransportClient transportClient;
private static TransportClient client;
根据ID查找elasticsearch是否存在某条数据
public static Map<String,Object> searchDataById(String index, String type, String id, String fields) {
GetRequestBuilder getRequestBuilder = client.prepareGet(index, type, id);
if (StringUtils.isNotEmpty(fields)) {
getRequestBuilder.setFetchSource(fields.split(","), null);
}
GetResponse getResponse = getRequestBuilder.execute().actionGet();
return getResponse.getSource();
}
判断索引是否存在
public static boolean isIndexExist(String index) {
IndicesExistsResponse inExistsResponse = client.admin().indices()
.exists(new IndicesExistsRequest(index)).actionGet();
if(inExistsResponse.isExists()) {
System.out.println("索引 "+ index + " 已存在。");
}
else {
System.out.println("索引 "+ index + " 不存在。");
}
return inExistsResponse.isExists();
}
创建索引
public static boolean createIndex(String index) {
if(!isIndexExist(index)) {
CreateIndexResponse indexResponse = client.admin().indices().prepareCreate(index).execute().actionGet();
if(indexResponse.isAcknowledged()) {
System.out.println("索引 "+ index + " 创建成功。");
}
else {
System.out.println("索引 "+ index + " 创建失败。");
}
return indexResponse.isAcknowledged();
}
return false;
}
删除索引
public static boolean deleteIndex(String index) {
if(isIndexExist(index)) {
AcknowledgedResponse dResponse = client.admin().indices().prepareDelete(index).execute().actionGet();
if (dResponse.isAcknowledged()) {
System.out.println("索引 "+ index + " 删除成功。");
} else {
System.out.println("索引 "+ index + " 删除失败。");
}
return dResponse.isAcknowledged();
}
else {
return false;
}
}
指定ID添加文档
public static String addData(JSONObject jsonObject, String index, String type, String id) {
IndexResponse response = client.prepareIndex(index, type, id).setSource(jsonObject).get();
System.out.println("添加数据状况: "+ response.status().getStatus() +" 。");
return response.getId();
}
其余的
public static void deleteDataById(String index, String type, String id) {
DeleteResponse response = client.prepareDelete(index, type, id).execute().actionGet();
System.out.println("删除数据状况: "+ response.status().getStatus() +" 。");
}
public static void updateDataById(JSONObject jsonObject, String index, String type, String id) {
UpdateRequest updateRequest = new UpdateRequest();
updateRequest.index(index).type(type).id(id).doc(jsonObject);
client.update(updateRequest);
}
public static Map<String,Object> searchDataById(String index, String type, String id, String fields) {
GetRequestBuilder getRequestBuilder = client.prepareGet(index, type, id);
if (StringUtils.isNotEmpty(fields)) {
getRequestBuilder.setFetchSource(fields.split(","), null);
}
GetResponse getResponse = getRequestBuilder.execute().actionGet();
return getResponse.getSource();
}
public static Map<String, Object> searchListData(String index, String type, QueryBuilder query, Integer size, String fields, String sortField, String highlightField) {
SearchRequestBuilder searchRequestBuilder = client.prepareSearch(index);
if (StringUtils.isNotEmpty(type)) {
searchRequestBuilder.setTypes(type.split(","));
}
searchRequestBuilder.setQuery(query);
if (StringUtils.isNotEmpty(fields)) {
searchRequestBuilder.setFetchSource(fields.split(","), null);
}
searchRequestBuilder.setFetchSource(true);
searchRequestBuilder.setExplain(true);
if (StringUtils.isNotEmpty(highlightField)) {
HighlightBuilder highlightBuilder = new HighlightBuilder();
String[] highlightFields = highlightField.split(",");
for(String hField: highlightFields) {
highlightBuilder.field(new HighlightBuilder.Field(hField));
}
highlightBuilder.preTags("<span style='color:red'>");
highlightBuilder.postTags("</span>");
highlightBuilder.fragmentSize(800000);
highlightBuilder.numOfFragments(0);
searchRequestBuilder.highlighter(highlightBuilder);
}
if (size != null && size > 0) {
searchRequestBuilder.setSize(size);
}
System.out.println(searchRequestBuilder);
SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
long total = searchResponse.getHits().totalHits;
long length = searchResponse.getHits().getHits().length;
System.out.println("共查询到" + total + "条数据,处理数据条数为" + length +"条。");
if (searchResponse.status().getStatus() == 200) {
List<Map<String, Object>> sourceList = setSearchResponse(searchResponse, highlightField);
Map<String, Object> map = new HashMap<String, Object>();
map.put("total", total);
map.put("sourceList", sourceList);
return map;
}
return null;
}
public static Map<String, Object> searchListDataPage(String index, String type, int startPage, int pageSize, QueryBuilder query, String fields, String sortField, String highlightField) {
SearchRequestBuilder searchRequestBuilder = client.prepareSearch(index);
if (StringUtils.isNotEmpty(type)) {
searchRequestBuilder.setTypes(type.split(","));
}
searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
if (StringUtils.isNotEmpty(fields)) {
searchRequestBuilder.setFetchSource(fields.split(","), null);
}
if (StringUtils.isNotEmpty(sortField)) {
searchRequestBuilder.addSort(sortField, SortOrder.DESC);
}
if (StringUtils.isNotEmpty(highlightField)) {
HighlightBuilder highlightBuilder = new HighlightBuilder();
String[] highlightFields = highlightField.split(",");
for(String hField: highlightFields) {
highlightBuilder.field(new HighlightBuilder.Field(hField));
}
highlightBuilder.preTags("<span style='color:red'>");
highlightBuilder.postTags("</span>");
highlightBuilder.fragmentSize(800000);
highlightBuilder.numOfFragments(0);
searchRequestBuilder.highlighter(highlightBuilder);
}
searchRequestBuilder.setQuery(query);
searchRequestBuilder.setFrom((startPage-1)*pageSize).setSize(pageSize);
searchRequestBuilder.setExplain(true);
System.out.println(searchRequestBuilder);
SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
long total = searchResponse.getHits().totalHits;
long length = searchResponse.getHits().getHits().length;
System.out.println("共查询到" + total + "条数据,处理数据条数为" + length +"条。");
if (searchResponse.status().getStatus() == 200) {
List<Map<String, Object>> sourceList = setSearchResponse(searchResponse, highlightField);
Map<String, Object> map = new HashMap<String, Object>();
map.put("total", total);
map.put("sourceList", sourceList);
return map;
}
return null;
}
public static void addAllData(List<ESKnowledgeEntity> know_list, String index, String type) {
deleteIndex(index);
know_list.forEach(esKnowledgeEntity -> {
esKnowledgeEntity.setDetails(delHTMLTag(esKnowledgeEntity.getDetails()));
});
BulkRequestBuilder bulkRequest= client.prepareBulk();
for(ESKnowledgeEntity know: know_list) {
String source = JSONSerializer.toJSON(know).toString();
bulkRequest.add(client.prepareIndex(index,type,know.getRecId()).setSource(source,XContentType.JSON));
}
bulkRequest.execute().actionGet();
System.out.println("共查询到" + know_list.size() + "条数据,已导入成功");
}
public static boolean addListData(List<ESKnowledgeEntity> know_list, String index, String type) {
boolean flag = false;
int count = 0;
if(isIndexExist(index)) {
know_list.forEach(esKnowledgeEntity -> {
esKnowledgeEntity.setDetails(delHTMLTag(esKnowledgeEntity.getDetails()));
});
for(ESKnowledgeEntity know: know_list) {
String source = JSONSerializer.toJSON(know).toString();
JSONObject json = JSONObject.parseObject(source);
Map<String,Object> map = searchDataById(index, type, know.getRecId(), null);
if(map!=null) {
updateDataById(json, index, type, know.getRecId());
}
else {
addData(json, index, type, know.getRecId());
}
count++;
}
System.out.println("共查询到" + count + "条数据,已导入成功");
flag = true;
return flag;
}
return flag;
}
public static String delHTMLTag(String htmlStr) {
String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>";
String regEx_html = "<[^>]+>";
Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
Matcher m_style = p_style.matcher(htmlStr);
htmlStr = m_style.replaceAll("");
Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
Matcher m_html = p_html.matcher(htmlStr);
htmlStr = m_html.replaceAll("");
htmlStr = htmlStr.replace(" ", "");
return htmlStr.trim();
}
private static List<Map<String, Object>> setSearchResponse(SearchResponse searchResponse, String highlightField) {
List<Map<String, Object>> sourceList = new ArrayList<Map<String, Object>>();
StringBuffer stringBuffer = new StringBuffer();
String[] hFields = highlightField.split(",");
for (SearchHit searchHit : searchResponse.getHits().getHits()) {
searchHit.getSourceAsMap().put("id", searchHit.getId());
for(String hFiled:hFields) {
highlightField = hFiled;
if (StringUtils.isNotEmpty(highlightField)) {
stringBuffer = new StringBuffer();
Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
if(highlightFields.containsKey(highlightField)) {
Text[] text = searchHit.getHighlightFields().get(highlightField).getFragments();
if (text != null) {
for (Text str : text) {
stringBuffer.append(str.string());
}
searchHit.getSourceAsMap().put(highlightField, stringBuffer.toString());
}
}
}
}
sourceList.add(searchHit.getSourceAsMap());
}
return sourceList;
}
|