文章目录
RestAPI
ES官方提供了各种不同语言的客户端,用来操作ES。这些客户端的本质就是组装DSL语句,通过http请求发送给ES。官方文档地址:https://www.elastic.co/guide/en/elasticsearch/client/index.html
其中的Java Rest Client又包括两种:
- Java Low Level Rest Client
- Java High Level Rest Client
我这边以
Java High Level Rest Client
为例
初始化RestClient
在elasticsearch提供的API中,与elasticsearch一切交互都封装在一个名为RestHighLevelClient的类中,必须先完成这个对象的初始化,建立与elasticsearch的连接。
分为三步:
java
在这里插入代码片
1)引入es的RestHighLevelClient依赖:
xml
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
</dependency>
2)因为SpringBoot默认的ES版本是7.6.2,所以我们需要覆盖默认的ES版本:
xml
<properties>
<java.version>1.8</java.version>
<elasticsearch.version>7.12.1</elasticsearch.version>
</properties>
3)初始化RestHighLevelClient:
java
@Value("${es.url}")
private String esUrl;
@Bean
public RestHighLevelClient restHighLevelClient() {
return new RestHighLevelClient(RestClient.builder(
HttpHost.create(esUrl)
));
}
创建索引库
代码分为三步:
- 1)创建Request对象。因为是创建索引库的操作,因此Request是CreateIndexRequest。
- 2)添加请求参数,其实就是DSL的JSON参数部分。因为json字符串很长,这里是定义了静态字符串常量MAPPING_TEMPLATE,让代码看起来更加优雅。
- 3)发送请求,client.indices()方法的返回值是IndicesClient类型,封装了所有与索引库操作有关的方法。
java
public static final String MAPPING_TEMPLATE = "{\n" +
" \"mappings\":{\n" +
" \"properties\":{\n" +
" \"msgId\":{\n" +
" \"type\":\"keyword\",\n" +
" \"index\":\"true\"\n" +
" },\n" +
" \"money\":{\n" +
" \"type\":\"double\"\n" +
" },\n" +
" \"type\":{\n" +
" \"type\":\"integer\",\n" +
" \"index\":\"true\"\n" +
" },\n" +
" \"fromUserId\":{\n" +
" \"type\":\"integer\",\n" +
" \"index\":\"true\"\n" +
" },\n" +
" \"convType\":{\n" +
" \"type\":\"integer\",\n" +
" \"index\":\"true\"\n" +
" },\n" +
" \"convId\":{\n" +
" \"type\":\"integer\",\n" +
" \"index\":\"true\"\n" +
" },\n" +
" \"msgType\":{\n" +
" \"type\":\"integer\",\n" +
" \"index\":\"true\"\n" +
" },\n" +
" \"msg_body\":{\n" +
" \"type\":\"keyword\"\n" +
" },\n" +
" \"msgTime\":{\n" +
" \"type\":\"long\"\n" +
" },\n" +
" \"subMsgType\":{\n" +
" \"type\":\"keyword\",\n" +
" \"index\":\"true\"\n" +
" }\n" +
" }\n" +
" }\n" +
"}" ;
@BeforeEach
void setUp() {
this.client = new RestHighLevelClient(RestClient.builder(
HttpHost.create("http://192.168.123.114:9200")
));
}
@AfterEach
void tearDown() throws IOException {
this.client.close();
}
@Test
public void createMessageIndex() throws IOException {
CreateIndexRequest request = new CreateIndexRequest("message");
// 2.准备请求的参数:DSL语句
request.source(MAPPING_TEMPLATE, XContentType.JSON);
// 3.发送请求
CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
log.info(GsonUtil.toJson(createIndexResponse));
}
删除索引库
java
@Test
void testDeleteMessageIndex() throws IOException {
// 1.创建Request对象
DeleteIndexRequest request = new DeleteIndexRequest("message");
// 2.发送请求
client.indices().delete(request, RequestOptions.DEFAULT);
}
判断索引库是否存在
java
@Test
void testExistsMessageIndex() throws IOException {
// 1.创建Request对象
GetIndexRequest request = new GetIndexRequest("message");
// 2.发送请求
boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
// 3.输出
System.err.println(exists ? "索引库已经存在!" : "索引库不存在!");
}
总结
JavaRestClient操作elasticsearch的流程基本类似。核心是client.indices()方法来获取索引库的操作对象。
索引库操作的基本步骤:
- 初始化RestHighLevelClient
- 创建XxxIndexRequest。XXX是Create、Get、Delete
- 准备DSL( Create时需要,其它是无参)
- 发送请求。调用RestHighLevelClient#indices().xxx()方法,xxx是create、exists、delete
RestClient操作文档
增加文档数据
java
@Test
public void testIndexDocument() throws IOException {
String json ="{\n" +
" \"id\":1,\n" +
" \"deleted\":0,\n" +
" \"fromUserId\":100,\n" +
" \"convType\":0,\n" +
" \"convId\":130,\n" +
" \"msgType\":1,\n" +
" \"msgBody\":\"我是王五\",\n" +
" \"msgId\":\"942131743446568960\",\n" +
" \"payload\":\"\",\n" +
" \"msgTime\":\"1699424599731\",\n" +
" \"sendResult\":0,\n" +
" \"subMsgType\":0,\n" +
" \"money\":200.1,\n" +
" \"type\":1\n" +
"}";
IndexRequest request = new IndexRequest("message").id("3");
// 2.准备请求的参数:DSL语句
request.source(json, XContentType.JSON);
// 3.发送请求
client.index(request, RequestOptions.DEFAULT);
}
查询文档
java
@Test
void testGetDocumentById() throws IOException {
// 1.准备Request
GetRequest request = new GetRequest("message", "3");
// 2.发送请求,得到响应
GetResponse response = client.get(request, RequestOptions.DEFAULT);
// 3.解析响应结果
String json = response.getSourceAsString();
}
删除文档
java
@Test
void testDeleteDocument() throws IOException {
// 1.准备Request
DeleteRequest request = new DeleteRequest("message", "3");
// 2.发送请求
client.delete(request, RequestOptions.DEFAULT);
}
修改文档
有修改两种方式:
- 全量修改:本质是先根据id删除,再新增
- 增量修改:修改文档中的指定字段值
在RestClient的API中,全量修改与新增的API完全一致,判断依据是ID:
- 如果新增时,ID已经存在,则修改
- 如果新增时,ID不存在,则新增
这里不再赘述,我们主要关注增量修改。
与之前类似,也是三步走:
- 1)准备Request对象。这次是修改,所以是UpdateRequest
- 2)准备参数。也就是JSON文档,里面包含要修改的字段
- 3)更新文档。这里调用client.update()方法
java
@Test
void testUpdateDocument() throws IOException {
// 1.准备Request
UpdateRequest request = new UpdateRequest("message", "3");
// 2.准备请求参数
request.doc(
"fromUserId", "11",
"msgBody", "土豆土豆,我是地瓜"
);
// 3.发送请求
client.update(request, RequestOptions.DEFAULT);
}
批量导入文档
java
@Test
void testBulkRequest() throws IOException {
// 批量查询酒店数据 修改为自己的
List<Message> messages= messageService.list();
// 1.创建Request
BulkRequest request = new BulkRequest();
// 2.准备参数,添加多个新增的Request
for (Message message: messages) {
// 2.2.创建新增文档的Request对象
request.add(new IndexRequest("message")
.id(message.getId().toString())
.source(JSON.toJSONString(message), XContentType.JSON));
}
// 3.发送请求
client.bulk(request, RequestOptions.DEFAULT);
}
小结
文档操作的基本步骤:
- 初始化RestHighLevelClient
- 创建XxxRequest。XXX是Index、Get、Update、Delete、Bulk
- 准备参数(Index、Update、Bulk时需要)
- 发送请求。调用RestHighLevelClient#.xxx()方法,xxx是index、get、update、delete、bulk
- 解析结果(Get时需要)