上篇文章介绍了elasticsearch的基本概念,今天主要介绍elasticsearch文档的基本crud操作,本文为《极客时间》学习笔记
create文档
1、create document 自动生成_id
请求:
POST ajtest/_doc
{
"user":"cb",
"create_time":"2020-08-02T14:12:12",
"remark":"elastic test"
}
返回结果(自动生成文档的_id):
{
"_index" : "ajtest",
"_type" : "_doc",
"_id" : "Gvw7rXMB-sPOHQAyK08l",
"_version" : 1,
"result" : "created",
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 0,
"_primary_term" : 1
}
2、使用PUT index_name/_create/_id
或PUT index_name/_doc/_id?op_type=create
创建时,URI中显示指定_create
,此时如果该_id的文档已经存在,操作会失败
#create document. 指定 ID 如果已经存在,就报错
PUT ajtest/_doc/1?op_type=create
{
"user":"aj",
"create_time":"2020-08-02T14:12:12",
"remark":"elasticsearch test"
}
#create document. 指定 ID 如果已经存在,就报错
PUT ajtest/_create/1
{
"user":"ajcb",
"create_time":"2020-08-02T14:12:12",
"remark":"elasticsearch test"
}
Get文档
Get ajtest/_doc/1(根据文档id返回文档信息)
返回结果
{
"_index" : "ajtest",
"_type" : "_doc",
"_id" : "1",
"_version" : 2,
"_seq_no" : 2,
"_primary_term" : 1,
"found" : true,
"_source" : {
"user" : "ajcb",
"create_time" : "2020-08-02T14:12:12",
"remark" : "elasticsearch test"
}
}
Index文档
Index 和create文档不同,如果文档不存在,会新建文档,否则现有文档会被删除,新建文档索引,且版本信息+1
### Index & Update
#Update 指定 ID (先删除,在写入)
PUT ajtest/_doc/1
{
"user":"cb"
}
update文档
update文档不会删除,只是数据表更新
POST ajtest/_update/1
{
"doc":{
"user":"jj",
"age":30
}
}
Delete 文档
根据文档id删除文档 DELETE ajtest/_doc/1
Bulk API
-
支持一次api调用中,对不同的索引进行操作
-
支持四种类型操作
- Index
- create
- update
- delete
-
可以在uri中指定index,也可在请求的payload中进行
-
操作中单条操作失败,并不影响其他操作
-
返回结果包括一条操作执行的结果
POST _bulk
{ "index" : { "_index" : "test", "_id" : "1" } }
{ "field1" : "value1" }
{ "delete" : { "_index" : "test", "_id" : "1" } }
{ "create" : { "_index" : "test2", "_id" : "3" } }
{ "field1" : "value3" }
{ "update" : {"_id" : "1", "_index" : "test"} }
{ "doc" : {"field2" : "value2"} }
批量读取-mget
GET /_mget
{
"docs" : [
{
"_index" : "test",
"_id" : "1"
},
{
"_index" : "test",
"_id" : "2"
}
]
}
常见错误
原文地址