栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

Elasticsearch Index Templates(索引模板),开源新作

Elasticsearch Index Templates(索引模板),开源新作

public static final void createIndexTemp() {

RestHighLevelClient client = EsClient.getClient();

try {

PutIndexTemplateRequest request = new PutIndexTemplateRequest(“ubi_index_template”)

List indexPatterns = new ArrayList();

indexPatterns.add(“ubi*”);

request.patterns(indexPatterns);

XContentBuilder jsonBuilder = XContentFactory.jsonBuilder()

.startObject()

.startObject("_source")

.field(“enabled”, false)

.endObject()

.startObject(“properties”)

.startObject(“host_name”)

.field(“type”, “keyword”)

.endObject()

.startObject(“created_at”)

.field(“type”, “date”)

.field(“format”, “yyyy-MM-dd HH:mm:ss”)

.endObject()

.endObject()

.endObject();

request.mapping("_doc", jsonBuilder);

Map settings = new HashMap<>();

settings.put(“number_of_shards”, 1);

request.settings(settings);

System.out.println(client

【一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义】

浏览器打开:qq.cn.hn/FTf 免费领取

.indices().putTemplate(request, RequestOptions.DEFAULT));

} catch (Exception e) {

// TODO: handle exception

} finally {

EsClient.close(client);

}

}

上述索引模板创建好之后,然后在向一个不存在的索引添加文档时,如果能找到合适的模板,则自动创建索引,否则抛出索引不存在,例如:

public static void index_template() {

ElasticsearchTemplate template = new ElasticsearchTemplate();

try {

Map data = new HashMap<>();

data.put(“host_name”, “localhost”);

data.put(“created_at”, “2019-04-07 23:05:04”);

//ubi_201904该索引一开始不存在,但索引ubi_201904符合ubi_index_template

//中定义的匹配表达式ubi*,所以会自动创建索引。

template.index(“ubi_201904”, “_doc”, data);

} finally {

template.close();

}

}

其返回结果:

IndexResponse[index=ubi_201904,type=_doc,id=lCJZ-GkBrOLJP-QWff3I,version=1,result=created,seqNo=0,primaryTerm=1,shards={“total”:2,“successful”:1,“failed”:0}]

那如果能匹配到多个模板呢?

多个索引模板可能匹配一个索引,可以使用order属性为索引模板指定顺序。从顺序较小的开始寻找,order越大,越优先(前提是匹配模板表达式)。

举例如下:

PUT /_template/template_1

{

“index_patterns” : ["*"],

“order” : 0,

“settings” : {

“number_of_shards” : 1

},

“mappings” : {

“_doc” : {

“_source” : { “enabled” : false }

}

}

}

PUT /_template/template_2

{

“index_patterns” : [“te*”],

“order” : 1,

“settings” : {

“number_of_shards” : 1

},

“mappings” : {

“_doc” : {

“_source” : { “enabled” : true }

}

}

}

首先从order=0进行匹配,由于其表达式为*,则默认会全匹配,故首先尝试使用该模板,然后再遍历下一个模板,也就是order=1的模板,如果匹配,则使用第二个模板的配置,如果不匹配,则使用第一个模板的配置,依次类推。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/488204.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号