一、ES 安装与部署
1.1 单点部署
# 下载 ES
wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-7.17.29-amd64.deb
# 安装
dpkg -i elasticsearch-7.17.29-amd64.deb
# 配置 (/etc/elasticsearch/elasticsearch.yml)
network.host: 0.0.0.0
discovery.type: single-node
# 启动
systemctl start elasticsearch.service
systemctl enable --now elasticsearch.service
1.2 集群部署
# 配置
cluster.name: oldboyedu-linux102-cluster
network.host: 0.0.0.0
discovery.seed_hosts: ["10.0.0.91", "10.0.0.92", "10.0.0.93"]
cluster.initial_master_nodes: ["10.0.0.91", "10.0.0.92", "10.0.0.93"]
# 清空旧数据
rm -rf /var/{log,lib}/elasticsearch/*
# 分发安装包
scp elasticsearch-7.17.29-amd64.deb 10.0.0.92:~
scp elasticsearch-7.17.29-amd64.deb 10.0.0.93:~
# 其他节点安装
dpkg -i elasticsearch-7.17.29-amd64.deb
# 同步配置
scp /etc/elasticsearch/elasticsearch.yml 10.0.0.92:/etc/elasticsearch/
scp /etc/elasticsearch/elasticsearch.yml 10.0.0.93:/etc/elasticsearch/
# 同时启动所有节点
systemctl enable --now elasticsearch.service
二、端口说明
9200 # HTTP/HTTPS 协议,ES 集群对外提供服务的端口
9300 # TCP 协议,ES 集群内部数据传输端口
三、集群状态查询
# 查看集群健康状态
curl 10.0.0.91:9200/_cat/health
curl 10.0.0.91:9200/_cat/health?v
# 查看节点列表
curl 10.0.0.91:9200/_cat/nodes
# 查看集群状态 (green/yellow/red)
curl 10.0.0.91:9200/_cluster/health
四、索引操作
4.1 创建索引
curl -X PUT https://10.0.0.91:9200/oldboyedu-linux
4.2 查看索引
curl 10.0.0.91:9200/_cat/indices
4.3 删除索引
curl -X DELETE https://10.0.0.91:9200/oldboyedu-linux
五、文档操作 (DSL)
5.1 写入数据
curl --location --request POST 'https://10.0.0.91:9200/oldboyedu-linux/_doc/1001' --header 'Content-Type: application/json' --data-raw '{"name": "孙悟空", "hobby": ["蟠桃", "仙丹", "紫霞仙子"]}'
5.2 查询数据
# 查询所有
curl -s https://10.0.0.93:9200/oldboyedu-linux/_search
# 模糊查询
curl -s --location --request GET '10.0.0.93:9200/oldboyedu-linux/_search' --header 'Content-Type: application/json' --data-raw '{"query": {"match": {"hobby": "蟠桃"}}}'
5.3 更新数据
curl --location --request POST 'https://10.0.0.93:9200/oldboyedu-linux/_doc/1003' --header 'Content-Type: application/json' --data-raw '{"docs": {"name": "唐僧"}}'
5.4 删除数据
# 删除文档
curl -s -X DELETE https://10.0.0.93:9200/oldboyedu-linux/_doc/1003
# 删除索引
curl -s -X DELETE https://10.0.0.93:9200/oldboyedu-linux/
六、ES 面试要点
6.1 端口作用
9200 # HTTP/HTTPS - ES 集群对外访问端口
9300 # TCP - ES 集群内部数据传输端口
6.2 集群颜色
green # 所有主分片和副本分片均正常
yellow # 部分副本分片无法访问
red # 部分主分片无法正常访问
6.3 核心概念
index # 索引 (相当于数据库)
shard # 分片 (索引数据分散存储)
replica # 副本 (分片备份,提供读负载均衡)
document # 文档 (索引中的数据记录)
七、快捷命令速查
| 用途 |
命令 |
| 集群状态 |
curl :9200/_cat/health?v |
| 节点列表 |
curl :9200/_cat/nodes |
| 索引列表 |
curl :9200/_cat/indices |
| 查询所有 |
curl :9200/<index>/_search |
| 创建索引 |
curl -X PUT :9200/<index> |
| 删除索引 |
curl -X DELETE :9200/<index> |
| 查看分片 |
curl :9200/_cat/shards |