【Elasticsearch7.0】文档接口之delete接口
简介
删除接口根据id删除具体文档,具体例子为:
curl -XDELETE "http://127.0.0.1:9200/test/_doc/1?pretty"
返回结果为:
{
"_index" : "test",
"_type" : "_doc",
"_id" : "1",
"_version" : 4,
"result" : "deleted",
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 7,
"_primary_term" : 6
}
乐观并发控制
可以通过参数if_seq_no和if_primary_term来控制修改的数据是否是最新的,如果不是最新的,那么会报VersionConflictException异常,并返回状态为409,_seq_no和_primary_term可以从查询接口中返回,如:
curl -XDELETE "http://127.0.0.1:9200/test/_doc/1?pretty&if_seq_no=362&if_primary_term=2"
返回结果为:
{
"error" : {
"root_cause" : [
{
"type" : "version_conflict_engine_exception",
"reason" : "[1]: version conflict, required seqNo [362], primary term [2]. but no document was found",
"index_uuid" : "sNvURoEgQX-a2VLHwJt59Q",
"shard" : "0",
"index" : "test"
}
],
"type" : "version_conflict_engine_exception",
"reason" : "[1]: version conflict, required seqNo [362], primary term [2]. but no document was found",
"index_uuid" : "sNvURoEgQX-a2VLHwJt59Q",
"shard" : "0",
"index" : "test"
},
"status" : 409
}
版本控制
每个文档都有版本号,删除文档的时候可以带上版本号,确保我们要删除的文档已经被删除了,在这期间没有修改过。每次写或者删除都会对版本号进行自增,删除文档的版本号在短时间内还可以使用,防止并发操作,可以使用index.gc_deletes来设置时间长度,默认是60秒。
路由
如果新增文档的时候,使用了路由,那么在删除文档的时候也需要带上新增文档时的路由,如:
curl -XDELETE "http://127.0.0.1:9200/test/_doc/1?pretty&routing=kimchy"
返回结果为:
{
"_index" : "test",
"_type" : "_doc",
"_id" : "1",
"_version" : 1,
"result" : "not_found",
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 8,
"_primary_term" : 6
}
例子中会基于用户进行路由,在删除id为1的文档,如果没有路由到正确的位置,那么将无法删除数据。如果在映射中设置了_routing为required,但是在删除的时候没有指定路由,删除请求将报RoutingMissingException异常。
自动索引创建
如果在创建索引的时候,使用了外部版本号控制,如果索引还没有创建,但此时执行了删除文档的操作,那么会自动创建索引。
分布式
删除操作将散列为特定的分片ID, 然后它被重定向到该id组中的主分片,并复制到该id组内的分片副本。
等活跃分片
如果设置了wait_for_active_shards参数,那么需要一定数据的活跃分片存在,才能执行删除操作。
刷新
控制做的操作什么时候生效。
超时
主分片执行删除操作的时候,可能出现不可用的情况,可能主分片在恢复或者在重新选举,默认情况下,删除操作会等待1分钟,如果在1分钟内主分片都没办法处理请求,那么该请求将失败。可以通过timeout参数来自己决定等待多时时间,如:
curl -XDELETE "http://127.0.0.1:9200/test/_doc/1?pretty&timeout=5m"
返回结果为:
{
"_index" : "test",
"_type" : "_doc",
"_id" : "1",
"_version" : 2,
"result" : "not_found",
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 9,
"_primary_term" : 6
}
也可以关注我的公众号:程序之声
关注公众号,领取更多资源。