Elasticsearch 索引Index API(7.5.0)
一、索引模板
1. 模板是否存在
A. 请求:HEAD /_template/rhxy_login_log
B. Kibana操作
C. Java实现:参考下面 5. Java自动创建索引模板
2. 获取模板
A. 请求:GET /_template/rhxy_login_log
B. Kibana操作
C. Java实现:参考下面 5. Java自动创建索引模板
3. 创建索引模板
A. 请求
PUT _template/rhxy_login_log { "index_patterns": ["rhxy_login_log_*"], "settings": { "number_of_shards": 5 }, "version": 20201201, "aliases": { "rhxy_login_log": {} }, "mappings" : { "properties" : { "country" : { "type" : "keyword" }, "lng" : { "type" : "double" }, "city" : { "type" : "keyword" }, "sex" : { "type" : "integer" }, "ip" : { "type" : "keyword" }, "remark" : { "type" : "text" }, "userId" : { "type" : "long" }, "province" : { "type" : "keyword" }, "phone" : { "type" : "keyword" }, "email" : { "type" : "keyword" }, "lat" : { "type" : "double" }, "timestamp" : { "format" : "yyyy-MM-dd HH:mm:ss.SSS", "type" : "date" }, "username" : { "type" : "keyword" }, "status" : { "type" : "integer" } } } }
B. Kibana操作
C. Java实现:参考下面 5. Java自动创建索引模板
4. 删除索引模板
A. 请求:DELETE /_template/rhxy_login_log
B. Kibana操作
C. Java实现:参考下面 5. Java自动创建索引模板
5. Java自动创建索引模板
package com.ruhuanxingyun.elasticsearch.config; import lombok.extern.slf4j.Slf4j; import org.elasticsearch.action.admin.indices.alias.Alias; import org.elasticsearch.action.admin.indices.template.delete.DeleteIndexTemplateRequest; import org.elasticsearch.action.support.master.AcknowledgedResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.client.indices.GetIndexTemplatesRequest; import org.elasticsearch.client.indices.GetIndexTemplatesResponse; import org.elasticsearch.client.indices.IndexTemplatesExistRequest; import org.elasticsearch.client.indices.PutIndexTemplateRequest; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.io.IOException; import java.util.Collections; /** * @description: 自动创建索引模板 * @author: ruphie * @date: Create in 2020/12/1 21:27 * @company: ruhuanxingyun */ @Component @Slf4j public class ElasticsearchIndexTemplate { @Autowired private RestHighLevelClient restHighLevelClient; private static final int VERSION = 20201201; private static final String TEMPLATE = "rhxy_login_log"; @PostConstruct public void initTemplate() { try { // 判断索引模板是否存在 boolean status = this.templateExist(); if (status) { // 获取模板版本 Integer version = this.getTemplate(); if (version != null && VERSION == version) { return; } // 删除模板 this.deleteTemplate(); } // 创建新模板 this.createTemplate(); } catch (Exception e) { log.error("创建索引模板{}失败:", TEMPLATE, e); } } /** * 判断索引模板是否存在 * * @return 存在与否 * @throws IOException 异常 */ private boolean templateExist() throws IOException { IndexTemplatesExistRequest request = new IndexTemplatesExistRequest(TEMPLATE); return restHighLevelClient.indices().existsTemplate(request, RequestOptions.DEFAULT); } /** * 创建索引模板 * * @throws IOException 异常 */ private void createTemplate() throws IOException { PutIndexTemplateRequest request = new PutIndexTemplateRequest(TEMPLATE); request.patterns(Collections.singletonList(String.format("%s_*", TEMPLATE))) .settings(Settings.builder().put("index.number_of_shards", 5)) .mapping(this.buildXContent()) .alias(new Alias(TEMPLATE)) .version(VERSION); AcknowledgedResponse response = restHighLevelClient.indices().putTemplate(request, RequestOptions.DEFAULT); log.info("创建索引模板【{}】{}", TEMPLATE, response.isAcknowledged() ? "成功" : "失败"); } /** * 构建mapping * * @return mapping * @throws IOException 异常 */ private XContentBuilder buildXContent() throws IOException { XContentBuilder builder = XContentFactory.jsonBuilder(); builder.startObject() .startObject("properties") .startObject("timestamp") .field("type", "date") .field("format", "yyyy-MM-dd HH:mm:ss.SSS") .endObject() .startObject("userId") .field("type", "long") .endObject() .startObject("username") .field("type", "keyword") .endObject() .startObject("phone") .field("type", "keyword") .endObject() .startObject("sex") .field("type", "integer") .endObject() .startObject("email") .field("type", "keyword") .endObject() .startObject("ip") .field("type", "keyword") .endObject() .startObject("country") .field("type", "keyword") .endObject() .startObject("province") .field("type", "keyword") .endObject() .startObject("city") .field("type", "keyword") .endObject() .startObject("lng") .field("type", "double") .endObject() .startObject("lat") .field("type", "double") .endObject() .startObject("status") .field("type", "integer") .endObject() .startObject("remark") .field("type", "text") .endObject() .endObject() .endObject(); return builder; } /** * 获取索引模板版本 * * @return 版本 * @throws IOException 异常 */ private Integer getTemplate() throws IOException { GetIndexTemplatesRequest request = new GetIndexTemplatesRequest(TEMPLATE); GetIndexTemplatesResponse response = restHighLevelClient.indices().getIndexTemplate(request, RequestOptions.DEFAULT); return response.getIndexTemplates().get(0).version(); } /** * 删除以前索引模板 * * @throws IOException 异常 */ private void deleteTemplate() throws IOException { DeleteIndexTemplateRequest request = new DeleteIndexTemplateRequest(TEMPLATE); AcknowledgedResponse response = restHighLevelClient.indices().deleteTemplate(request, RequestOptions.DEFAULT); log.info("删除索引模板【{}】{}", TEMPLATE, response.isAcknowledged() ? "成功" : "失败"); } }
二、索引
1. 获取索引
A. elasticsearch-head/postman/kibana
GET /<index>
路径参数:index是索引名称,多个以逗号分隔,或者通配符表达式,可使用_all来获取集群所有的索引;
查询参数:expand_wildcards是控制通配符表达式可以扩展到的索引类型,默认值为open,all-展示开放和关闭的索引,open-仅展示开放的索引,closed-仅展示关闭的索引,none-不接受通配符表达式;
B. kibana操作
C. java编写
/** * 删除超过预存天数的日志 * * @param preserveDay 预留天数 */ private void deleteLogByTime(Integer preserveDay) { String[] indexPrefixs = this.indexPrefix.split(StrUtil.COMMA); GetIndexRequest getIndexRequest; DeleteIndexRequest deleteIndexRequest; List<String> list = new ArrayList<>(); Set<String> set = new HashSet<>(); try { for (String indexPrefix : indexPrefixs) { getIndexRequest = new GetIndexRequest(String.format("%s*", indexPrefix)); GetIndexResponse response = restHighLevelClient.indices().get(getIndexRequest, RequestOptions.DEFAULT); // 索引数据第一条就是本索引最先的存储的数据 String[] indexs = response.getIndices(); int diff = indexs.length - preserveDay; if (diff > 0) { list.clear(); for (int i = 0; i < diff; i++) { list.add(indexs[i]); set.add(indexs[i].replace(indexPrefix, "")); } deleteIndexRequest = new DeleteIndexRequest(list.toArray(new String[0])); restHighLevelClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT); log.info(String.format("删除索引名称为%s日志", list.toString())); } } if (CollUtil.isNotEmpty(set)) { this.deleteDiskSpaceByLogTime(set); } } catch (IOException e) { e.printStackTrace(); log.info("删除超过预存天数的日志失败"); } }
2. 创建索引
A. elasticsearch-head/postman/kibana
PUT /<index>
路径参数:index索引名称仅小写;
请求正文:aliases是索引别名,mappings是索引中字段,映射对象,settings是索引的配置项
B. kibana操作
C. java编写
3. 删除索引
A. elasticsearch-head/postman/kibana
DELETE /<index>
路径参数:不能使用别名删除索引,要禁用_all或通配符表达式删除索引,请将elasticsearch.yml
文件中action.destructive_requires_name
群集设置设为true
B. kibana操作
C. java编写:见获取索引里的代码
4. 关闭索引
A. elasticsearch-head/postman
POST /<index>/_close 关闭索引禁止进行读写操作,并且不允许开放索引允许的所有操作,无法对文档建立索引或者在关闭索引中进行搜索文档。这使关闭索引不必维护用于文档建立索引或搜索文档的内部数据结构,从而减少了集群上的开销,但关闭索引会占用大量的磁盘空间。
B. java代码层
CloseIndexRequest request = new CloseIndexRequest("index"); AcknowledgedResponse closeIndexResponse = client.indices().close(request, RequestOptions.DEFAULT); boolean acknowledged = closeIndexResponse.isAcknowledged();
5. 开放索引
A. elasticsearch-head/postman
POST /<index>/_open 重新打开封闭索引,当打开或关闭索引时,主服务器负责重新启动索引分片以反映索引的新状态,然后索引将经历正常的恢复过程
B. java代码层
OpenIndexRequest request = new OpenIndexRequest("index"); OpenIndexResponse openIndexResponse = client.indices().open(request, RequestOptions.DEFAULT); boolean acknowledged = openIndexResponse.isAcknowledged(); boolean shardsAcked = openIndexResponse.isShardsAcknowledged();
可参考:ES官网 索引Index
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗