1. 文档的基本CRUD与批量操作
文档的基本CRUD与批量操作¶
- create一个文档
支持自动生成id或者指定id的方式
通过调用post /users/_doc 系统会自动生成docmentid
使用http put /users/_doc/1 创建时uri显示指定_create,如果文档id已经存在,操作失败
put /users/_create/1 {}
找到文档返回200,找不到返回404
文档元信息
_index 索引名称 _source 默认包含文档的原始信息
- Index文档
index跟create不一样的地方:如果文档不存在,就索引新的文档.否则现有文档会被删除,索引新的文档,版本信息+1
put /users/_doc/1 {}
- Update
Update方法不会删除原来的文档,而是实现真正的数据更新
post方法,需要包含在doc中
POST users/_update/1 { "doc":{ "aaa":["xxx","yyy"] } }
#create document. 自动生成 _id POST users/_doc { "user" : "Mike", "post_date" : "2019-04-15T14:12:12", "message" : "trying out Kibana" } #create document. 指定Id。如果id已经存在,报错 PUT users/_doc/1?op_type=create { "user" : "Jack", "post_date" : "2019-05-15T14:12:12", "message" : "trying out Elasticsearch" } #create document. 指定 ID 如果已经存在,就报错 PUT users/_create/1 { "user" : "Jack", "post_date" : "2019-05-15T14:12:12", "message" : "trying out Elasticsearch" } ### Get Document by ID #Get the document by ID GET users/_doc/1 ### Index & Update #Update 指定 ID (先删除,在写入) GET users/_doc/1 PUT users/_doc/1 { "user" : "Mike" } #GET users/_doc/1 #在原文档上增加字段 POST users/_update/1/ { "doc":{ "post_date" : "2019-05-15T14:12:12", "message" : "trying out Elasticsearch" } } ### Delete by Id # 删除文档 DELETE users/_doc/1
支持在一次api调用中,对不同的索引进行操作
支持index create update delete
操作中单条操作失败不会影响其他操作
返回结果包含每一条操作执行的结果
演练
### Bulk 操作 #执行两次,查看每次的结果 #执行第1次 POST _bulk { "index" : { "_index" : "test", "_id" : "1" } } { "field1" : "value1" } { "delete" : { "_index" : "test", "_id" : "2" } } { "create" : { "_index" : "test2", "_id" : "3" } } { "field1" : "value3" } { "update" : {"_id" : "1", "_index" : "test"} } { "doc" : {"field2" : "value2"} } #执行第2次 POST _bulk { "index" : { "_index" : "test", "_id" : "1" } } { "field1" : "value1" } { "delete" : { "_index" : "test", "_id" : "2" } } { "create" : { "_index" : "test2", "_id" : "3" } } { "field1" : "value3" } { "update" : {"_id" : "1", "_index" : "test"} } { "doc" : {"field2" : "value2"} }
- 批量读取 mget
### mget 操作 GET /_mget { "docs" : [ { "_index" : "test", "_id" : "1" }, { "_index" : "test", "_id" : "2" } ] } #URI中指定index GET /test/_mget { "docs" : [ { "_id" : "1" }, { "_id" : "2" } ] } GET /_mget { "docs" : [ { "_index" : "test", "_id" : "1", "_source" : false }, { "_index" : "test", "_id" : "2", "_source" : ["field3", "field4"] }, { "_index" : "test", "_id" : "3", "_source" : { "include": ["user"], "exclude": ["user.location"] } } ] }
批量查询mserach
### msearch 操作 POST kibana_sample_data_ecommerce/_msearch {} {"query" : {"match_all" : {}},"size":1} {"index" : "kibana_sample_data_flights"} {"query" : {"match_all" : {}},"size":2}