Elastic分布式搜索,如何对索引(表)进行增删改查管理?
发布于 作者:苏南大叔 来源:程序如此灵动~
Elastic Search
并不是关系数据库,它内部不存在传统意义上的表结构,它管理的数据是一条条索引,可以通俗的理解为常见的关系数据库中的数据表(数据)。所以,苏南大叔把elastic search
中索引的管理行为,看做是一个crud
行为,这样也就更容易对相关行为做更好的理解。
苏南大叔的“程序如此灵动”博客,记录苏南大叔的代码编程经验总结。本文测试环境:win10
,elasticsearch@8.17.1
,kibana@8.17.1
。本文的内容中,都使用kibana
执行elasticsearch
最原始的接口操作。
前文回顾
elastic search
的安装及配置,参考文章:
kibana
的安装及配置:
- https://newsn.net/say/kibana.html
- https://newsn.net/say/elastic-kibana.html
- https://newsn.net/say/elastic-kibana-2.html
elastic search
开启集群:
对分片Shards
和副本Replicas
概念的理解:
选择操作方式
因为原始接口的话,除了GET
操作,还有PUT
/DELETE
/HEAD
等操作,所以,还是在在kibana
的devtools
下进行操作,比较合适:
本文要操作的例子里面,my_index
就是要操作的索引的名字。本文操作的各种结果,还可以通过kibana
的“索引管理”功能里面,进行验证。
索引(表)是否存在
HEAD /my_index
在执行删除或修改之前,可以先查看一下要操作的索引是否存在。存在就返回200 - OK
,不存在会返回404 - Not Found
。
建立索引(表)
索引的建立,分为settings
和mappings
两个部分。settings
部分可以不存在,使用默认。
settings
中规定了分片shards
和副本replicas
的设置情况,分片一经设置,禁止修改。副本数是可有可无可修改的。mappings.properties
,实际上规定了字段的名字和类型,这个是必须的。
PUT /my_index
{
"settings": {
"number_of_shards": 3,
"number_of_replicas": 2
},
"mappings": {
"properties": {
"field1": { "type": "text" },
"field2": { "type": "keyword" }
}
}
}
查看索引(表)
查看索引,其实也有三个操作。查看整体,查看settings
,查看mappings
。
GET /my_index
GET /my_index/_settings
GET /my_index/_mappings
修改索引(表)
修改的话,只需要设置需要修改的部分即可。和“创建”操作基本一致。
PUT /my_index/_mapping
{
"properties": {
"new_field": { "type": "text" }
}
}
但是,需要注意的是:number_of_shards
创建后,原则上不能修改。
PUT /my_index/_settings
{
"number_of_shards": 5
}
会收到报错信息:
{
"error": {
"root_cause": [
{
"type": "illegal_argument_exception",
"reason": "Can't update non dynamic settings [[index.number_of_shards]] for open indices [[my_index/ciQuucKlR7KvNlqwFFZnyg]] unless the `reopen` query parameter is set to true. Alternatively, close the indices, apply the settings changes, and reopen the indices"
}
],
"type": "illegal_argument_exception",
"reason": "Can't update non dynamic settings [[index.number_of_shards]] for open indices [[my_index/ciQuucKlR7KvNlqwFFZnyg]] unless the `reopen` query parameter is set to true. Alternatively, close the indices, apply the settings changes, and reopen the indices"
},
"status": 400
}
删除索引(表)
DELETE /my_index
打开关闭索引
打开和关闭的目的,就是是否允许数据写入。
POST /my_index/_open
POST /my_index/_close
结语
最基础常见的elastic
数据操作,就这么多了。更多elastic
经验文章,请点击:


