一 . elasticSearch提供了一些基本的rest命令,基本如下:
-
1 /index/_search 搜索指定索引下的数据,http://ip:9200/index/_search 查询当前索引下的数据 2 -
1 /index/ 查看指定索引的详细信息 2 -
1 /index/type/ 创建或操作类型 2 -
1 /index/_mapping 创建或操作mapping 2 -
1 /index/_settings 创建或操作设置(number_of_shards是不可更改的) 2 3 使用rest命令的时候一般都是配合着curl命令一起使用,例如 4 -
curl -x 指定http请求的方法 HEAD GET POST PUT DELETE
-
1 -d 指定要传输的数据 2 -
创建索引的时候可以使用如下命令
-
1 curl -XPUT 'http://localhost:9200/index_name/' 2 -
1 当然使用PUT/POST都可以,创建索引带有数据使用如下命令 2curl -XPOST http://localhost:9200/test/employee/1 -d '{ "first_name" : "John", "last_name" : "Smith", "age" : 25, "about" : "I love to go rock climbing", "interests": [ "sports", "music" ] }'
二. 虽然可以使用rest命令可以灵活操作es,但是真正平时开发肯定是用Java或者python了,下面看下JavaApi如何操作es.
首先构建客户端
1Client client = TransportClient.builder().build() 2 .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
因为这些操作基本可以封装为一个工具类,所以对创建客户端做了一层封装。
1 EsSearchManager esSearchManager = EsSearchManager.getInstance(); 2 esSearchManager.buildIndex("testIndex","testType");
在EsSearchManger构建实例的时候创建了ecClient,通过单例模式保证对象的唯一。
1private EsSearchManager(){ 2 getClient(); 3} 4public static EsSearchManager getInstance(){ 5 if(null == esSearchManager ){ 6 synchronized (EsSearchManager.class){ 7 esSearchManager = new EsSearchManager(); 8 } 9 } 10 return esSearchManager; 11 } 12
getClient()封装了创建client的细节不在赘述,下面是构建索引的代码,部分配置封装到了配置文件中,放置硬编码造成的修改麻烦,下面这个方法只是构建了索引,当然可以指定mapping设置,只是封装到了另一个方法中。
1public Boolean buildIndex(String indexName) throws Exception { 2 IndicesExistsResponse response = getClient().admin().indices() 3 .prepareExists(indexName).execute().actionGet(); 4 Boolean flag = true; 5 ResourceBundle rb = ResourceBundle.getBundle("commons"); 6 String replicas = rb.getString("replicas"); 7 String shards = rb.getString("shards"); 8 String refreshInterval = rb.getString("refreshInterval"); 9 if (!response.isExists()) { //需要将配置放置到配置文件中 10 Settings settings = Settings.settingsBuilder() 11 .put("number_of_replicas", Integer.parseInt(replicas)) 12 .put("number_of_shards", Integer.parseInt(shards)) 13 .put("index.translog.flush_threshold_ops", 10000000) 14 .put("refresh_interval", refreshInterval) 15 .put("index.codec", "best_compression").build(); 16 CreateIndexResponse createIndxeResponse = getClient().admin().indices() 17 .prepareCreate(indexName).setSettings(settings).execute() 18 .actionGet(); 19 flag = createIndxeResponse.isAcknowledged(); 20 LOG.info("返回值" + flag); 21 } 22 return flag; 23 }
至此索引创建完毕,通过head插件可以迅速查看到,详细的代码已将上传至github中,地址如下 https://github.com/winstonelei/BigDataTools