本节实现文档的新增,修改
实现User.java
package com.zwy.es;
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;
}
}
ESTest_Doc_Insert.java
package com.zwy.es;
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.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;
import org.elasticsearch.common.xcontent.XContentType;
import java.io.IOException;
public class ESTest_Doc_Insert {
public static void main(String[] args) throws IOException {
//
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http"))
);
// 插入数据
IndexRequest request = new IndexRequest();
request.index("users").id("1001");
// 定义数据对象
User user = new User();
user.setName("张三");
user.setAge(30);
user.setSex("男");
// 向ES插入数据,必须将数据转换为JSON格式
ObjectMapper mapper = new ObjectMapper();
String userJson = mapper.writeValueAsString(user);
request.source(userJson, XContentType.JSON); // 将数据放进request中,并告知数据类型
IndexResponse response = esClient.index(request, RequestOptions.DEFAULT);
System.out.println(response.getResult());
// 关闭ES客户端
esClient.close();
}
}
ESTest_Doc_Update.java
package com.zwy.es;
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.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;
import java.io.IOException;
public class ESTest_Doc_Update {
public static void main(String[] args) throws IOException {
//
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http"))
);
// 插入数据
UpdateRequest request = new UpdateRequest();
request.index("users").id("1001");
request.doc(XContentType.JSON, "sex", "女"); // 修改文档数据
UpdateResponse response = esClient.update(request, RequestOptions.DEFAULT);
System.out.println(response.getResult());
// 关闭ES客户端
esClient.close();
}
}
文件结构
文件结构如下:
运行运行 ESTest_Doc_Insert.java:
然后打开POSTMAN,定义一个GET 请求,地址为我们刚刚定义的
http://127.0.0.1:9200/users/_doc/1001
然后发送请求有:
查询成功!
运行 ESTest_Doc_Update.java
修改成功,POSTMAN发送请求:
此时张三修改为了女。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)