Elasticsearch基于Client 写了个demo(增删改查)
最近项目用到了Elasticsearch存储一些资讯文档。好久没弄Elasticsearch,百度了一下,发现Elasticsearch版本变化挺大的,记得以前弄的时候还是5.XX版本,由于线上环境用的阿里云Elasticsearch7.1.4,所以下面代码是基于7.14的demo代码,其他版本没有测试,不扯了,开始上代码。
yml配置
elasticsearch:
user:
password:
host: 127.0.0.1:9200
pom配置
<!--es依赖 begin -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>7.4.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.4.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.4.0</version>
<scope>compile</scope>
</dependency>
<!--es依赖 end -->
配置类ESRestClient.java
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.jeedp.core.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Arrays;
import java.util.Objects;
@Slf4j
@Configuration
public class ESRestClient {
private static final int ADDRESS_LENGTH = 2;
private static final String HTTP_SCHEME = "http";
@Value("${elasticsearch.host}")
String ipAddress;
@Value("${elasticsearch.user}")
private String userName;
@Value("${elasticsearch.password}")
private String password;
@Bean
public RestClientBuilder restClientBuilder() {
String[] split = ipAddress.split(",");
HttpHost[] hosts = Arrays.stream(split)
.map(this::makeHttpHost)
.filter(Objects::nonNull)
.toArray(HttpHost[]::new);
return RestClient.builder(hosts);
}
@Bean(name = "highLevelClient")
public RestHighLevelClient highLevelClient(@Autowired RestClientBuilder restClientBuilder){
//配置身份验证
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
System.out.println("password:"+password+"------userName:"+userName);
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));
restClientBuilder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpAsyncClientBuilder) {
return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
});
return new RestHighLevelClient(restClientBuilder);
}
private HttpHost makeHttpHost(String str) {
assert StringUtils.isNotEmpty(str);
String[] address = str.split(":");
if (address.length == ADDRESS_LENGTH) {
String ip = address[0];
int port = Integer.parseInt(address[1]);
log.info("ES连接ip和port:{},{}", ip, port);
return new HttpHost(ip, port, HTTP_SCHEME);
} else {
log.error("传入的ip参数不正确!");
return null;
}
}
}
工具类ESUtil.java
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
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.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.jeedp.core.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Component
@Slf4j
public class ESUtil {
@Qualifier("highLevelClient")
@Autowired
private RestHighLevelClient rhlClient;
private static RestHighLevelClient client;
/**
* spring容器初始化的时候执行该方法
*/
@PostConstruct
public void init() {
client = this.rhlClient;
}
/**
* 查询数据
*
* @param index 索引
* @param id id
*/
public static GetResponse queyDataById(String index, String id) {
try {
GetRequest request= new GetRequest(index).id(id);
GetResponse response = client.get(request, RequestOptions.DEFAULT);
log.info("索引:{},数据查询,返回结果:{},id:{}", index, JsonUtils.toJson(response), id);
return response;
} catch (IOException e) {
e.printStackTrace();
log.error("查询数据失败,index:{},id:{}", index, id);
}
return null;
}
/**
* 添加数据
*
* @param content 数据内容
* @param index 索引
* @param id id
*/
public static String addData(XContentBuilder content, String index, String id) {
String Id = null;
try {
IndexRequest request = new IndexRequest(index).id(id).source(content);
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
Id = response.getId();
log.info("索引:{},数据添加,返回码:{},id:{}", index, response.status().getStatus(), Id);
} catch (IOException e) {
e.printStackTrace();
log.error("添加数据失败,index:{},id:{}", index, id);
}
return Id;
}
/**
* 修改数据
*
* @param content 修改内容
* @param index 索引
* @param id id
*/
public static String updateData(XContentBuilder content, String index, String id) {
String Id = null;
try {
UpdateRequest request = new UpdateRequest(index, id).doc(content);
UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
Id = response.getId();
log.info("数据更新,返回码:{},id:{}", response.status().getStatus(), Id);
} catch (IOException e) {
log.error("数据更新失败,index:{},id:{}", index, id);
}
return Id;
}
/**
* 批量插入数据
*
* @param index 索引
* @param list 批量增加的数据
*/
public static String insertBatch(String index, List<EsEntity> list) {
String state = null;
BulkRequest request = new BulkRequest();
list.forEach(item -> request.add(new IndexRequest(index)
.id(item.getId()).source(JSON.toJSONString(item.getData()), XContentType.JSON)));
try {
BulkResponse bulk = client.bulk(request, RequestOptions.DEFAULT);
int status = bulk.status().getStatus();
state = Integer.toString(status);
log.info("索引:{},批量插入{}条数据成功!", index, list.size());
} catch (IOException e) {
log.error("索引:{},批量插入数据失败", index);
}
return state;
}
/**
* 根据条件删除数据
*
* @param index 索引
* @param builder 删除条件
*/
public static void deleteByQuery(String index, QueryBuilder builder) {
DeleteByQueryRequest request = new DeleteByQueryRequest(index);
request.setQuery(builder);
//设置此次删除的最大条数
request.setBatchSize(1000);
try {
client.deleteByQuery(request, RequestOptions.DEFAULT);
} catch (IOException e) {
log.error("根据条件删除数据失败,index:{}", index);
}
}
/**
* 根据id删除数据
*
* @param index 索引
* @param id id
*/
public static String deleteById(String index, String id) {
String state = null;
DeleteRequest request = new DeleteRequest(index, id);
try {
DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
int status = response.status().getStatus();
state = Integer.toString(status);
log.info("索引:{},根据id{}删除数据:{}", index, id, JSON.toJSONString(response));
} catch (IOException e) {
log.error("根据id删除数据失败,index:{},id:{}", index, id);
}
return state;
}
/**
* 根据条件查询数据
*
* @param index 索引
* @param startPage 开始页
* @param pageSize 每页条数
* @param sourceBuilder 查询返回条件
* @param queryBuilder 查询条件
*/
public static List<Map<String, Object>> SearchDataPage(String index, int startPage, int pageSize,
SearchSourceBuilder sourceBuilder, QueryBuilder queryBuilder) {
SearchRequest request = new SearchRequest(index);
//设置超时时间
sourceBuilder.timeout(new TimeValue(120, TimeUnit.SECONDS));
//设置是否按匹配度排序
sourceBuilder.explain(true);
//加载查询条件
sourceBuilder.query(queryBuilder);
//设置分页
sourceBuilder.from((startPage - 1) * pageSize).size(pageSize);
log.info("查询返回条件:" + sourceBuilder.toString());
request.source(sourceBuilder);
try {
SearchResponse searchResponse = client.search(request, RequestOptions.DEFAULT);
//System.out.println("查询结果"+JsonUtils.toJson(searchResponse));
long totalHits = searchResponse.getHits().getTotalHits().value;
log.info("共查出{}条记录", totalHits);
RestStatus status = searchResponse.status();
if (status.getStatus() == 200) {
List<Map<String, Object>> sourceList = new ArrayList<>();
for (SearchHit searchHit : searchResponse.getHits().getHits()) {
Map<String, Object> sourceAsMap = searchHit.getSourceAsMap();
log.info("结果得分:" + searchHit.getScore());
sourceList.add(sourceAsMap);
}
return sourceList;
}
} catch (IOException e) {
log.error("条件查询索引{}时出错", index);
}
return null;
}
public static List<Map<String, Object>> SearchDataPageAndSource(String index, int startPage, int pageSize,
SearchSourceBuilder sourceBuilder, QueryBuilder queryBuilder) {
SearchRequest request = new SearchRequest(index);
//设置超时时间
sourceBuilder.timeout(new TimeValue(120, TimeUnit.SECONDS));
//设置是否按匹配度排序
sourceBuilder.explain(true);
//加载查询条件
sourceBuilder.query(queryBuilder);
//设置分页
sourceBuilder.from((startPage - 1) * pageSize).size(pageSize);
log.info("查询返回条件:" + sourceBuilder.toString());
request.source(sourceBuilder);
try {
SearchResponse searchResponse = client.search(request, RequestOptions.DEFAULT);
//System.out.println("查询结果"+JsonUtils.toJson(searchResponse));
long totalHits = searchResponse.getHits().getTotalHits().value;
log.info("共查出{}条记录", totalHits);
RestStatus status = searchResponse.status();
if (status.getStatus() == 200) {
List<Map<String, Object>> sourceList = new ArrayList<>();
for (SearchHit searchHit : searchResponse.getHits().getHits()) {
Map<String, Object> sourceAsMap = searchHit.getSourceAsMap();
log.info("结果得分:" + searchHit.getScore());
sourceAsMap.put("score",searchHit.getScore());
sourceList.add(sourceAsMap);
}
// 对查询到的分数进行缩放处理
Float[] orgData = new Float[sourceList.size()];
for (int i = 0; i < sourceList.size(); i++) {
orgData[i] = (Float) sourceList.get(i).get("score");
}
Float[] newData = new Float[sourceList.size()];
// if (pageSize==5) {
newData = dataZoom(orgData, 50, 100);
// } else {
// long pages = searchResponse.getHits().getTotalHits().value / pageSize; // 有多少页
// pages = pages == 0 ? 2 : pages;
// long avePages = 100 / pages; //每页的区间
//
// newData = dataZoom(orgData, (int) (100 - ((startPage + 1) * avePages)), (int) (100 - ((startPage) * avePages)));
// }
for (int i = 0; i < sourceList.size(); i++) {
sourceList.get(i).put("score", newData[i]);
}
return sourceList;
}
} catch (IOException e) {
log.error("条件查询索引{}时出错", index);
}
return null;
}
private static Float[] dataZoom(Float[] orgData, int minSection, int maxSection) {
Float[] newData = new Float[orgData.length];
for (int i = 0; i < orgData.length; i++) {
Float tmp ;
// 数据归一化
if(0==(orgData[0] - orgData[orgData.length - 1])){
newData[i] =new Float(maxSection);
continue;
}
tmp = (orgData[i] - orgData[orgData.length - 1]) / (orgData[0] - orgData[orgData.length - 1]);
// 数据缩放
newData[i] = minSection + tmp * (maxSection - minSection);
}
return newData;
}
public static EsPage<Map<String, Object>> SearchDataEsPage(String index, int startPage, int pageSize,
SearchSourceBuilder sourceBuilder, QueryBuilder queryBuilder) {
EsPage page=new EsPage();
SearchRequest request = new SearchRequest(index);
//设置超时时间
sourceBuilder.timeout(new TimeValue(120, TimeUnit.SECONDS));
//设置是否按匹配度排序
sourceBuilder.explain(true);
//加载查询条件
sourceBuilder.query(queryBuilder);
//设置分页
sourceBuilder.from((startPage - 1) * pageSize).size(pageSize);
log.info("查询返回条件:" + sourceBuilder.toString());
request.source(sourceBuilder);
try {
SearchResponse searchResponse = client.search(request, RequestOptions.DEFAULT);
//System.out.println("查询结果"+JsonUtils.toJson(searchResponse));
long totalHits = searchResponse.getHits().getTotalHits().value;
log.info("共查出{}条记录", totalHits);
page.setTotal(totalHits);
RestStatus status = searchResponse.status();
if (status.getStatus() == 200) {
List<Map<String, Object>> sourceList = new ArrayList<>();
for (SearchHit searchHit : searchResponse.getHits().getHits()) {
Map<String, Object> sourceAsMap = searchHit.getSourceAsMap();
log.info("结果得分:" + searchHit.getScore());
sourceList.add(sourceAsMap);
}
page.setList(sourceList);
return page;
}
} catch (IOException e) {
log.error("条件查询索引{}时出错", index);
}
return null;
}
}
分页page类(EsPage.java)
import java.util.List;
public class EsPage<T> {
private long total;
private List<T> list;
public long getTotal() {
return total;
}
public void setTotal(long total) {
this.total = total;
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
}
实体类(EsArticle.java)
import java.time.LocalDateTime;
public class EsArticle{
private String id;
private String title;
private String content;
private String artircleStatus;
private String articleCategory;
private Long updateDate;
private String abstractContent;
private String tags;
private Integer readNum;
private String image;
private String recommend;
public String getRecommend() {
return recommend;
}
public void setRecommend(String recommend) {
this.recommend = recommend;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public Integer getReadNum() {
return readNum;
}
public void setReadNum(Integer readNum) {
this.readNum = readNum;
}
public String getAbstractContent() {
return abstractContent;
}
public void setAbstractContent(String abstractContent) {
this.abstractContent = abstractContent;
}
public String getTags() {
return tags;
}
public void setTags(String tags) {
this.tags = tags;
}
public String getArtircleStatus() {
return artircleStatus;
}
public void setArtircleStatus(String artircleStatus) {
this.artircleStatus = artircleStatus;
}
public String getArticleCategory() {
return articleCategory;
}
public void setArticleCategory(String articleCategory) {
this.articleCategory = articleCategory;
}
public Long getUpdateDate() {
return updateDate;
}
public void setUpdateDate(Long updateDate) {
this.updateDate = updateDate;
}
private float score;
public float getScore() {
return score;
}
public void setScore(float score) {
this.score = score;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
Service类-(EsArticleService.java)
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.jeedp.core.utils.JsonUtils;
import org.jeedp.core.utils.StringUtils;
import org.jeedp.core.vo.ApiResult;
import org.jeedp.system.es.entity.CorporateName;
import org.jeedp.system.es.entity.EsDoctorArticle;
import org.jeedp.system.es.util.ESUtil;
import org.jeedp.system.es.util.EsPage;
import org.jeedp.system.es.vo.QueryDoctorArticleRequest;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Slf4j
@Service
public class EsArticleService {
/**
* 添加
*
* @return
*/
public ApiResult<String> add(EsDoctorArticle article) {
ApiResult<String> res = checkcommon(article);
if (!"0000".equals(res.getError_code())) {
return res;
}
String Id = null;
String index = "doctor_article";
String id = article.getId();
try {
XContentBuilder builder = XContentFactory.jsonBuilder()
.startObject()
.field("id",article.getId())
.field("title", article.getTitle())
.field("content", article.getContent())
.field("artircleStatus", article.getArtircleStatus())
.field("articleCategory", article.getArticleCategory())
.field("updateDate", article.getUpdateDate())
.field("abstractContent", article.getAbstractContent())
.field("tags", article.getTags())
.field("readNum", article.getReadNum())
.field("image", article.getImage())
.field("recommend", article.getRecommend())
.endObject();
Id = ESUtil.addData(builder, index, id);
log.info("add a DoctorArticle:id=" + Id + ";title=" + article.getTitle());
res.setError_code("0000");
res.setMessage("存入成功");
res.setData(article.getId());
return res;
} catch (IOException e) {
log.error("索引:{},id:{},添加数据失败", index, id);
e.printStackTrace();
res.setError_code("0001");
res.setMessage("存入失败");
res.setData(article.getId());
return res;
}
}
/**
* 局部更新
* @return
*/
public ApiResult<String> update( EsDoctorArticle article) {
ApiResult<String> res=checkcommon(article);
if(!"0000".equals(res.getError_code())){
return res;
}
String Id = null;
String index = "doctor_article";
String id =article.getId();
try {
XContentBuilder builder = XContentFactory.jsonBuilder()
.startObject()
.field("id", article.getId())
.field("title", article.getTitle())
.field("content", article.getContent())
.field("artircleStatus", article.getArtircleStatus())
.field("articleCategory", article.getArticleCategory())
.field("updateDate", article.getUpdateDate())
.field("abstractContent", article.getAbstractContent())
.field("tags", article.getTags())
.field("readNum", article.getReadNum())
.field("image", article.getImage())
.field("recommend", article.getRecommend())
.endObject();
Id = ESUtil.updateData(builder, index, id);
System.err.println("update a CorporateName");
res.setError_code("0000");
res.setMessage("更新成功");
res.setData(article.getId());
return res;
} catch (IOException e) {
log.error("索引:{},id:{},添加数据失败", index, id);
e.printStackTrace();
res.setError_code("0001");
res.setMessage("更新失败");
res.setData(article.getId());
return res;
}
}
/**
* 根据id查询
* @return
*/
public ApiResult<EsDoctorArticle> queyDataById( String articleId) {
ApiResult<EsDoctorArticle> res=new ApiResult<>();
String index = "doctor_article";
String id =articleId;
try {
GetResponse response = ESUtil.queyDataById(index, id);
EsDoctorArticle article=new EsDoctorArticle();
article.setReadNum(Integer.parseInt(response.getSource().get("readNum").toString()));
article.setUpdateDate(Long.parseLong(response.getSource().get("updateDate").toString()));
article.setTags(response.getSource().get("tags").toString());
article.setArtircleStatus(response.getSource().get("artircleStatus").toString());
article.setArticleCategory(response.getSource().get("articleCategory").toString());
article.setAbstractContent(response.getSource().get("abstractContent").toString());
article.setTitle(response.getSource().get("title").toString());
article.setContent(response.getSource().get("content").toString());
article.setImage(response.getSource().get("image").toString());
article.setRecommend(response.getSource().get("recommend").toString());
article.setId(response.getId());
res.setData(article);
return res;
} catch (Exception e) {
e.printStackTrace();
res.setError_code("0001");
res.setMessage("查询异常");
return res;
}
}
/**
* 删除
*
* @return
*/
public ApiResult<String> delete(EsDoctorArticle article) {
ApiResult<String> res = checkcommon(article);
String s;
String index = "doctor_article";
if (!"0000".equals(res.getError_code())) {
return res;
}
String id = article.getId();
s = ESUtil.deleteById(index, id);
System.err.println("delete a DoctorArticle");
res.setError_code("0000");
res.setMessage("删除成功");
res.setData(article.getId());
return res;
}
/**
* 查询
*/
public ApiResult<EsPage<EsDoctorArticle>> query(QueryDoctorArticleRequest query) {
ApiResult<EsPage<EsDoctorArticle>> res = new ApiResult<EsPage<EsDoctorArticle>>();
String index = "doctor_article";
String keyWord = query.getKeyWord();
int pageNum = query.getPage();
int pageSize = query.getSize();
String articleCategory=query.getArticleCategory();
String artircleStatus=query.getArtircleStatus();
String updateDate=query.getUpdateDate();
if (0 == pageNum) {
res.setError_code("0001");
res.setMessage("page必须>=1");
return res;
}
if (0 == pageSize) {
res.setError_code("0001");
res.setMessage("size必须>=1");
return res;
}
int pagenew = pageNum - 1;
if (pagenew < 0) {
res.setError_code("0001");
res.setMessage("page必须>=1");
return res;
}
BoolQueryBuilder builder = QueryBuilders.boolQuery();
//builder下有must、should以及mustNot 相当于sql中的and、or以及not
if(!StringUtils.isEmpty(keyWord)){
BoolQueryBuilder builderkeword = QueryBuilders.boolQuery();
builderkeword.should(QueryBuilders.matchQuery("title", keyWord)).should(QueryBuilders.matchQuery("content",keyWord));
builder.must(builderkeword);
}
if(!StringUtils.isEmpty(articleCategory)){
builder.must(QueryBuilders.termsQuery("articleCategory",articleCategory));
}
if(!StringUtils.isEmpty(artircleStatus)){
builder.must(QueryBuilders.termsQuery("artircleStatus",artircleStatus));
}
if(!StringUtils.isEmpty(updateDate)){
try {
SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date startTime=format2.parse(updateDate+" 00:00:00");
Date endTime=format2.parse(updateDate+" 23:59:59");
RangeQueryBuilder rangeQueryBuilder= QueryBuilders.rangeQuery("updateDate").gt(startTime.getTime()).lt(endTime.getTime());
builder.must(rangeQueryBuilder);
}catch (ParseException e){
res.setError_code("0001");
res.setMessage("updateDate格式错误:"+updateDate);
return res;
}
}
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.sort("updateDate", SortOrder.DESC);
EsPage<Map<String, Object>> page = ESUtil.SearchDataEsPage(index, pageNum, pageSize, sourceBuilder, builder);
List<Map<String, Object>> list=page.getList();
List<EsDoctorArticle> listres = new ArrayList<>();
for (Map map : list) {
String json = JsonUtils.toJson(map);
EsDoctorArticle article = JsonUtils.toObject(json, EsDoctorArticle.class);
listres.add(article);
}
log.info(JsonUtils.toJson(list));
EsPage<EsDoctorArticle> articleEsPage=new EsPage<>();
articleEsPage.setTotal(page.getTotal());
articleEsPage.setList(listres);
res.setError_code("0000");
res.setMessage("成功");
res.setData(articleEsPage);
return res;
}
private ApiResult<String> checkcommon(EsDoctorArticle article) {
ApiResult<String> response = new ApiResult<String>();
String id = article.getId();
if (null == id || "".equals(id)) {
response.setError_code("0001");
response.setMessage("id不能为空");
return response;
}
response.setError_code("0000");
response.setMessage("校验成功");
return response;
}
}
其他类
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel("返回json")
public class ApiResult<T> {
@ApiModelProperty(value = "error_code(0000表示成功,其他失败)" ,dataType = "String")
private String error_code;
@ApiModelProperty(value = "描述信息" ,dataType = "String")
private String message;
@ApiModelProperty(value = "返回结果" )
private T data;
public String getError_code() {
return error_code;
}
public void setError_code(String error_code) {
this.error_code = error_code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public ApiResult(String error_code,String message){
this.error_code=error_code;
this.message =message;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public ApiResult(){
this.error_code="0000";
this.message ="请求成功";
}
}