4. 索引数据的增删改查
1. 使用rest端点对索引映射中的数据进行crud
PUT test33
{"mappings": {"properties": {"id":{"type": "integer"},"sex":{"type": "boolean"},"name":{"type": "text","fields": {"keyword":{"type":"keyword","ignore_above":256}}},"born":{"type": "date","format": "yyyy-MM-dd HH:mm:ss"},"location":{"type": "geo_point"}}}
}
{"acknowledged" : true,"shards_acknowledged" : true,"index" : "test33"
}
插入数据:
POST test33/_doc/1
{"id":1,"sex":true,"name":"张三","born":"2025-01-01 00:00:00","location":{"lat":41.12,"lon":"-71.34"}
}
{"_index" : "test33","_type" : "_doc","_id" : "1","_version" : 1,"result" : "created","_shards" : {"total" : 2,"successful" : 1,"failed" : 0},"_seq_no" : 0,"_primary_term" : 1
}
查询插入的数据:GET test33/_doc/1
{"_index" : "test33","_type" : "_doc","_id" : "1","_version" : 1,"_seq_no" : 0,"_primary_term" : 1,"found" : true,"_source" : {"id" : 1,"sex" : true,"name" : "张三","born" : "2025-01-01 00:00:00","location" : {"lat" : 41.12,"lon" : "-71.34"}}
}
对数据进行修改:
POST test33/_update/1
{"doc": {"sex":false,"born":"1999-09-09 00:00:00"}
}
{"_index" : "test33","_type" : "_doc","_id" : "1","_version" : 2,"result" : "updated","_shards" : {"total" : 2,"successful" : 1,"failed" : 0},"_seq_no" : 1,"_primary_term" : 1
}
上面的请求使用了_update端点进行数据修改,这时只需要传递主键和需要修改的字段内容,对于无须修改的自带可以不用提供。
删除数据:delete test33/_doc/1
2. 使用乐观锁进行并发控制
由于elasticsearch不支持事务管理,自然也就没有事务的隔离级别。由于无法保证修改请求是按顺序到达elasticsearch的,需要防止低版本的修改请求把高版本的数据覆盖,这时就需要使用乐观锁进行并发控制。
乐观锁的实现是基于版本号或者时间戳进行的。