private static int port = 9200;
private static String host = "192.168.1.105";
private static RestHighLevelClient getClient() {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost(host, port, "http")));
return client;
}
/**
* bulk批量添加
*/
public static void batchAddDocuments(){
try {
RestHighLevelClient client = getClient();
Map<String, Object> jsonMap = new HashMap<String, Object>();
jsonMap.put("id", "01209");
jsonMap.put("title", "紅樓夢");
jsonMap.put("author", "曹雪芹");
jsonMap.put("classification", "小說");
IndexRequest request = new IndexRequest("book")
.id("2").source(jsonMap);
jsonMap.put("id", "01210");
jsonMap.put("title", "水滸傳");
jsonMap.put("author", "施耐庵");
jsonMap.put("classification", "小說");
IndexRequest request1 = new IndexRequest("book")
.id("3").source(jsonMap);
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.add(request);
bulkRequest.add(request1);
BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
for (BulkItemResponse bulkItemResponse : bulkResponse) {
DocWriteResponse itemResponse = bulkItemResponse.getResponse();
switch (bulkItemResponse.getOpType()) {
case INDEX:
break;
case CREATE:
IndexResponse indexResponse = (IndexResponse) itemResponse;
System.out.println("新增文档成功!");
break;
case UPDATE:
UpdateResponse updateResponse = (UpdateResponse) itemResponse;
System.out.println("更新文档成功!");
break;
case DELETE:
DeleteResponse deleteResponse = (DeleteResponse) itemResponse;
System.out.println("删除文档成功!");
break;
default:
}
}
client.close();
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 根据索引id删除
*/
public static void deleteDocument(){
try {
RestHighLevelClient client = getClient();
DeleteRequest request = new DeleteRequest(
"ancientbook",
"2607");
DeleteResponse deleteResponse = client.delete(
request, RequestOptions.DEFAULT);
System.out.println(deleteResponse.getResult());
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 根据索引id获取
*/
public static void getIndex() {
try {
RestHighLevelClient client = getClient();
GetRequest getRequest = new GetRequest(
"ancientbook",
"2607");
GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
String index = getResponse.getIndex();
String id = getResponse.getId();
if (getResponse.isExists()) {
long version = getResponse.getVersion();
String sourceAsString = getResponse.getSourceAsString();
Map<String, Object> sourceAsMap = getResponse.getSourceAsMap();
byte[] sourceAsBytes = getResponse.getSourceAsBytes();
System.out.println("index:" + index);
System.out.println("id:" + id);
System.out.println("version:" + version);
System.out.println("sourceAsString:" + sourceAsString);
System.out.println("sourceAsMap:" + sourceAsMap);
System.out.println("sourceAsBytes:" + sourceAsBytes);
} else {
}
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
(1条消息) ElasticSearch学习(五)—— Java写入数据_yilia_jia的博客-CSDN博客