文章目录
文档创建
- 文档创建
- 文档修改
创建User对象, 用于封装数据
public class User {
private String name;
private String sex;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
进行创建文档操作.
import com.fasterxml.jackson.databind.ObjectMapper;
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;
/**
* 类名称:ESTest_Client
* 类描述: 创建索引
*
* @author:
* 创建时间:2022/1/11 21:05
*/
public class ESTest_Doc_Insert {
public static void main(String[] args) throws Exception {
RestHighLevelClient esClient = null;
// 创建ES客户端
try {
esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("127.0.0.1", 9200, "http"))
);
IndexRequest request = new IndexRequest();
request.index("user").id("1002");
// 文档数据 转为json
User user = new User();
user.setName("zhangsan");
user.setSex("男");
user.setAge(20);
ObjectMapper mapper = new ObjectMapper();
String userJson = mapper.writeValueAsString(user);
request.source(userJson, XContentType.JSON);
IndexResponse response = esClient.index(request, RequestOptions.DEFAULT);
System.out.println("创建文档操作结果:" + response.getResult());
} finally {
if (esClient != null) {
// 关闭ES客户端
esClient.close();
}
}
}
}
request.index("user").id("1002");
用于指定创建文档的索引和id . IndexRequest
用于文档的创建操作对象.
运行结果如下: 如果再次执行, 则为update, 代表对于创建文档操作, 如果该id存在, 则是更新 ,如果不存在, 则是创建.
import org.apache.http.HttpHost;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
/**
* 类名称:ESTest_Client
* 类描述: 创建索引
*
* @author:
* 创建时间:2022/1/11 21:05
*/
public class ESTest_Doc_Update {
public static void main(String[] args) throws Exception {
RestHighLevelClient esClient = null;
// 创建ES客户端
try {
esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("127.0.0.1", 9200, "http"))
);
UpdateRequest request = new UpdateRequest();
request.index("user").id("1002");
request.doc(XContentType.JSON, "sex", "女");
UpdateResponse response = esClient.update(request, RequestOptions.DEFAULT);
System.out.println("更新文档操作结果:" + response.getResult());
} finally {
if (esClient != null) {
// 关闭ES客户端
esClient.close();
}
}
}
}
用UpdateRequest
请求, 把sex改成"女"
执行结果如下 , 代表修改成功 如果再次执行, 返回noop, 代表没有修改值.