ElasticSearch Indice mapping和Index Template管理
The best elasticsearch highlevel java rest api——-
ElasticSearch客户端框架bboss的ClientInterface 接口提供了创建/修改、获取、删除索引Indice和IndexTemplate的方法,本文举例说明其使用方法。
1 准备工作
参考文档在项目中导入Elasticsearch客户端:
本文除了介绍索引Indice和Index Template的创建修改方法,还可以看到如何在dsl中添加注释的用法:
单行注释
。。。。注释内容
。。。
*#
更多bboss dsl配置和定义的内容,参考文档:高性能elasticsearch ORM开发库使用介绍 章节【5.3 配置es查询dsl脚本语法】
2 定义创建Indice的dsl脚本
在配置文件-esmapper/demo.xml中定义一个名称为createDemoIndice的dsl脚本:
3 创建indice/判断indice是否存在/删除indice
根据上面定义的dsl脚本文件初始化ClientInterface对象,并创建索引表demo:
public void testCreateIndice(){
//创建加载配置文件的客户端工具,单实例多线程安全
ClientInterface clientUtil = ElasticSearchHelper.getConfigRestClientUtil("esmapper/demo.xml");
try {
//判读索引表demo是否存在,存在返回true,不存在返回false
boolean exist = clientUtil.existIndice("demo");
//如果索引表demo已经存在先删除mapping
if(exist)
clientUtil.dropIndice("demo");
//创建索引表demo
clientUtil.createIndiceMapping("demo",//索引表名称
"createDemoIndice");//索引表mapping dsl脚本名称,在esmapper/demo.xml中定义createDemoIndice
String mapping = clientUtil.getIndice("demo");
System.out.println(mapping);
} catch (ElasticSearchException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
4 定义索引Template dsl脚本
通过定义索引模板,定义表结构相同,但是索引表名称不同的索引表的建表模板,通过index_patterns中对应的模式名称来匹配索引模板适用的索引表:
5 创建/获取/删除索引表模板
public void testCreateTempate() throws ParseException{
ClientInterface clientUtil = ElasticSearchHelper.getConfigRestClientUtil("esmapper/demo.xml");
//创建模板
String response = clientUtil.createTempate("demotemplate_1",//模板名称
"demoTemplate");//模板对应的脚本名称,在esmapper/demo.xml中配置
System.out.println("createTempate-------------------------");
//获取模板
/**
* 指定模板
* /_template/demoTemplate*
* 所有模板 /_template
*
*/
String template = clientUtil.executeHttp("/_template/demotemplate_1",ClientUtil.HTTP_GET);
System.out.println("HTTP_GET-------------------------");
System.out.println(template);
ElasticSearchHelper.getRestClientUtil().deleteTempate("demotemplate_1");
}
6 修改和获取索引表结构
修改先前创建的demo表,为其中的type demo增加email关键字段
修改和获取mapping结构的方法:
public void updateDemoIndice(){
ClientInterface clientUtil = ElasticSearchHelper.getConfigRestClientUtil(mappath);
//修改索引表demo中type为demo的mapping结构,增加email字段,对应的dsl片段updateDemoIndice定义在esmapper/demo.xml文件中
String response = clientUtil.executeHttp("demo/_mapping/demo","updateDemoIndice",ClientUtil.HTTP_PUT);
System.out.println(response);
//获取修改后的索引mapping结构
String mapping = clientUtil.getIndice("demo");
System.out.println(mapping);
7 案例源码工程下载
https://github.com/bbossgroups/eshelloword-booter
8 参考文档
9 开发交流
elasticsearch技术交流:166471282