026 elasticsearch文档管理(添加、修改、删除、批处理)-Java原生客户端
文章目录
- 1.添加文档
- 2.更新文档
- 3.删除文档
- 4.根据id取文档对象
- 5.批量操作bulk
1.添加文档
使用RestHightLevelClient对象
使用client对象的index方法添加文档
创建IndexRequest对象,其中包含了索引库名称、文档的id、文档的内容
{"id":"1","title":"测试文档1","content":"测试文档中的内容"}
package com.xd.cubemall.es;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class DocumentManager {
private RestHighLevelClient client;
@BeforeEach
public void init() {
//创建一个client对象
client = new RestHighLevelClient(RestClient.builder(
new HttpHost("1.1.1.1",9200),
new HttpHost("2.2.2.2",9200),
new HttpHost("3.3.3.3",9200)
));
}
@Test
public void addDocument() throws Exception{
String document = "{\"id\":\"1\",\"title\":\"测试文档1\",\"content\":\"测试文档中的内容\"}";
//创建IndexRequest对象,其中包含了索引库名称、文档id、文档的内容
IndexRequest indexRequest = new IndexRequest(/**"hello1"**/)
.index("hello1")
.id("1")
.source(document, XContentType.JSON);
IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
System.out.println(response);
}
}
2.更新文档
使用client对象的update方法。
需要UpdateRequest参数:
1.更新的索引
2.更新的文档的id
3.更新的文档内容
@Test
public void updateDocument() throws Exception {
String document = "{\"id\":\"1\",\"title\":\"测试文档2\",\"content\":\"测试文档中的内容2\"}";
UpdateRequest request = new UpdateRequest()
.index("hello1")
.id("1")
.doc(document,XContentType.JSON);
UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
System.out.println(response);
}
3.删除文档
使用client的delete方法
需要DeleteRequest对象,需要三个参数
1.操作的索引
2.文档的id
@Test
public void deleteDocument() throws Exception {
DeleteRequest request = new DeleteRequest("hello1","1");
client.delete(request, RequestOptions.DEFAULT);
}
4.根据id取文档对象
使用client对象的get方法
需要使用GetRequest对象,两个参数:
1.操作的索引
2.文档的id
@Test
public void getDocument() throws Exception {
GetRequest request = new GetRequest("hello1","2");
GetResponse response = client.get(request, RequestOptions.DEFAULT);
System.out.println(response);
}
5.批量操作bulk
使用client对象的bulk方法
BulkRequest对象,使用add方法,添加要批量处理的请求。
支持的处理:
IndexRequest
DeleteRequest
UpdateRequest
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
@Test
public void bulkDocument() throws Exception {
String json = "";
JSONArray jsonArray = JSONObject.parseArray(json);
BulkRequest request = new BulkRequest();
jsonArray.stream()
.forEach(j->{
IndexRequest r = new IndexRequest()
.index("hello1")
.id(((JSONObject)j).getString("id"))
.source(((JSONObject) j).toJSONString(),XContentType.JSON);
request.add(r);
});
BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
System.out.println(response);
}