目录
1. Elasticsearch 简介
2. 安装与启动
方式 1:Docker 快速安装(推荐)
方式 2:手动安装
3. 基础操作
3.1 创建索引
3.2 插入文档
3.3 查询文档
3.4 更新文档
3.5 删除文档
4. 高级查询
4.1 布尔查询
4.2 范围查询
4.3 通配符查询
5. 聚合分析
5.1 统计年龄分布
5.2 计算平均值
6. 自定义分析器
6.1 创建分词器
6.2 应用分析器到索引
7. 集群管理
7.1 启用集群发现
7.2 添加节点
8. 安全配置(基础)
8.1 生成证书
8.2 创建用户
8.3 启用 HTTPS
9. 性能优化
9.1 索引优化
9.2 冷热架构
10. 实战案例
案例:电商商品搜索
Elasticsearch 的分步教程,涵盖从基础到进阶的核心内容,适合快速上手和实践。
_doc
。# 拉取 Elasticsearch 镜像
docker pull docker.elastic.co/elasticsearch/elasticsearch:7.16.0
# 启动容器(默认端口 9200)
docker run -d --name es -p 9200:9200 docker.elastic.co/elasticsearch/elasticsearch:7.16.0
cd elasticsearch-7.16.0
bin/elasticsearch
# 创建名为 "users" 的索引
curl -X PUT "localhost:9200/users"
# 插入一条用户数据
curl -X POST "localhost:9200/users/_doc" -H 'Content-Type: application/json' -d'
{
"name": "张三",
"age": 30,
"email": "[email protected]"
}'
# 查找所有文档
curl -X GET "localhost:9200/users/_doc/_search?pretty"
# 根据 ID 查询
curl -X GET "localhost:9200/users/_doc/1?pretty"
curl -X POST "localhost:9200/users/_doc/1/_update" -H 'Content-Type: application/json' -d'
{
"doc": {
"age": 31
}
}'
curl -X DELETE "localhost:9200/users/_doc/1"
{
"query": {
"bool": {
"must": [{"match": {"name": "张三"}}],
"filter": [{"range": {"age": {"gte": 25}}}]
}
}
}
{
"query": {
"range": {
"age": {
"gte": 20,
"lte": 30
}
}
}
}
{
"query": {
"wildcard": {
"email": "*example.com"
}
}
}
{
"aggs": {
"age_distribution": {
"histogram": {
"field": "age",
"interval": 10
}
}
}
}
{
"aggs": {
"average_age": {
"avg": {
"field": "age"
}
}
}
}
{
"analysis": {
"analyzer": {
"custom_keyword": {
"type": "keyword",
"tokenizer": "keyword"
}
}
}
}
curl -X PUT "localhost:9200/my_index" -H 'Content-Type: application/json' -d'
{
"settings": {
"analysis": {
"analyzer": {
"default_search": {
"type": "standard"
},
"default_index": {
"type": "custom_keyword"
}
}
}
}
}'
编辑 elasticsearch.yml
:
cluster.name: my-es-cluster
node.name: node-1
network.host: 0.0.0.0
discovery.seed_hosts: ["127.0.0.1:9300"]
在另一台机器启动 Elasticsearch 并配置相同 cluster.name
,节点会自动加入集群。
bin/elasticsearch-certutil ca
bin/elasticsearch-certutil cert --ca elastic-stack-ca.p12
bin/elasticsearch-users useradd es_admin -p admin123 -r superuser
编辑 elasticsearch.yml
:
xpack.security.enabled: true
http.ssl.enabled: true
http.ssl.key: path/to/es-node.jks
# 强制合并分段
curl -X POST "localhost:9200/users/_forcemerge?max_num_segments=1"
使用 ILM(Index Lifecycle Management)策略将数据迁移至冷存储。
{
"mappings": {
"dynamic": false,
"properties": {
"title": {"type": "text"},
"price": {"type": "float"},
"category": {"type": "keyword"}
}
}
}
curl -X POST "localhost:9200/products/_doc" -d'
{
"title": "iPhone 14 Pro",
"price": 9999.0,
"category": "electronics"
}'
{
"query": {
"match": {
"title": "iPhone 14"
}
}
}
建议结合实际项目场景深入练习,并关注官方更新以获取最新特性!