ES查询集群状态
使用ES的REST API可以做到下面的事情:
1 管理集群,节点,索引数据和元数据
2 对索引 执行创建,读取,更新和删除操作,以及根据索引查询
3 执行更深入的操作,比如分页、排序、过滤、脚本编写、faceting、聚合等。
4 查询集群,索引,节点的健康状况和各种统计信息
查询集群的健康状况:
curl localhost:9200/_cat/health?v
查询结果中status会显示状态颜色:
red:表示有些数据不可用
yellow:表示所有数据可用,但是备份不可用
green:表示一切正常
注意,即便是红色,部分分片上的数据也是可用的。
上面的第一次是我们默认执行elasticsearch.bat时,响应的结果。
这是因为第一次默认执行时,时没有配置集群以及节点名称的。
第二次手动修改了配置文件conf/elasticsearch.yml,所以我们查询集群时,会有两个节点。
列出所有的索引:
curl localhost:9200/_cat/indices?v
返回:health status index uuid pri rep docs.count docs.deleted store.size pri.store.size
意味着我们没有索引。
创建索引:
curl -XPUT 'localhost:9200/customer?pretty'
索引(添加)并查询一个文档:
curl -XPUT 'localhost:9200/customer/external/1?pretty' -d '{ "name":"boss"}'
返回结果:
{
"_index" : "customer",
"_type" : "external",
"_id" : "1",
"_version" : 1,
"result" : "created",
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"created" : true
}
获取文档:
curl -XGET 'localhost:9200/customer/external/1?pretty'
返回结果:
{
"_index" : "customer",
"_type" : "external",
"_id" : "1",
"_version" : 1,
"found" : true,
"_source" : {
"name" : "boss"
}
}
删除索引:
curl -XDELETE 'localhost:9200/customer?pretty'
返回:
{
"acknowledged" : true
}
总结:
rest 命令格式 ( 适合所有的api 命令)
curl -X<REST Verb> <Node>:<port>/<Index>/<Type>/<iD>
修改数据:
注意 :默认情况下,从你索引/更新,删除你的数据动作开始到它出现在你的搜索结果中,大概会有1秒钟的延迟。
这个其他sql 平台不同,他们的数据在一个事物完成之后就会立即可用。
如果在 索引(添加)文档的时候没有指定ID,可以使用curl -X POST 请求代替 XPUT 请求。
索引(添加)文档的时候,如果id已经存在,则替换,如果不存在,则添加。
es 不支持原地更新,做更新操作的时候,会先删除就文档,再添加新文档。
更新操作:
1 curl -XPOST 'localhost:9200/customer/external/1/_udpate?pretty' -d '{"doc":{"name":"asdadfa"}}';
2 curl -XPOST 'localhost:9200/customer/external/1/_udpate?pretty' -d '{"script":"ctx._source.name="asdfasfasfafasfafa"}';
删除指定ID文档:
curl -XDELETE 'localhost:9200/customer/external/1?pretty' ;
删除满足条件文档:
curl -XDELETE 'localhost:9200/customer/external/_query?pretty' -d ‘{"query":{"match":{"name":"John"}}}’;
批处理:
批量索引文档
curl -XPOST 'localhost:9200/customer/external/_bulk?pretty' -d '
{"index":{"_id":""1}}
{"name":"john sa"}
{"index":{"_id":""2}}
{"name":"john s121"}
'
先更新文档1,再删除文档2
curl -XPOST 'localhost:9200/customer/external/_bulk?pretty' -d '
{"update":{"_id":"1"}}
{"doc":{"name":"hello"}}
{"delete":{"_id":"2"}}
‘
bulk api 按顺序执行动作,如果其中一个失败了,不影响后续动作执行。
结果会返回每个动作的执行状态。
载入样本数据:
curl -XPOST "http://localhost:9200/bank/account/_bulk?pretty" --data-binary "@accounts.json"