本文示例es版本为6.4.3,理论上支持到最新的7.x
es在6.3.x版本后不支持transport版本,改为支持restClient, 底层调用依旧为httpclient,只是基于es请求包装了一层。
restClient分为hign版本和low版本,暂时只调试了hign版本
经过一天的调试,写了一个简单的demo记录一下。
疑问:restClient底层依旧为长连接,那么我如果不长期close情况的下,会不会造成什么影响呢
pom:
<!-- es pom start-->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>${es.version}</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>${es.version}</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>${es.version}</version>
</dependency>
<!--如果项目本身的依赖低于该版本时,restClient会创建失败-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
<!-- es pom emd-->
demo代码
/**
* @Desc:
* @Auth: li
* @Date: 2020/9/1
**/
@Component
public class RestClient {
protected static final Logger LOG = LoggerFactory.getLogger(RestClient.class);
/**
* 相关配置信息Test
*/
public static String URL = "127.0.0.1";
public static int PORT = 9300;
public static String USERNAME = "es-test";
public static String PASSWORD = "xxx";
private static RestHighLevelClient client;
@PostConstruct
public void init() {
client = getClient();
}
public RestHighLevelClient getClient() {
if (Objects.nonNull(client)) {
return client;
}
synchronized (RestClient.class) {
try {
RestClientBuilder builder = org.elasticsearch.client.RestClient.builder(new HttpHost(URL, PORT, "http"));
//没有用户名 密码的话 这块可以忽略 直接调用最后一行
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(USERNAME, PASSWORD));
builder.setHttpClientConfigCallback(f -> f.setDefaultCredentialsProvider(credentialsProvider));
client = new RestHighLevelClient(builder);
} catch (Exception e) {
e.printStackTrace();
}
return client;
}
}
/**
* getApi
*
* @param index
* @param type
* @param id
* @param includes 返回的字段集合 不能为空
* @throws Exception
*/
public Map<String, Object> getDocById(String index, String type, String id, List<String> includes) throws Exception {
GetRequest request = new GetRequest(index, type, id);
//可选参数设置
request.fetchSourceContext(FetchSourceContext.DO_NOT_FETCH_SOURCE);
FetchSourceContext fetchSourceContext = new FetchSourceContext(true, includes.toArray(new String[0]), null);
request.fetchSourceContext(fetchSourceContext);
//同步执行
GetResponse getResponse = getClient().get(request, RequestOptions.DEFAULT);
LOG.debug("开始获取doc信息,index-{},id-{},result-{}", index, id, JSON.toJSONString(getResponse.getSource()));
return getResponse.getSource();
}
/**
* 删除doc
*
* @param index
* @param type
* @param id
* @throws Exception
*/
public void deleteDocById(String index, String type, String id) throws Exception {
DeleteRequest request = new DeleteRequest(index, type, id);
DeleteResponse deleteResponse = getClient().delete(request, RequestOptions.DEFAULT);
LOG.debug("开始删除数据id-{},返回值-{}", id, JSON.toJSONString(deleteResponse.getResult()));
}
/**
* 新增doc
*
* @param index
* @param type
* @param jsonString
* @return
* @throws Exception
*/
public String addDoc(String index, String type, String jsonString) throws Exception {
IndexRequest indexRequest = new IndexRequest(index, type);
indexRequest.source(jsonString, XContentType.JSON);
//同步执行
IndexResponse indexResponse = getClient().index(indexRequest, RequestOptions.DEFAULT);
LOG.debug("新增doc,index-{},context-{},resultId-{}", index, jsonString, indexResponse.getId());
return indexResponse.getId();
}
/**
* 更新doc
*
* @param index
* @param type
* @param id
* @param updateMap
* @return
* @throws Exception
*/
public void updateDocById(String index, String type, String id, Map<String, String> updateMap) throws Exception {
UpdateRequest updateRequest = new UpdateRequest(index, type, id);
updateRequest.doc(updateMap, XContentType.JSON);
//同步执行
UpdateResponse updateResponse = getClient().update(updateRequest, RequestOptions.DEFAULT);
LOG.debug("更新doc,index-{},id-{},updateJson-{}", index, id, JSON.toJSONString(updateMap));
}
public static void main(String[] args) throws Exception {
Map<String, Object> docById = new RestClient().getDocById("test202002111215", "doc", "97x3MnABuFEFg1xQqGnQ", Lists.newArrayList("title", "url", "remark"));
System.out.println(JSON.toJSONString(docById));
}
public <T> List<T> select(String key,String value,Integer size,Class<T> T){
SearchRequest request = new SearchRequest();
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.termQuery(key, value));
if(Objects.nonNull(size)) {
searchSourceBuilder.from(0);
searchSourceBuilder.size(size);
}
request.source(searchSourceBuilder);
List<T> result = Lists.newArrayList();
try {
SearchResponse response = getClient().search(request, RequestOptions.DEFAULT);
SearchHit[] results = response.getHits().getHits();
for(SearchHit hit : results){
String sourceAsString = hit.getSourceAsString();
if (StringUtils.isNotBlank(sourceAsString)) {
result.add(JSONObject.parseObject(sourceAsString, T));
}
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}