本节我们来讲解一下ES中文档的相关操作
一:索引/更新文档
ES中索引和更新文档都是PUT
操作。
PUT /{IndexName}/{TypeName}/{ID}
比如我又一条测试文档如下:
{
"took" : 1,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : 1,
"max_score" : 1.0,
"hits" : [
{
"_index" : "user",
"_type" : "introduce",
"_id" : "1",
"_score" : 1.0,
"_source" : {
"name" : "jack",
"age" : 20,
"gender" : "male"
}
}
]
}
}
索引一条新文档
PUT /user/introduce/2
{
"name":"lucy",
"age":18,
"gender":"female"
}
执行检索GET /user/introduce/_search?pretty
查看文档
......
{
"_index" : "user",
"_type" : "introduce",
"_id" : "2",
"_score" : 1.0,
"_source" : {
"name" : "lucy",
"age" : 18,
"gender" : "female"
}
},
{
"_index" : "user",
"_type" : "introduce",
"_id" : "1",
"_score" : 1.0,
"_source" : {
"name" : "jack",
"age" : 20,
"gender" : "male"
}
}
......
这时候就插入了索引了一条新的文档了,接下来我们更新一条文档试试
PUT /user/introduce/1
{
"name":"jone"
}
//返回
{
"_index" : "user",
"_type" : "introduce",
"_id" : "1",
"_version" : 4,
"result" : "updated",
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 3,
"_primary_term" : 1
}
注意到
result
变为了updated
再次执行检索GET /user/introduce/_search?pretty
查看文档
........
"hits" : [
{
"_index" : "user",
"_type" : "introduce",
"_id" : "2",
"_score" : 1.0,
"_source" : {
"name" : "lucy",
"age" : 18,
"gender" : "female"
}
},
{
"_index" : "user",
"_type" : "introduce",
"_id" : "1",
"_score" : 1.0,
"_source" : {
"name" : "jone"
}
}
]
.......
注意到没有,
_id
为1的文档里面只有name
一个字段了,age
和gender
都没了。这说明PUT
是对整个文档更新而不是文档中的某一个或某几个字段更新
文档局部字段更新POST
我先还原数据,然后再对某几个字段更新
POST /{IndexName}/{TypeName}/{ID}/_update
{
"doc":{}
}
POST /user/introduce/1/_update
{
"doc":{
"name":"jone",
"age":22
}
}
POST也可以创建一个文档
POST /user/introduce?pretty
{
"age":20
}
//返回
{
"_index" : "user",
"_type" : "introduce",
"_id" : "VXetwmkBA0w1SMUATD7Z",
"_version" : 1,
"result" : "created",
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 0,
"_primary_term" : 1
}
系统会自动分配
_id
这一点和MongoDB
是一样的
二:删除文档
DELETE /{IndexName}/{TypeName}/{ID}?pretty