阅读文本大概需要15分钟。
1、 创建文档Create Document
类似于数据库里面向数据表中插入一行数据,一行数据就相当一个文档
使用json字符串方式创建Document
public static void createWithJsonString(RestHighLevelClientclient){
// 1、创建索引请求
IndexRequestrequest = new IndexRequest(
"it", //索引
"_doc", // mapping type
"5"); //文档id
// 2、准备文档数据
// 方式一:直接给JSON串
StringjsonString = "{" +
"\"bookName\":\"java\","+
"\"publishDate\":\"2013-01-30\"," +
"\"sales\":\"100.00\"" +
"}";
request.source(jsonString, XContentType.JSON);
//3、其他可选设置
// request.routing("routing"); //设置routing值
// request.timeout(TimeValue.timeValueSeconds(1)); //设置主分片等待时长
// request.setRefreshPolicy("wait_for"); //设置重刷新策略
// request.version(2); //设置版本号
// request.opType(DocWriteRequest.OpType.CREATE); //操作类别
//4、发送请求
try{
// 同步方式
IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
//5、处理响应
if(indexResponse != null) {
String index =indexResponse.getIndex();
Stringtype = indexResponse.getType();
Stringid = indexResponse.getId();
long version = indexResponse.getVersion();
if (indexResponse.getResult() == DocWriteResponse.Result.CREATED) {
System.out.println("新增文档成功,处理逻辑代码写到这里。");
}else if (indexResponse.getResult()== DocWriteResponse.Result.UPDATED) {
System.out.println("修改文档成功,处理逻辑代码写到这里。");
}
// 分片处理信息
ReplicationResponse.ShardInfo shardInfo =indexResponse.getShardInfo();
if (shardInfo.getTotal() != shardInfo.getSuccessful()) {
}
// 如果有分片副本失败,可以获得失败原因信息
if (shardInfo.getFailed() > 0) {
for (ReplicationResponse.ShardInfo.Failurefailure : shardInfo.getFailures()) {
String reason =failure.reason();
System.out.println("副本失败原因:" + reason);
}
}
}
} catch(Exception e) {
e.printStackTrace();
}
}
使用Map的方式创建Document
public static void createWithMap(RestHighLevelClient client){
try{
// 1、创建索引请求
IndexRequest request = new IndexRequest(
"it", //索引
"_doc", // mapping type
"2"); //文档id
// 2、准备文档数据
// 方式二:以map对象来表示文档
Map<String, Object> jsonMap = new HashMap<String, Object>();
jsonMap.put("bookName", "c#");
jsonMap.put("publishDate", new Date());
jsonMap.put("sales", "100.00");
request.source(jsonMap);
//异步方式发送索引请求
ActionListener<IndexResponse> listener = new ActionListener<IndexResponse>() {
public void onResponse(IndexResponse indexResponse) {
}
public void onFailure(Exception e) {
}
};
client.indexAsync(request, RequestOptions.DEFAULT, listener);
} catch(Exception e) {
e.printStackTrace();
}
}
使用XContentBuilder对象创建Document
public static void createWithXContentBuilder(RestHighLevelClient client){
try {
// 1、创建索引请求
IndexRequest request = new IndexRequest(
"it", //索引
"_doc", // mapping type
"3"); //文档id
// 2、准备文档数据
// 方式三:用XContentBuilder来构建文档
XContentBuilder builder = XContentFactory.jsonBuilder();
builder.startObject();
{
builder.field("bookName", "python");
builder.field("publishDate", new Date());
builder.field("sales", "100.00");
}
builder.endObject();
request.source(builder);
// 同步方式
IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
//5、处理响应
if(indexResponse != null) {
String index = indexResponse.getIndex();
String type = indexResponse.getType();
String id = indexResponse.getId();
long version = indexResponse.getVersion();
if (indexResponse.getResult() == DocWriteResponse.Result.CREATED) {
System.out.println("新增文档成功,处理逻辑代码写到这里。");
} else if (indexResponse.getResult() == DocWriteResponse.Result.UPDATED) {
System.out.println("修改文档成功,处理逻辑代码写到这里。");
}
// 分片处理信息
ReplicationResponse.ShardInfo shardInfo = indexResponse.getShardInfo();
if (shardInfo.getTotal() != shardInfo.getSuccessful()) {
}
// 如果有分片副本失败,可以获得失败原因信息
if (shardInfo.getFailed() > 0) {
for (ReplicationResponse.ShardInfo.Failure failure : shardInfo.getFailures()) {
String reason = failure.reason();
System.out.println("副本失败原因:" + reason);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
使用Key-Value方式创建Document
public static void createWithKeyValue(RestHighLevelClient client){
// 1、创建索引请求
IndexRequest request = new IndexRequest(
"it", //索引
"_doc", // mapping type
"4"); //文档id
// 2、准备文档数据
// 方式四:直接用key-value对给出
request.source("bookName", "C++",
"publishDate", new Date(),
"sales", "100.00");
//4、发送请求
try {
// 同步方式
IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
//5、处理响应
if(indexResponse != null) {
String index = indexResponse.getIndex();
String type = indexResponse.getType();
String id = indexResponse.getId();
long version = indexResponse.getVersion();
if (indexResponse.getResult() == DocWriteResponse.Result.CREATED) {
System.out.println("新增文档成功,处理逻辑代码写到这里。");
} else if (indexResponse.getResult() == DocWriteResponse.Result.UPDATED) {
System.out.println("修改文档成功,处理逻辑代码写到这里。");
}
// 分片处理信息
ReplicationResponse.ShardInfo shardInfo = indexResponse.getShardInfo();
if (shardInfo.getTotal() != shardInfo.getSuccessful()) {
}
// 如果有分片副本失败,可以获得失败原因信息
if (shardInfo.getFailed() > 0) {
for (ReplicationResponse.ShardInfo.Failure failure : shardInfo.getFailures()) {
String reason = failure.reason();
System.out.println("副本失败原因:" + reason);
}
}
}
} catch(Exception e) {
e.printStackTrace();
}
}
2、 获取Document
同步方式获取:
public static void getDocumentSync(RestHighLevelClient client){
try {
// 1、创建获取文档请求
GetRequest request = new GetRequest(
"it", //索引
"_doc", // mapping type
"2"); //文档id
// 2、可选的设置
//request.routing("routing");
//request.version(2);
//request.fetchSourceContext(new FetchSourceContext(false)); //是否获取_source字段
//选择返回的字段
String[] includes = new String[]{"sales", "*Date"};
String[] excludes = Strings.EMPTY_ARRAY;
FetchSourceContext fetchSourceContext = new FetchSourceContext(true, includes, excludes);
request.fetchSourceContext(fetchSourceContext);
//也可写成这样
/*String[] includes = Strings.EMPTY_ARRAY;
String[] excludes = new String[]{"sales"};
FetchSourceContext fetchSourceContext = new FetchSourceContext(true, includes, excludes);
request.fetchSourceContext(fetchSourceContext);*/
// 取stored字段
/*request.storedFields("sales");
GetResponse getResponse = client.get(request);
String sales = getResponse.getField("sales").getValue();*/
//3、发送请求
// 同步请求
GetResponse getResponse = client.get(request, RequestOptions.DEFAULT);
//4、处理响应
if(getResponse != null) {
String index = getResponse.getIndex();
String type = getResponse.getType();
String id = getResponse.getId();
if (getResponse.isExists()) { // 文档存在
long version = getResponse.getVersion();
String sourceAsString = getResponse.getSourceAsString(); //结果取成 String
Map<String, Object> sourceAsMap = getResponse.getSourceAsMap(); // 结果取成Map
byte[] sourceAsBytes = getResponse.getSourceAsBytes(); //结果取成字节数组
System.out.println("index:" + index + " type:" + type + " id:" + id);
System.out.println(sourceAsString);
} else {
System.out.println("没有找到该id的文档" );
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
运行结果:
index:java type:_doc id:2
{"publishDate":"2019-06-30T11:45:00.548Z","sales":"100.00"}
异步方式获取:
public static void getDocumentAsync(RestHighLevelClient client){
try {
// 1、创建获取文档请求
GetRequest request = new GetRequest(
"it", //索引
"_doc", // mapping type
"2"); //文档id
// 2、可选的设置
//request.routing("routing");
//request.version(2);
//request.fetchSourceContext(new FetchSourceContext(false)); //是否获取_source字段
//选择返回的字段
String[] includes = new String[]{"sales", "*Date"};
String[] excludes = Strings.EMPTY_ARRAY;
FetchSourceContext fetchSourceContext = new FetchSourceContext(true, includes, excludes);
request.fetchSourceContext(fetchSourceContext);
//也可写成这样
/*String[] includes = Strings.EMPTY_ARRAY;
String[] excludes = new String[]{"sales"};
FetchSourceContext fetchSourceContext = new FetchSourceContext(true, includes, excludes);
request.fetchSourceContext(fetchSourceContext);*/
// 取stored字段
/*request.storedFields("sales");
GetResponse getResponse = client.get(request);
String sales = getResponse.getField("sales").getValue();*/
//3、发送请求
//异步方式发送获取文档请求
ActionListener<GetResponse> listener = new ActionListener<GetResponse>() {
public void onResponse(GetResponse getResponse) {
}
public void onFailure(Exception e) {
}
};
client.getAsync(request, RequestOptions.DEFAULT, listener);
} catch (Exception e) {
e.printStackTrace();
}
}