PUT lglbc_crud
{
"mappings": {
"properties": {
"age":{
"type": "integer"
},
"stu_no":{
"type": "keyword"
},
"score":{
"type": "float"
},
"birth":{
"type":"date"
}
}
}
}
POST lglbc_crud/_doc/1
{
"age":10,
"stu_no":"1301098762",
"score":90.8,
"birth":"2023-07-01"
}
PUT lglbc_crud/_doc/1
{
"age":15,
"stu_no":"1301098762"
}
POST lglbc_crud/_update/1
{
"doc": {
"age": 18,
"stu_no": "1301098762"
}
}
GET lglbc_crud/_doc/1
DELETE lglbc_crud/_doc/1
每次查询、删除、更新等操作,都会与ES建立一次连接,这会导致大量的请求打在ES服务器上面,从而间接导致数据索引变慢,那么ES是不是可以搞一个批量请求提交,多个操作都在一个请求中完成?答案当然是可以的啦,那我们看下怎么操作
POST lglbc_bulk/_bulk
{"index":{"_id":"1"}}
{"id":1,"name":"乐哥聊编程"}
{"update":{"_id":"1"}}
{"doc":{"id":1,"name":"乐哥聊编程3"}}
执行次请求后,做一次查询,可以看到name为“乐哥聊编程3”
POST lglbc_bulk/_bulk
{"index":{"_id":"1"}}
{"id":1,"name":"乐哥聊编程"}
{"update":{"_id":"1"}}
{"doc":{"id":1,"name":"乐哥聊编程3"}}
{"delete":{"_id":"1"}}
执行完这个,数据将被删除
在产线环境,我们都是使用静态mapping,用了一段时间后,业务需求有变动,我们需要更新字段类型或者数据量太大,我们需要扩展分片数量,但是经过前面的学习,大家都知道,这些都是无法修改的,所以我们的解决办法通常是重建索引,然后将老数据给merge过去,那我们来看下ES如何实现这个功能
PUT lglbc_reindex_old/_doc/1
{
"name":"乐哥聊编程",
"count":"10"
}
GET lglbc_reindex_old
{
"lglbc_reindex_old": {
"aliases": {},
"mappings": {
"properties": {
"count": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"name": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
},
"settings": {
"index": {
"routing": {
"allocation": {
"include": {
"_tier_preference": "data_content"
}
}
},
"number_of_shards": "1",
"provided_name": "lglbc_reindex_old",
"creation_date": "1690618771362",
"number_of_replicas": "1",
"uuid": "x23pbFDvQl2nNQg0tfRyBQ",
"version": {
"created": "8090099"
}
}
}
}
}
创建新索引,指定分片2个,副本2个,name:keyword,count:long
PUT lglbc_reindex_new
{
"mappings": {
"properties": {
"name": {
"type": "keyword"
},
"count": {
"type": "long"
}
}
},
"settings": {
"number_of_shards": 3,
"number_of_replicas": 2
}
}
看下配置
{
"lglbc_reindex_new": {
"aliases": {},
"mappings": {
"properties": {
"count": {
"type": "long"
},
"name": {
"type": "keyword"
}
}
},
"settings": {
"index": {
"routing": {
"allocation": {
"include": {
"_tier_preference": "data_content"
}
}
},
"number_of_shards": "3",
"provided_name": "lglbc_reindex_new",
"creation_date": "1690618970812",
"number_of_replicas": "2",
"uuid": "sNl1jnMoSVukb3ii3lO9Rg",
"version": {
"created": "8090099"
}
}
}
}
}
POST _reindex
{
"source": {"index": "lglbc_reindex_old"},
"dest": {"index": "lglbc_reindex_new"}
}
GET lglbc_reindex_new/_search
{
"took": 4,
"timed_out": false,
"_shards": {
"total": 3,
"successful": 3,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": 1,
"hits": [
{
"_index": "lglbc_reindex_new",
"_id": "1",
"_score": 1,
"_source": {
"name": "乐哥聊编程",
"count": "10"
}
}
]
}
}