一、通过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。其中两个动态参数可以根据需求自行更改成自己想要的参数值。