ElasticSearch(二)-- 简单的增删改查
1.查看集群的健康状态
_cat命令是系统信息查询相关的
curl--user elastic:changeme-XGET'localhost:9200/_cat/health?v'
--user表示用户名和密码
-XGET后面为请求查询的url
?v 每个命令都支持使用?v参数,来显示详细的信息 (verbose),或者说加上表头显示
无论何时查看集群健康状态,我们会得到 green
、 yellow
、 red
中的任何一个。
Green - 一切运行正常(集群功能齐全)
Yellow - 所有数据是可以获取的,但是一些复制品还没有被分配(集群功能齐全)
Red - 一些数据因为一些原因获取不到(集群部分功能不可用),当一个集群处于red状态时,它会通过可用的分片继续提供搜索服务,但是当有未分配的分片时,你需要尽快的修复它
2.列出所有的索引
curl--user elastic:changeme-XGET'localhost:9200/_cat/indices?v&pretty'
这里只有一个默认的索引,因为我们还没有创建自己的索引。
3.创建一个索引
curl--user elastic:changeme-H'Content-Type:application/json;charset=UTF-8'-XPUT'localhost:9200/goods/type1/1?pretty'-d'{"name":"Joe","hobby":"编程"}'
注意:增加 和 修改索引 需要加上 -H'Content-Type:application/json;charset=UTF-8'
4.查询整个索引
curl--user elastic:changeme-XGET'localhost:9200/goods?pretty'
这个索引包含5个分片,复制数1,包含一个文档类型tp1。
还可以用_search命令来查询索引里的具体文档,不带任何参数查询所有文档:
curl--user elastic:changeme-XGET'localhost:9200/goods/_search?pretty'
注意:curl --user elastic:changeme -XGET localhost:9200/goods 查询的是索引goods的源数据情况;而curl --user elastic:changeme -XGET localhost:9200/goods/_query 返回的是索引里的数据。
curl--user elastic:changeme-XGET'localhost:9200/goods/type1/1?pretty'
source属性返回我们在上一步中加入索引的完整JSON文档内容
5.修改索引中的id为1 的文档
curl--user elastic:changeme-H'Content-Type:application/json;charset=UTF-8'-XPOST'localhost:9200/goods/type1/1?pretty'-d'{"name":"xbq","hobby":"足球"}'
6.使用_update修改文档
curl--user elastic:changeme-H'Content-Type:application/json;charset=UTF-8'-XPOST'localhost:9200/goods/type1/1/_update?pretty'-d'{"doc":{"name":"beckham","age":37}}'
7.删除文档
curl--user elastic:changeme-XDELETE'localhost:9200/goods/type1/1?pretty'
查询一下,发现hits中为空了,表示删除成功了。
curl--user elastic:changeme-XGET'localhost:9200/goods/_search?pretty'
8.查询字符串
查询字段名name中包含”hello”的记录
curl--user elastic:changeme-H'Content-Type:application/json;charset=UTF-8'-XGET'localhost:9200/goods/_search?pretty'-d'{"query": {"match":{"name":"beckham"}}}'
注意:这里的match如果是针对字符串,那么会以空格为分解符,也就是说“beckham”和“beckham Joe”都是满足条件的,但是“beckhamJoe”就不满足条件了。
指定返回某些字段:只需要返回”name”和”age”字段:
curl--user elastic:changeme-H'Content-Type:application/json;charset=UTF-8'-XGET'localhost:9200/goods/_search?pretty'-d'{"_source":["name","age"]},{"query": {"match":{"name":"beckham"}}}'