elasticsearch 的client的完善

This commit is contained in:
Pancaihua 2024-08-19 15:33:42 +08:00
parent 36a39872bb
commit 1f4b51533a

View File

@ -2,6 +2,10 @@ package cn.iocoder.yudao.framework.common.util.elasticsearch;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.List;
import org.apache.http.HttpHost;
@ -43,13 +47,20 @@ public class EsearchUtils {
private static RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost(ipStr,port,modeStr)));
public static <T> void saveIndex(long id,T createReqVO, String indexName) throws IOException {
String indexStatus = null;
// Long kId = id;
//String indexStatus = null;
String knowStr = JSON.toJSONString(createReqVO);
JSONObject knowObj = JSONObject.parseObject(knowStr);
String createTimeStr = DateTimeFormatter.ISO_INSTANT
.withZone(ZoneOffset.UTC)
.format(Instant.now())
.replaceAll("\\.[0-9]+Z$", "Z");
//knowObj.put("createTime", System.currentTimeMillis()); // 时间戳格式
knowObj.put("createTime", createTimeStr);
knowObj.put("id", String.valueOf(id));
IndexRequest esRequest = new IndexRequest( indexName );
esRequest.id(String.valueOf(id));
esRequest.source(knowObj.toJSONString(), XContentType.JSON);
//System.out.println("========保存数据:" + knowObj.toJSONString());
esRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL);
@ -65,8 +76,11 @@ public class EsearchUtils {
public static <T> void updateIndex(long id,T createReqVO, String indexName){
JSONObject kmsMainObj = (JSONObject) JSONObject.toJSON(createReqVO);
//kmsMainObj.put("createTime",createReqVO.getCreateTime()!=null?createReqVO.getCreateTime().getTime():0L);
//kmsMainObj.put("publishDate",createReqVO.getPublishDate()!=null?createReqVO.getPublishDate().getTime():0L);
String createTimeStr = DateTimeFormatter.ISO_INSTANT
.withZone(ZoneOffset.UTC)
.format(Instant.now())
.replaceAll("\\.[0-9]+Z$", "Z");
kmsMainObj.put("createTime", createTimeStr); // 时间戳格式
UpdateRequest updateRequest = new UpdateRequest(indexName, id+"").doc(kmsMainObj);
updateRequest.docAsUpsert(true);
UpdateResponse updateResponse = null;
@ -120,7 +134,7 @@ public class EsearchUtils {
// 设置排序规则
String sortBy = kmsSearchDto.getSortBy();
SortOrder sortType = kmsSearchDto.getSortType().equals("1") ? SortOrder.DESC : SortOrder.ASC;
//searchSourceBuilder.sort(sortBy, sortType);
searchSourceBuilder.sort(sortBy, sortType);
SearchRequest searchRequest = new SearchRequest(indexName);
searchRequest.source(searchSourceBuilder);