基于kibana-7.4版本和Elastisearch-7.4版本结合进行的增删改
新增操作
语法
POST /{index}/_doc/{id}
index: 索引的名称
_doc:固定值,其实就是type,但是7.0之后就废弃了type,所以ES的团队采用了一个固定值_doc的方式来代替type
{id}:数据的id,如果没有写此值,那么就会自动生成一个
- 示例代码:
- 输入
POST /staffs/_doc/1a
{
"name": "shu xian sheng",
"age": 28,
"phone": "15711111111",
"posittion": "java kaifa",
"hobby": [
"lanqiu",
"zuqiu",
"tubu"
]
}
- 输出
{
"_index" : "staffs", 索引的名称
"_type" : "_doc", 固定式 其实就是type
"_id" : "1a", 数据的索引
"_version" : 1, 版本号,用于控制乐观锁
"result" : "created", 表示该条数据是创建的 不是更新的
"_shards" : {
"total" : 2, 有几个shard
"successful" : 1, 写入成功几个shard
"failed" : 0
},
"_seq_no" : 0,
"_primary_term" : 1
}
- 如果将上面的语句再次执行一次,那么数据的操作为更新操作
{
"_index" : "staffs",
"_type" : "_doc",
"_id" : "1a",
"_version" : 2, 版本号加1
"result" : "updated", 表示数据的操作为更新 不是创建了
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 1,
"_primary_term" : 1
}
第二种新增方式
- 不指定数据的索引,那么就会自动创建一个索引
- 示例
- 输入:
POST /staffs/_doc
{
"name": "wang xiao san",
"age": 21,
"phone": "15722222222",
"posittion": "web kaifa",
"hobby": [
"yumaoqiu",
"zuqiu",
"taiqiu"
]
}
- 输出:
{
"_index" : "staffs",
"_type" : "_doc",
"_id" : "Nq_96G0Bs8sg-pU7kn0S", 自动生成的
"_version" : 1,
"result" : "created",
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 2,
"_primary_term" : 1
}
更新操作
方式一:数据的全量替换
语法
POST /{index}/_doc/{id}
或者
PUT /{index}/_doc/{id}
- 会将更新时传入的字段全部替换掉原来存储的数据,如果传入的字段A没有,更新之前的es存储的数据包含字段A,那么该字段会被删除,反之亦然
- 示例
输入:
将age字段删除了,然后修改了电话号码
PUT /staffs/_doc/1a
{
"name": "shu xian sheng",
"phone": "15711111112",
"posittion": "java kaifa",
"hobby": [
"lanqiu",
"zuqiu",
"tubu"
]
}
{
"_index" : "staffs",
"_type" : "_doc",
"_id" : "1a",
"_version" : 8,
"result" : "updated",
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 8,
"_primary_term" : 1
}
查询出的结果
这里面每一个字段的含义会在下一个章节讲解
{
"_index" : "staffs",
"_type" : "_doc",
"_id" : "1a",
"_version" : 8,
"_seq_no" : 8,
"_primary_term" : 1,
"found" : true,
"_source" : {
"name" : "shu xian sheng",
"phone" : "15711111112",
"posittion" : "java kaifa",
"hobby" : [
"lanqiu",
"zuqiu",
"tubu"
]
}
}
方式二,只更新存在的field(推荐)
- 只会更新es中存储的field,如果更新的数据中含有es不存在的field,那么es会将这个数据新增进入
- 语法
POST /{index}/_update/{id}
{
"doc":{
"xx":"xx" 需要更新的值,写在这里面
}
}
es官方建议更新的时候直接去type(_doc)的值,直接写成_update
- 示例
输入:
修改职位和爱好
POST /staffs/_update/1a
{
"doc": {
"posittion": "java gaojikaifazhuanjia ",
"hobby": [
"youyong",
"tiaosheng"
]
}
}
输入的结果
{
"_index" : "staffs",
"_type" : "_doc",
"_id" : "1a",
"_version" : 12,
"result" : "updated", 如果更新的值和原来的值一样,那么就会此处会变为:noop
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 12,
"_primary_term" : 1
}
删除操作
语法
DELETE POST /{index}/_doc/{id}
示例
输入
DELETE /staffs/_doc/1a
输出
{
"_index" : "staffs",
"_type" : "_doc",
"_id" : "1a",
"_version" : 16,
"result" : "deleted",如果该值没有,那么就会显示not_found
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 16,
"_primary_term" : 1
}