文章目录
![在这里插入图片描述](https://img-blog.csdnimg.cn/1557a08a2a9c43bfaef79eb79159c721.png)
概念
es中有三个概念要清楚,分别为
-
索引、映射和文档(不用死记硬背,大概有个印象就可以)
- 索引可理解为MySQL数据库;
- 映射可理解为MySQL的表结构;
- 文档可理解为MySQL表中的每行数据
静态映射和动态映射
-
上面已经介绍了,映射可理解为MySQL的表结构,在MySQL中,向表中插入数据是需要先创建表结构的;
-
但在es中不必这样,可以直接插入文档,es可以根据插入的文档(数据),动态的创建映射(表结构),这就是动态映射;
-
而静态映射是指,在创建文档时,手动添加文档映射,类似于MySQL创建表结构一样;
-
下面为es根据插入的数据推断出的字段类型规则:
下面为针对索引、文档以及映射编写的CRUD
索引相关操作
创建索引
json
中指定了分片和副本;
PUT /{索引名称}
{
"settings": {
"number_of_shards": 3, // 分片数量
"number_of_replicas": 1 // 副本数量
}
}
响应
{
"acknowledged": true,
"shards_acknowledged": true,
"index": "blog"
}
更新副本
Elasticsearch
允许更新索引副本数量
PUT /{索引名字}/_settings
{
"number_of_replicas": 2
}
查看索引
- 查看索引有多个命令
GET /{索引名字}
GET /{索引名字}/_settings
GET /{索引名字1},{索引名字} // 多个索引
GET /_all/_settings // 所有索引
删除索引
- 删除索引之后,索引中的文档就会不存在,建议删除之前备份;
DELETE /{索引名字}
索引的打开与关闭
Elasticsearch
中,索引是有打开和关闭状态的,关闭的索引,几乎不占用资源;- 已经关闭的索引不可以进行读写;
POST /{索引名字}/_close // 关闭索引
POST /{索引名字}/_open // 开启索引
POST /_all/_close // 打开所有
POST /_all/_open // 关闭所有
收缩索引
- 一个索引的分片初始化以后是无法再做修改的,但可以使用shrink index AP提供的缩小索引分片数机制;
索引别名
- 索引别名就是给一个索引或者多个索引起的另一个名字,下面为给索引blog取别名为blog1;
POST /_aliases
{
"actions": [
{
"add": {
"index": "blog",
"alias": "blog1"
}
}
]
}
查询索引别名
GET /_aliases
返回结果
{
".kibana_1": {
"aliases": {
".kibana": {}
}
},
"blog": {
"aliases": {
"blog1": {}
}
}
}
文档相关操作
新建文档
- id为空,则系统自动生成
POST /{索引名称}/{文档名称}/{id}
{
"title": "我是标题",
"content": "我是内容"
}
响应
{
"_index": "blog", // 所在索引
"_type": "article", // 所在文档
"_id": "otl3EYIBIy80TGr00MPx", // 随机id
"_version": 1, // 版本号
"result": "created",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
},
"_seq_no": 0,
"_primary_term": 1
}
查询文档
GET/{索引名称}/{文档名称}/{id}
响应
{
"_index": "blog",
"_type": "article",
"_id": "otl3EYIBIy80TGr00MPx",
"_version": 1,
"_seq_no": 0,
"_primary_term": 1,
"found": true,
"_source": {
"title": "我是标题",
"content": "我是内容"
}
}
更新文档
- 实际上
Elasticsearch
并不在原有的基础上进行更新; - 新增文档没有什么区别的,
elasticSearch
会判断id是否存在,如果存在,即更新,否则新增; - 更新之后,
_version
版本号也会自增+1;
POST /blog/article/otl3EYIBIy80TGr00MPx
{
"title": "我是标题1",
"content": "我是内容1"
}
删除文档
DELETE /blog/article/otl3EYIBIy80TGr00MPx
映射相关操作
查询文档映射
- 如果对es检索依赖比较严重的话,那么并不推荐开启动态映射;
GET /{索引}/_mappings
响应(此映射为es根据文档创建的动态映射)
{
"blog": {
"mappings": {
"properties": {
"content": {
"type": "text", // text类型
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"title": {
"type": "text", // text类型
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
}
}
}
创建静态映射
PUT /{索引名称}
{
"properties":{
"content":{
"type":"text",
"fields":{
"keyword":{
"type":"keyword",
"ignore_above":256
}
}
},
"title":{
"type":"text",
"fields":{
"keyword":{
"type":"keyword",
"ignore_above":256
}
}
}
}
}
响应
{
"acknowledged": true,
"shards_acknowledged": true,
"index": "user"
}
创建索引并添加映射
PUT /{索引名称}
{
"mappings": {
"properties": {
"name":{
"type":"keyword"
},
"age":{
"type":"integer"
},
"address":{
"type":"text"
}
}
}
}