ElasticSearch是一款非常强大的搜索框架,我们在开发的时候常常需要通过命令来操作ES,注意本文中使用的ES版本为7.1.x,好了接下来直接进入主题。
创建索引
curl -XPUT 'http://localhost:9200/people?include_type_name=true' -H 'Content-Type:application/json' -d '{
"settings":{
"index.number_of_shards":3,
"index.number_of_replicas":1
},
"mappings":{
"_doc":{
"properties":{
"name":{
"type":"keyword"
},
"age":{
"type":"integer"
}
}
}
}
}'
返回结果:
{"acknowledged":true,"shards_acknowledged":true,"index":"people"}
插入数据
curl -XPUT 'http://localhost:9200/people/_doc/1' -H 'Content-Type:application/json' -d '{
"name":"zhangsan",
"age": 21
}'
{"_index":"people","_type":"_doc","_id":"1","_version":1,"result":"created","_shards":{"total":2,"successful":2,"failed":0},"_seq_no":0,"_primary_term":1}
查询数据
- 根据ID查询
curl -XGET 'http://localhost:9200/people/_doc/1'
返回结果:
{"_index":"people","_type":"_doc","_id":"1","_version":2,"_seq_no":1,"_primary_term":1,"found":true,"_source":{"name":"wangwu","age":21}}
- 查询所有数据
curl -XPOST 'http://localhost:9200/people/_search' -H 'Content-Type:application/json' -d '{
"query":{
"match_all":{}
}
}'
返回结果:
{"took":1,"timed_out":false,"_shards":{"total":3,"successful":3,"skipped":0,"failed":0},"hits":{"total":{"value":1,"relation":"eq"},"max_score":1.0,"hits":[{"_index":"people","_type":"_doc","_id":"1","_score":1.0,"_source":{"name":"wangwu","age":21}}]}}
- 查询所有根据指定from和size
curl -XPOST 'http://localhost:9200/people/_search' -H 'Content-Type:application/json' -d '{
"query":{
"match_all":{}
},
"from":0,
"size":1
}'
返回结果:
{"took":1,"timed_out":false,"_shards":{"total":3,"successful":3,"skipped":0,"failed":0},"hits":{"total":{"value":1,"relation":"eq"},"max_score":1.0,"hits":[{"_index":"people","_type":"_doc","_id":"1","_score":1.0,"_source":{"name":"wangwu","age":21}}]}}
- 根据条件查询
curl -XPOST 'http://localhost:9200/people/_search' -H 'Content-Type:application/json' -d '{
"query":{
"match":{
"name":"wangwu"
}
},
"size":1
}'
返回结果:
{"took":2200,"timed_out":false,"_shards":{"total":3,"successful":3,"skipped":0,"failed":0},"hits":{"total":{"value":1,"relation":"eq"},"max_score":0.2876821,"hits":[{"_index":"people","_type":"_doc","_id":"1","_score":0.2876821,"_source":{"name":"wangwu","age":21}}]}}
修改数据
curl -XPOST 'http://localhost:9200/people/_doc/1/_update' -H 'Content-Type:application/json' -d '{
"doc":{
"name":"wangwu"
}
}'
返回结果:
{"_index":"people","_type":"_doc","_id":"1","_version":2,"result":"updated","_shards":{"total":2,"successful":2,"failed":0},"_seq_no":1,"_primary_term":1}
删除数据
curl -XDELETE 'http://localhost:9200/people/_doc/1'
返回结果:
{"_index":"people","_type":"_doc","_id":"1","_version":3,"result":"deleted","_shards":{"total":2,"successful":2,"failed":0},"_seq_no":2,"_primary_term":1}