您的位置:首页 > 其它

Elasticsearch学习总结二 elasticSearch一些基本用法

2017-05-24 00:00 274 查看
摘要: 本篇将介绍一些es的基本用法包括基本索引的创建,删除,查询等

一 . elasticSearch提供了一些基本的rest命令,基本如下:

/index/_search    搜索指定索引下的数据,http://ip:9200/index/_search 查询当前索引下的数据


/index/                 查看指定索引的详细信息


/index/type/          创建或操作类型


/index/_mapping    创建或操作mapping


/index/_settings      创建或操作设置(number_of_shards是不可更改的)

使用rest命令的时候一般都是配合着curl命令一起使用,例如


curl -x 指定http请求的方法 HEAD GET POST PUT DELETE

-d   指定要传输的数据


创建索引的时候可以使用如下命令

curl -XPUT 'http://localhost:9200/index_name/'


当然使用PUT/POST都可以,创建索引带有数据使用如下命令


curl -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.

首先构建客户端

Client client = TransportClient.builder().build()
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));

因为这些操作基本可以封装为一个工具类,所以对创建客户端做了一层封装。

EsSearchManager esSearchManager = EsSearchManager.getInstance();
esSearchManager.buildIndex("testIndex","testType");

在EsSearchManger构建实例的时候创建了ecClient,通过单例模式保证对象的唯一。

private EsSearchManager(){
getClient();
}
public static EsSearchManager getInstance(){
if(null == esSearchManager ){
synchronized (EsSearchManager.class){
esSearchManager = new EsSearchManager();
}
}
return  esSearchManager;
}

getClient()封装了创建client的细节不在赘述,下面是构建索引的代码,部分配置封装到了配置文件中,放置硬编码造成的修改麻烦,下面这个方法只是构建了索引,当然可以指定mapping设置,只是封装到了另一个方法中。

public Boolean buildIndex(String indexName) throws Exception {
IndicesExistsResponse response = getClient().admin().indices()
.prepareExists(indexName).execute().actionGet();
Boolean flag = true;
ResourceBundle rb = ResourceBundle.getBundle("commons");
String replicas = rb.getString("replicas");
String shards = rb.getString("shards");
String refreshInterval = rb.getString("refreshInterval");
if (!response.isExists()) { //需要将配置放置到配置文件中
Settings settings = Settings.settingsBuilder()
.put("number_of_replicas", Integer.parseInt(replicas))
.put("number_of_shards", Integer.parseInt(shards))
.put("index.translog.flush_threshold_ops", 10000000)
.put("refresh_interval", refreshInterval)
.put("index.codec", "best_compression").build();
CreateIndexResponse createIndxeResponse = getClient().admin().indices()
.prepareCreate(indexName).setSettings(settings).execute()
.actionGet();
flag = createIndxeResponse.isAcknowledged();
LOG.info("返回值" + flag);
}
return flag;
}

至此索引创建完毕,通过head插件可以迅速查看到,详细的代码已将上传至github中,地址如下
https://github.com/winstonelei/BigDataTools
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: