文章目录
前言
如果您觉得有用的话,记得给博主点个赞,评论,收藏一键三连啊,写作不易啊^ _ ^。
而且听说点赞的人每天的运气都不会太差,实在白嫖的话,那欢迎常来啊!!!
Elasticsearch - SpringBoot 索引与文档相关demo
1. _cat/* 相关API
示例:
GET /_cat/indices/yzy-*-20240830?v&h=index,pri.store.size&s=ss:desc&bytes=gb
含义:
GET /_cat/indices/yzy-*-20240830:请求 _cat/indices API,获取匹配模式为 yzy-*-20240830 的索引信息。
v:表示显示表头(列名)。
h=index,pri.store.size:指定要显示的列,index 是索引名称,pri.store.size 是主分片的存储大小。
s=ss:desc:按存储大小(ss)降序排序。
bytes=gb:将存储大小以 GB 为单位显示。
代码示例:
@GetMapping("/api/index_cat")
public String getIndexCat() {
try {
// 构建 Cat Indices 请求
Request request = new Request("GET", "/_cat/indices/yzy-*-20240830?v&h=index,pri.store.size&s=ss:desc&bytes=gb");
// 执行请求
Response response = client.getLowLevelClient().performRequest(request);
// 处理响应
String responseBody = EntityUtils.toString(response.getEntity());
log.info(responseBody);
return responseBody;
} catch (ResponseException e) {
log.error("Error executing request: " + e.getMessage());
} catch (IOException i){
log.error("错误 ",i);
}
return null;
}
2. 查看所有索引
代码示例:
@GetMapping("/api/index_all")
public String getAllIndex() {
try {
// 创建索引请求
Request request = new Request("GET", "/_cat/indices?v");
// 执行请求
Response response = client.getLowLevelClient().performRequest(request);
String msg = EntityUtils.toString(response.getEntity());
log.info(msg);
return msg;
} catch (ResponseException e) {
log.error("Error executing request: " + e.getMessage());
} catch (IOException i){
log.error("错误 ",i);
}
return null;
}
测试:
3. 创建索引
示例:
PUT /yzy_test
{
"settings": {
"number_of_shards": 1,
"number_of_replicas": 1
},
"mappings": {
"properties": {
"field1": { "type": "text" },
"field2": { "type": "keyword" }
}
}
}
代码:
@GetMapping("/api/index_create")
public String getIndexCreate() {
try {
// 创建索引请求
Request request = new Request("PUT", "/yzy_test");
String jsonString = "{ \"settings\": { \"number_of_shards\": 1, \"number_of_replicas\": 1 }, " +
"\"mappings\": { \"properties\": { \"field1\": { \"type\": \"text\" }, \"field2\": { \"type\": \"keyword\" } } } }";
request.setJsonEntity(jsonString);
// 执行请求
Response response = client.getLowLevelClient().performRequest(request);
String msg = EntityUtils.toString(response.getEntity());
log.info(msg);
return msg;
} catch (ResponseException e) {
log.error("Error executing request: " + e.getMessage());
} catch (IOException i){
log.error("错误 ",i);
}
return null;
}
测试
4. 检索索引
代码:
@GetMapping("/api/index_get")
public String getGetIndex() {
try {
// 创建索引请求
Request request = new Request("GET", "/yzy_test");
// 执行请求
Response response = client.getLowLevelClient().performRequest(request);
String msg = EntityUtils.toString(response.getEntity());
log.info(msg);
return msg;
} catch (ResponseException e) {
log.error("Error executing request: " + e.getMessage());
} catch (IOException i){
log.error("错误 ",i);
}
return null;
}
测试:
5. 删除索引
代码:
@GetMapping("/api/index_delete")
public String getDelIndex() {
try {
// 创建索引请求
Request request = new Request("DELETE", "/yzy_test");
// 执行请求
Response response = client.getLowLevelClient().performRequest(request);
String msg = EntityUtils.toString(response.getEntity());
log.info(msg);
return msg;
} catch (ResponseException e) {
log.error("Error executing request: " + e.getMessage());
} catch (IOException i){
log.error("错误 ",i);
}
return null;
}
测试:
6. 新增文档
代码:
@GetMapping("/api/doc_create")
public void createDocument() {
try {
// 创建 IndexRequest 对象,指定索引名称和文档ID
IndexRequest request = new IndexRequest("yzy-app-a-20240830").id("1");
// 设置文档内容
String jsonString = "{" +
"\"user\":\"kimchy\"," +
"\"postDate\":\"2023-08-30\"," +
"\"message\":\"trying out Elasticsearch\"" +
"}";
request.source(jsonString, XContentType.JSON);
// 执行请求
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
log.info( "Document add: " + response.getResult());
} catch (IOException e) {
log.error("Error creating document", e);
}
}
测试:
7. 更新文档
代码:
@GetMapping("/api/doc_update")
public void updateDocument() {
try {
// 创建 UpdateRequest 对象,指定索引名称和文档ID
UpdateRequest request = new UpdateRequest("yzy-app-a-20240830", "1");
// 设置更新内容
String jsonString = "{" +
"\"message\":\"updating document content\"" +
"}";
request.doc(jsonString, XContentType.JSON);
// 执行请求
UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
log.info( "Document update: " + response.getResult());
} catch (IOException e) {
log.error("Error updating document", e);
}
}
测试:
8. 根据索引中的文档 ID 查询文档
代码:
@GetMapping("/api/doc/{index}/{id}")
public String getDocumentById(@PathVariable String index, @PathVariable String id) {
try {
// 创建 GetRequest 对象,指定索引名称和文档ID
GetRequest getRequest = new GetRequest(index, id);
// 执行查询
GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
// 判断文档是否存在
if (getResponse.isExists()) {
// 返回文档内容
return getResponse.getSourceAsString();
} else {
return "Document not found";
}
} catch (Exception e) {
// 错误处理
e.printStackTrace();
return "Error retrieving document: " + e.getMessage();
}
}
测试:
9. 删除文档
@GetMapping("/api/doc_delete")
public void deleteDocument() {
try {
// 创建 DeleteRequest 对象,指定索引名称和文档ID
DeleteRequest request = new DeleteRequest("yzy-app-a-20240830", "1");
// 执行请求
DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
log.info( "Document deleted: " + response.getResult());
} catch (IOException e) {
log.error("Error deleting document", e);
}
}
测试: