在使用 RestHighLevelClient的过程中发现,它已经标记为过时了。
在 Elasticsearch7.15版本之后,Elasticsearch官方将它的高级客户端 RestHighLevelClient标记为弃用状态。
同时推出了全新的 Java API客户端 Elasticsearch Java API Client,该客户端也将在 Elasticsearch8.0及以后版本中成为官方推荐使用的客户端。
由于项目中使用的是低版本的ES。所有有必要记录一下它的基本使用。
参考官方AP文档:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.17/java-rest-high-supported-apis.html
一、将连接信息封装成工具类
引入依赖:
<!--与ES安装版本保持一致-->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.17.4</version>
</dependency>
新建工具类,简单封装一下。
public class ESUtil {
private static RestHighLevelClient restHighLevelClient;
static {
RestClientBuilder restClientBuilder = RestClient.builder(new HttpHost("192.168.xxx.xxx", 9200, "http"));
restHighLevelClient = new RestHighLevelClient(restClientBuilder);
System.out.println("==========Connect to Elasticsearch successfully================");
}
public static RestHighLevelClient getRestHighLevelClient() {
return restHighLevelClient;
}
@Test
public void test(){
RestHighLevelClient restHighLevelClient = ESUtil.getRestHighLevelClient();
System.out.println(restHighLevelClient);
}
}
二、索引操作
1、创建索引
1.1 默认创建索引
// 创建索引(PUT /索引名称)
@Test
public void testCreateIndex() throws IOException {
// 1、获取客户端
RestHighLevelClient restHighLevelClient = ESUtil.getRestHighLevelClient();
// 2、创建索引请求
CreateIndexRequest indexRequest = new CreateIndexRequest("db_index1");
// 3、客户端执行请求 IndicesClient,请求后获得响应
CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(indexRequest, RequestOptions.DEFAULT);
System.out.println(createIndexResponse.index());
System.out.println(createIndexResponse.isAcknowledged());
}
查看索引信息:
{
"db_index1" : {
"aliases" : { },
"mappings" : {
"properties" : {
"age" : {
"type" : "long"
},
"createTime" : {
"type" : "long"
},
"email" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"height" : {
"type" : "float"
},
"id" : {
"type" : "long"
},
"updateTime" : {
"type" : "long"
},
"userName" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"version" : {
"type" : "long"
}
}
},
"settings" : {
"index" : {
"routing" : {
"allocation" : {
"include" : {
"_tier_preference" : "data_content"
}
}
},
"number_of_shards" : "1",
"provided_name" : "db_index1",
"creation_date" : "1661680036350",
"number_of_replicas" : "1",
"uuid" : "fwgaTuOBRkKr092qLRTHsw",
"version" : {
"created" : "7170499"
}
}
}
}
}
1.2 指定参数创建索引
/**
* 创建索引,使用ik分词器
* @throws IOException
*/
@Test
public void createIndex() throws IOException {
RestHighLevelClient restHighLevelClient = ESUtil.getRestHighLevelClient();
CreateIndexRequest request = new CreateIndexRequest("db_index2");
// 设置setting
request.settings(Settings.builder()
.put("index.number_of_shards", 3)
.put("index.number_of_replicas", 2)
.put("index.analysis.analyzer.default.type", "ik_max_word") //指定 ik分词器作为默认分词器
);
// 设置mapping
String mapping = "{\n" +
" \"properties\" : {\n" +
" \"age\" : {\n" +
" \"type\" : \"long\"\n" +
" },\n" +
" \"createTime\" : {\n" +
" \"type\" : \"long\"\n" +
" },\n" +
" \"email\" : {\n" +
" \"type\" : \"text\",\n" +
" \"fields\" : {\n" +
" \"keyword\" : {\n" +
" \"type\" : \"keyword\",\n" +
" \"ignore_above\" : 256\n" +
" }\n" +
" }\n" +
" },\n" +
" \"height\" : {\n" +
" \"type\" : \"float\"\n" +
" },\n" +
" \"id\" : {\n" +
" \"type\" : \"long\"\n" +
" },\n" +
" \"updateTime\" : {\n" +
" \"type\" : \"long\"\n" +
" },\n" +
" \"userName\" : {\n" +
" \"type\" : \"text\",\n" +
" \"fields\" : {\n" +
" \"keyword\" : {\n" +
" \"type\" : \"keyword\",\n" +
" \"ignore_above\" : 256\n" +
" }\n" +
" }\n" +
" },\n" +
" \"version\" : {\n" +
" \"type\" : \"long\"\n" +
" }\n" +
" }\n" +
" }";
/**
* 由于是过时的方法,则 mapping方法需要加_doc。
*/
request.mapping("_doc", mapping, XContentType.JSON);
CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
System.out.println(createIndexResponse.index());
System.out.println(createIndexResponse.isAcknowledged());
}
查看索引信息:文章来源:https://www.toymoban.com/news/detail-503298.html
{
"db_index2" : {
"aliases" : { },
"mappings" : {
"properties" : {
"age" : {
"type" : "long"
},
"createTime" : {
"type" : "long"
},
"email" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"height" : {
"type" : "float"
},
"id" : {
"type" : "long"
},
"updateTime" : {
"type" : "long"
},
"userName" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"version" : {
"type" : "long"
}
}
},
"settings" : {
"index" : {
"routing" : {
"allocation" : {
"include" : {
"_tier_preference" : "data_content"
}
}
},
"number_of_shards" : "3",
"provided_name" : "db_index2",
"creation_date" : "1661692389533",
"analysis" : {
"analyzer" : {
"default" : {
"type" : "ik_max_word"
}
}
},
"number_of_replicas" : "2",
"uuid" : "3o0lJVxYT5S7ycg36nrP5A",
"version" : {
"created" : "7170499"
}
}
}
}
}
2、查询索引
// 查询索引(GET /索引名称/参数)
@Test
public void testGetIndex() throws IOException {
RestHighLevelClient restHighLevelClient = ESUtil.getRestHighLevelClient();
GetIndexRequest indexRequest = new GetIndexRequest("db_index1");
//获取
GetIndexResponse indexResponse = restHighLevelClient.indices().get(indexRequest, RequestOptions.DEFAULT);
System.out.println(indexResponse.getAliases());
System.out.println(indexResponse.getMappings());
System.out.println(indexResponse.getSettings());
}
3、判断索引是否存在
// 判断索引是否存在
@Test
public void testExistIndex() throws IOException {
RestHighLevelClient restHighLevelClient = ESUtil.getRestHighLevelClient();
GetIndexRequest indexRequest = new GetIndexRequest("db_index1");
//存在
boolean exists = restHighLevelClient.indices().exists(indexRequest, RequestOptions.DEFAULT);
System.out.println(exists);
}
4、删除索引
// 删除索引(DELETE /索引名称)
@Test
public void testDeleteIndex() throws IOException {
RestHighLevelClient restHighLevelClient = ESUtil.getRestHighLevelClient();
DeleteIndexRequest request = new DeleteIndexRequest("db_index2");
// 删除
AcknowledgedResponse delete = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
System.out.println(delete.isAcknowledged());
}
三、文档操作
@Data
@ToString
public class UserVO {
private Long id;
private String userName;
private Integer age;
private Double height;
private String email;
private Date createTime;
private Date updateTime;
private Integer enabled;
private Integer version;
}
1、添加文档
/**
* 添加文档(POST /索引名称/[_doc | _create ]/id)。如果 id已存在,则会全量修改。
*
* @throws IOException
*/
@Test
public void testAddDocument() throws IOException {
// 1、获取客户端
RestHighLevelClient restHighLevelClient = ESUtil.getRestHighLevelClient();
// 2、构建文档数据
UserVO userVO = new UserVO();
userVO.setId(1L);
userVO.setUserName("赵云2");
userVO.setAge(18);
userVO.setCreateTime(new Date());
userVO.setUpdateTime(new Date());
userVO.setEmail("ss.com");
userVO.setVersion(1);
userVO.setHeight(12D);
// 创建请求
IndexRequest indexRequest = new IndexRequest("db_index1"); //索引不存在时,会自动创建
indexRequest.id(userVO.getId().toString());
indexRequest.timeout(TimeValue.timeValueSeconds(1));
indexRequest.timeout("1s");
// 3、将文档数据放入请求 json
indexRequest.source(JSON.toJSONString(userVO), XContentType.JSON);
// 4、客户端发送请求 , 获取响应的结果
IndexResponse indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
System.out.println(indexResponse.toString()); //
System.out.println(indexResponse.status()); // 对应命令返回的状态CREATED/OK
}
2、获取文档
// 获得文档记录(get //索引名称/doc/id)
@Test
public void testGetDocument() throws IOException {
RestHighLevelClient restHighLevelClient = ESUtil.getRestHighLevelClient();
GetRequest getRequest = new GetRequest("db_index1", "1");
//获取
GetResponse getResponse = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
System.out.println(getResponse.getSourceAsString()); // 打印文档的内容
System.out.println(getResponse); // 返回的全部内容和命令式一样的
}
3、判断文档是否存在
// 判断文档是否存在
@Test
public void testIsExists() throws IOException {
RestHighLevelClient restHighLevelClient = ESUtil.getRestHighLevelClient();
GetRequest getRequest = new GetRequest("db_index1", "1");
// 不获取返回的 _source 的上下文了
getRequest.fetchSourceContext(new FetchSourceContext(false));
getRequest.storedFields("_none_");
// 存在
boolean exists = restHighLevelClient.exists(getRequest, RequestOptions.DEFAULT);
System.out.println(exists);
}
4、增量更新文档记录
/**
* 增量更新文档记录(POST /索引名称/_update/id),文档必须存在。
* @throws IOException
*/
@Test
public void testUpdateRequest() throws IOException {
RestHighLevelClient restHighLevelClient = ESUtil.getRestHighLevelClient();
// 构建文档数据
UserVO userVO = new UserVO();
userVO.setId(1L);
userVO.setUserName("赵云update");
userVO.setHeight(1.88D);
userVO.setCreateTime(new Date());
// 根据文档id修改
UpdateRequest updateRequest = new UpdateRequest("db_index1", userVO.getId().toString());
updateRequest.timeout("1s");
// 将文档数据放入请求 json
updateRequest.doc(JSON.toJSONString(userVO), XContentType.JSON);
// 修改
UpdateResponse updateResponse = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
System.out.println(updateResponse.status()); // 对应命令返回的状态OK
}
5、删除文档
// 删除文档记录(DELETE //索引名称/_doc/id)
@Test
public void testDeleteRequest() throws IOException {
RestHighLevelClient restHighLevelClient = ESUtil.getRestHighLevelClient();
DeleteRequest request = new DeleteRequest("db_index1", "1");
request.timeout("1s");
// 删除
DeleteResponse deleteResponse = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
System.out.println(deleteResponse.status()); // 对应命令返回的状态OK
}
6、批量操作文档数据
@Test
public void testBulkRequest() throws IOException {
RestHighLevelClient restHighLevelClient = ESUtil.getRestHighLevelClient();
// 构建批处理请求
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.timeout("10s");
for (int i = 1; i <= 5; i++) {
UserVO userVO = new UserVO();
userVO.setId(1L);
userVO.setUserName("赵云batch" + i );
userVO.setHeight(1.88D);
userVO.setAge(10 + i);
userVO.setCreateTime(new Date());
// 批量添加/更新和批量删除,只需要修改对应的请求即可
IndexRequest indexRequest = new IndexRequest("db_index2");
indexRequest.id(userVO.getId().toString());
indexRequest.source(JSON.toJSONString(userVO), XContentType.JSON);
bulkRequest.add(indexRequest);
}
//执行批处理请求
BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
System.out.println(bulkResponse.hasFailures()); // 是否失败,返回 false 代表 成功!
}
– 求知若饥,虚心若愚。文章来源地址https://www.toymoban.com/news/detail-503298.html
到了这里,关于Java 操作RestHighLevelClient基本使用的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!