通过JestClient实现ES的updateByQuery

一、通过jestClient连接elasticSearch

连接es有很多种方式,大多数使用情况采用封装好的client,里面有很多现成的API能够调用,但是Es的版本更新太快,每个版本都兼容性很差,但是通过jestClient操作es,再写类似于原生sql的es query查询语句,兼容性较好,这样即使es 在java中引用的版本更新,也能够实现查询等操作。

1.先建立一个jestClient

import io.searchbox.client.JestClient;

import io.searchbox.client.JestClientFactory;

import io.searchbox.client.config.HttpClientConfig;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.stereotype.Component;



@Component

public class JestClientUtil {

private static String serverUri = "http://127.0.0.1:9200";

public static JestClient getClient(){

JestClient jestClient = null;

try{

JestClientFactory factory = new JestClientFactory();

HttpClientConfig.Builder httpClientConfig = new HttpClientConfig.Builder(serverUri).multiThreaded(true).connTimeout(30000).readTimeout(30000);

factory.setHttpClientConfig(httpClientConfig.build());

jestClient = factory.getObject();

}catch (Exception e){

e.printStackTrace();

}

return jestClient;

}



@Value("${elasticsearch.serverUri}")

public void setServerUri(String serverUri) {

JestClientUtil.serverUri = serverUri;

}

}

可以通过配置文件引入Uri的地址

2.通过java代码操作es

public boolean updateEsLog(LogDTO document) {
JestClient client = JestClientUtil.getClient();
String BuilderStr = "{"+
" \"script\": { " +
"\"source\": \"ctx._source['"+ "mailNo" +"']='" +document.getMailNo() +"'\" "+
"}," +
"\"query\": {"+
"\"match\": {"+
"\"orderNo\": \"" + document.getOrderNo() +"\""+
"}"+
"}"+
"}";
UpdateByQuery updateByQuery = new UpdateByQuery.Builder(BuilderStr).addIndex(INDEX_NAME).build();
UpdateByQueryResult result = null;
try {
result = client.execute(updateByQuery);
long updatedCount = result.getUpdatedCount();
if(result.isSucceeded() && updatedCount != 0L){
return true;
}
} catch (IOException e) {
logger.error("ES更新log异常Exception:" , e);
}
return false;
}

 

通过穿插script字符串脚本语言,来操作jestClient,实现updateByQuery。其中两个动态参数可以根据需求自行更改成自己想要的参数值。

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值