ElasticSearch Indice mapping和Index Template管理

The best elasticsearch highlevel java rest api——-

ElasticSearch客户端框架bboss的ClientInterface 接口提供了创建/修改、获取、删除索引Indice和IndexTemplate的方法,本文举例说明其使用方法。

1 准备工作

参考文档在项目中导入Elasticsearch客户端:

本文除了介绍索引Indice和Index Template的创建修改方法,还可以看到如何在dsl中添加注释的用法:

单行注释

  1. 。。。。注释内容
  2. 。。。
  3. *#

更多bboss dsl配置和定义的内容,参考文档:高性能elasticsearch ORM开发库使用介绍 章节【5.3 配置es查询dsl脚本语法

2 定义创建Indice的dsl脚本

在配置文件-esmapper/demo.xml中定义一个名称为createDemoIndice的dsl脚本:

3 创建indice/判断indice是否存在/删除indice

根据上面定义的dsl脚本文件初始化ClientInterface对象,并创建索引表demo:

  1. public void testCreateIndice(){
  2. //创建加载配置文件的客户端工具,单实例多线程安全
  3. ClientInterface clientUtil = ElasticSearchHelper.getConfigRestClientUtil("esmapper/demo.xml");
  4. try {
  5. //判读索引表demo是否存在,存在返回true,不存在返回false
  6. boolean exist = clientUtil.existIndice("demo");
  7. //如果索引表demo已经存在先删除mapping
  8. if(exist)
  9. clientUtil.dropIndice("demo");
  10. //创建索引表demo
  11. clientUtil.createIndiceMapping("demo",//索引表名称
  12. "createDemoIndice");//索引表mapping dsl脚本名称,在esmapper/demo.xml中定义createDemoIndice
  13. String mapping = clientUtil.getIndice("demo");
  14. System.out.println(mapping);
  15. } catch (ElasticSearchException e) {
  16. // TODO Auto-generated catch block
  17. e.printStackTrace();
  18. }
  19. }

4 定义索引Template dsl脚本

通过定义索引模板,定义表结构相同,但是索引表名称不同的索引表的建表模板,通过index_patterns中对应的模式名称来匹配索引模板适用的索引表:

5 创建/获取/删除索引表模板

  1. public void testCreateTempate() throws ParseException{
  2. ClientInterface clientUtil = ElasticSearchHelper.getConfigRestClientUtil("esmapper/demo.xml");
  3. //创建模板
  4. String response = clientUtil.createTempate("demotemplate_1",//模板名称
  5. "demoTemplate");//模板对应的脚本名称,在esmapper/demo.xml中配置
  6. System.out.println("createTempate-------------------------");
  7. //获取模板
  8. /**
  9. * 指定模板
  10. * /_template/demoTemplate*
  11. * 所有模板 /_template
  12. *
  13. */
  14. String template = clientUtil.executeHttp("/_template/demotemplate_1",ClientUtil.HTTP_GET);
  15. System.out.println("HTTP_GET-------------------------");
  16. System.out.println(template);
  17. ElasticSearchHelper.getRestClientUtil().deleteTempate("demotemplate_1");
  18. }

6 修改和获取索引表结构

修改先前创建的demo表,为其中的type demo增加email关键字段

修改和获取mapping结构的方法:

  1. public void updateDemoIndice(){
  2. ClientInterface clientUtil = ElasticSearchHelper.getConfigRestClientUtil(mappath);
  3. //修改索引表demo中type为demo的mapping结构,增加email字段,对应的dsl片段updateDemoIndice定义在esmapper/demo.xml文件中
  4. String response = clientUtil.executeHttp("demo/_mapping/demo","updateDemoIndice",ClientUtil.HTTP_PUT);
  5. System.out.println(response);
  6. //获取修改后的索引mapping结构
  7. String mapping = clientUtil.getIndice("demo");
  8. System.out.println(mapping);

7 案例源码工程下载

https://github.com/bbossgroups/eshelloword-booter

8 参考文档

9 开发交流

elasticsearch技术交流:166471282