如何通过Curl方式进行ElasticSearch增删改查


如何通过Curl方式进行ElasticSearch增删改查

文章插图
关于ElasticSearch增删改查的方法有很多,使用curl操作命令总结如下,如有需要可以点击收藏 。
1、ElasticSearch新增数据如果进行一个类似于SQL的 insert的操作
insert into users(name,age,email) values('ctt',18,'ctt@abc.com')具体示例如下:
curl -XPOST "http://127.0.0.1:9200/users/_doc" -H "Content-Type: Application/json" -d '{"name": "ctt","age": 18,"email": "ctt@abc.com"}'
如何通过Curl方式进行ElasticSearch增删改查

文章插图
上面的命令使用HTTP POST方法向名为"users"的索引中添加一条文档,文档包含"name"、"age"和"email"三个字段 。其中,-X选项指定HTTP请求的方法,-H选项指定HTTP请求的头部信息,-d选项指定HTTP请求的数据体 。
写了多条记录,便于后面进行测试,结果如下:
{"took":1,"timed_out":false,"_shards":{"total":5,"successful":5,"skipped":0,"failed":0},"hits":{"total":5,"max_score":1.0,"hits":[{"_index":"users","_type":"_doc","_id":"Uxz2jYYBNjbWHoXGCfXa","_score":1.0,"_source":{"name": "jgt","age": 29,"email": "jgt@abc.com"}},{"_index":"users","_type":"_doc","_id":"UBz0jYYBNjbWHoXGufWJ","_score":1.0,"_source":{"name": "ttc","age": 20,"email": "ttc@abc.com"}},{"_index":"users","_type":"_doc","_id":"URz1jYYBNjbWHoXGOvU0","_score":1.0,"_source":{"name": "tt","age": 25,"email": "tt@abc.com"}},{"_index":"users","_type":"_doc","_id":"Uhz1jYYBNjbWHoXGhPWI","_score":1.0,"_source":{"name": "att","age": 27,"email": "att@abc.com"}},{"_index":"users","_type":"_doc","_id":"TxzvjYYBNjbWHoXG-fUx","_score":1.0,"_source":{"name": "ctt","age": 18,"email": "ctt@abc.com"}}]}}
如何通过Curl方式进行ElasticSearch增删改查

文章插图
可以用pretty加以修饰,结果集显示如下
: {"name" : "ttc","age" : 20,"email" : "ttc@abc.com"}},{"_index" : "users","_type" : "_doc","_id" : "URz1jYYBNjbWHoXGOvU0","_score" : 1.0,"_source" : {"name" : "tt","age" : 25,"email" : "tt@abc.com"}},{"_index" : "users","_type" : "_doc","_id" : "Uhz1jYYBNjbWHoXGhPWI","_score" : 1.0,"_source" : {"name" : "att","age" : 27,"email" : "att@abc.com"}},{"_index" : "users","_type" : "_doc","_id" : "TxzvjYYBNjbWHoXG-fUx","_score" : 1.0,"_source" : {"name" : "ctt","age" : 18,"email" : "ctt@abc.com"}}]}}如果新增的文档ID由Elasticsearch自动生成,可以将"_doc"替换为"_create",这样在新增数据时,Elasticsearch会在响应中返回文档ID,示例如下:
curl -XPOST "http://127.0.0.1:9200/users/_create" -H "Content-Type: application/json" -d '{"name": "ctty","age": 30,"email": "ctty@abc.com"}'2、更新记录进行一次类似如下update的操作
update users set age=30 where name='jgt'可以使用Elasticsearch的Update By Query API来根据条件更新数据 。Update By Query API可以对符合特定条件的所有文档进行更新操作 。以下是一个使用curl更新满足条件的文档的示例:
 curl -XPOST "http://127.0.0.1:9200/users/_update_by_query" -H "Content-Type: application/json" -d '{"query": {"term": {"name": "jgt"}},"script": {"source": "ctx._source.age = params.new_age","params": {"new_age": 30}}}'更新完成后查看结果如下:


推荐阅读