Elasticsearch学习总结

4 阅读11分钟

Elasticsearch学习总结

目录

  1. Elasticsearch概述
  2. 核心架构
  3. 核心概念
  4. 索引管理
  5. 数据操作
  6. 搜索查询
  7. 聚合分析
  8. 集群管理
  9. 性能优化
  10. 最佳实践

Elasticsearch概述

什么是Elasticsearch?

Elasticsearch是一个基于Lucene的开源、分布式、RESTful搜索引擎。它提供了强大的全文搜索能力,支持实时数据分析,具有高可扩展性和高可用性。

核心特性

  1. 分布式架构: 支持集群部署,自动分片和副本
  2. 实时搜索: 毫秒级搜索响应
  3. 全文检索: 强大的全文搜索和分析能力
  4. 多语言支持: 支持多种编程语言的客户端
  5. RESTful API: 简单易用的HTTP接口
  6. 可扩展性: 水平扩展,支持PB级数据
  7. 高可用性: 自动故障转移和数据恢复
  8. 灵活的数据模型: 支持结构化、非结构化数据

应用场景

1. 全文搜索

  • 网站搜索
  • 电商商品搜索
  • 文档搜索

2. 日志分析

  • 应用日志分析
  • 系统监控
  • 安全审计

3. 数据分析

  • 业务数据分析
  • 实时仪表盘
  • 数据可视化

4. 地理搜索

  • 位置服务
  • 地理围栏
  • 附近搜索

版本演进

版本发布时间主要特性
1.x2014-2015基础功能稳定
2.x2015-2016性能优化、Pipeline
5.x2016-2017Ingest Node、Painless脚本
6.x2017-2018SQL支持、索引生命周期管理
7.x2019-2020向量搜索、机器学习
8.x2021-安全性增强、性能提升

核心架构

整体架构

┌─────────────────────────────────────────────────────────┐
│                  Elasticsearch Cluster                   │
├─────────────────────────────────────────────────────────┤
│                                                          │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐ │
│  │   Node 1     │  │   Node 2     │  │   Node 3     │ │
│  │              │  │              │  │              │ │
│  │ Master Node  │  │ Data Node    │  │ Coordinating │ │
│  │ Data Node    │  │              │  │ Node         │ │
│  │              │  │              │  │              │ │
│  │ ┌──────────┐ │  │ ┌──────────┐ │  │ ┌──────────┐ │ │
│  │ │Index A   │ │  │ │Index B   │ │  │ │          │ │ │
│  │ │Shard 1   │ │  │ │Shard 2   │ │  │ │          │ │ │
│  │ │Shard 2   │ │  │ │Shard 3   │ │  │ │          │ │ │
│  │ └──────────┘ │  │ └──────────┘ │  │ └──────────┘ │ │
│  └──────────────┘  └──────────────┘  └──────────────┘ │
│                                                          │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐ │
│  │   Node 4     │  │   Node 5     │  │   Node N     │ │
│  │              │  │              │  │              │ │
│  │ Data Node    │  │ Ingest Node  │  │ Data Node    │ │
│  │              │  │              │  │              │ │
│  │ ┌──────────┐ │  │ ┌──────────┐ │  │ ┌──────────┐ │ │
│  │ │Index C   │ │  │ │Pipeline  │ │  │ │Index D   │ │ │
│  │ │Shard 4   │ │  │ │Processor │ │  │ │Shard 5   │ │ │
│  │ │Shard 5   │ │  │ └──────────┘ │  │ │Shard 6   │ │ │
│  │ └──────────┘ │  │              │  │ └──────────┘ │ │
│  └──────────────┘  └──────────────┘  └──────────────┘ │
│                                                          │
└─────────────────────────────────────────────────────────┘
         │                              │
         │                              │
┌────────┴──────┐              ┌───────┴────────┐
│   Clients     │              │   Monitoring   │
│               │              │                │
│ ┌───────────┐ │              │ ┌────────────┐ │
│ │ HTTP/REST │ │              │ │ Kibana     │ │
│ │ Client    │ │              │ │ Grafana    │ │
│ └───────────┘ │              │ └────────────┘ │
└──────────────┘              └────────────────┘

节点类型

1. Master Node (主节点)

职责:

  • 管理集群状态
  • 处理索引创建和删除
  • 分配分片到节点
  • 协调集群级别的操作

配置:

node.roles: [master]
2. Data Node (数据节点)

职责:

  • 存储索引数据
  • 执行CRUD操作
  • 执行聚合查询
  • 处理搜索请求

配置:

node.roles: [data]
3. Coordinating Node (协调节点)

职责:

  • 处理客户端请求
  • 分发请求到相关节点
  • 合并结果返回给客户端
  • 不存储数据

配置:

node.roles: []
4. Ingest Node (摄取节点)

职责:

  • 预处理数据
  • 执行Pipeline转换
  • 数据清洗和格式化

配置:

node.roles: [ingest]
5. Machine Learning Node (机器学习节点)

职责:

  • 运行机器学习作业
  • 异常检测
  • 预测分析

配置:

node.roles: [ml]

核心概念

1. Index (索引)

定义: 索引是相似文档的集合,类似于关系数据库中的数据库。

特点:

  • 一个索引包含多个类型(Type,已废弃)
  • 每个索引有自己的映射(Mapping)
  • 支持多个分片和副本

命名规则:

  • 必须小写
  • 不能包含特殊字符(除_、-、+)
  • 不能以.开头
  • 不能包含,

示例:

索引名称示例:
- product-index
- user-log-20260312
- order_data

2. Document (文档)

定义: 文档是索引中的基本数据单元,以JSON格式存储。

特点:

  • 每个文档有唯一的ID
  • 文档包含多个字段(Field)
  • 支持嵌套结构
  • 文档是无模式的

示例:

{
  "_index": "product-index",
  "_type": "_doc",
  "_id": "1",
  "_score": 1.0,
  "_source": {
    "name": "iPhone 15",
    "price": 5999,
    "category": "phone",
    "tags": ["apple", "smartphone"],
    "created_at": "2026-03-12T10:00:00"
  }
}

3. Field (字段)

定义: 字段是文档中的属性,类似于数据库中的列。

字段类型:

  • 字符串: text(全文搜索), keyword(精确匹配)
  • 数值: long, integer, short, byte, double, float
  • 日期: date
  • 布尔: boolean
  • 二进制: binary
  • 地理: geo_point, geo_shape
  • 嵌套: nested, object

示例:

{
  "name": {
    "type": "text",
    "fields": {
      "keyword": {
        "type": "keyword"
      }
    }
  },
  "price": {
    "type": "double"
  },
  "created_at": {
    "type": "date",
    "format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis"
  }
}

4. Mapping (映射)

定义: 映射定义了索引中字段的类型和属性。

动态映射:

PUT my-index
{
  "mappings": {
    "dynamic": true,
    "properties": {
      "title": {
        "type": "text"
      },
      "tags": {
        "type": "keyword"
      }
    }
  }
}

显式映射:

PUT product-index
{
  "mappings": {
    "properties": {
      "name": {
        "type": "text",
        "analyzer": "ik_max_word",
        "fields": {
          "keyword": {
            "type": "keyword"
          }
        }
      },
      "price": {
        "type": "double"
      },
      "category": {
        "type": "keyword"
      },
      "created_at": {
        "type": "date"
      }
    }
  }
}

5. Shard (分片)

定义: 分片是索引的水平分割单元,每个分片是一个完整的Lucene索引。

分片类型:

  • 主分片(Primary Shard): 原始数据分片
  • 副本分片(Replica Shard): 主分片的副本

分片配置:

PUT my-index
{
  "settings": {
    "number_of_shards": 3,
    "number_of_replicas": 2
  }
}

分片分配:

Index "my-index"
├── Primary Shard 0 → Node 1
├── Primary Shard 1 → Node 2
├── Primary Shard 2 → Node 3
├── Replica Shard 0 → Node 2, Node 3
├── Replica Shard 1 → Node 1, Node 3
└── Replica Shard 2 → Node 1, Node 2

6. Analyzer (分析器)

定义: 分析器用于处理文本,将文本转换为可搜索的词项。

组成:

  • 字符过滤器(Character Filter): 处理原始字符
  • 分词器(Tokenizer): 将文本分割成词项
  • 词项过滤器(Token Filter): 处理词项

内置分析器:

  • standard: 标准分词器
  • ik_max_word: 中文细粒度分词
  • ik_smart: 中文智能分词
  • whitespace: 空格分词
  • simple: 非字母字符分割

自定义分析器:

PUT my-index
{
  "settings": {
    "analysis": {
      "analyzer": {
        "my_analyzer": {
          "type": "custom",
          "tokenizer": "standard",
          "filter": [
            "lowercase",
            "stop"
          ]
        }
      }
    }
  },
  "mappings": {
    "properties": {
      "content": {
        "type": "text",
        "analyzer": "my_analyzer"
      }
    }
  }
}

测试分析器:

POST my-index/_analyze
{
  "analyzer": "ik_max_word",
  "text": "中华人民共和国"
}

// 结果
{
  "tokens": [
    {"token": "中华人民共和国", "start_offset": 0, "end_offset": 7},
    {"token": "中华人民", "start_offset": 0, "end_offset": 4},
    {"token": "中华", "start_offset": 0, "end_offset": 2},
    {"token": "华人", "start_offset": 1, "end_offset": 3},
    {"token": "人民共和国", "start_offset": 2, "end_offset": 7},
    {"token": "人民", "start_offset": 2, "end_offset": 4},
    {"token": "共和国", "start_offset": 4, "end_offset": 7},
    {"token": "共和", "start_offset": 4, "end_offset": 6},
    {"token": "国", "start_offset": 6, "end_offset": 7}
  ]
}

索引管理

创建索引

基本创建
PUT my-index
{
  "settings": {
    "number_of_shards": 3,
    "number_of_replicas": 1
  },
  "mappings": {
    "properties": {
      "title": {
        "type": "text"
      },
      "content": {
        "type": "text"
      }
    }
  }
}
完整配置
PUT product-index
{
  "settings": {
    "number_of_shards": 3,
    "number_of_replicas": 2,
    "index": {
      "max_result_window": 10000,
      "refresh_interval": "1s"
    },
    "analysis": {
      "analyzer": {
        "ik_max_word": {
          "type": "custom",
          "tokenizer": "ik_max_word"
        }
      }
    }
  },
  "mappings": {
    "properties": {
      "product_id": {
        "type": "keyword"
      },
      "name": {
        "type": "text",
        "analyzer": "ik_max_word",
        "fields": {
          "keyword": {
            "type": "keyword"
          }
        }
      },
      "price": {
        "type": "double"
      },
      "category": {
        "type": "keyword"
      },
      "description": {
        "type": "text",
        "analyzer": "ik_max_word"
      },
      "stock": {
        "type": "integer"
      },
      "created_at": {
        "type": "date",
        "format": "yyyy-MM-dd HH:mm:ss"
      }
    }
  }
}

查看索引

查看所有索引
GET _cat/indices?v
查看索引信息
GET product-index
查看映射
GET product-index/_mapping

删除索引

DELETE product-index

批量删除:

DELETE product-*, test-*

索引模板

创建模板
PUT _index_template/product-template
{
  "index_patterns": ["product-*"],
  "template": {
    "settings": {
      "number_of_shards": 3,
      "number_of_replicas": 2
    },
    "mappings": {
      "properties": {
        "product_id": {
          "type": "keyword"
        },
        "name": {
          "type": "text",
          "analyzer": "ik_max_word"
        },
        "price": {
          "type": "double"
        }
      }
    }
  }
}
查看模板
GET _index_template/product-template
删除模板
DELETE _index_template/product-template

索引生命周期管理(ILM)

创建ILM策略
PUT _ilm/policy/product-policy
{
  "policy": {
    "phases": {
      "hot": {
        "actions": {
          "rollover": {
            "max_size": "50GB",
            "max_age": "30d"
          }
        }
      },
      "warm": {
        "min_age": "30d",
        "actions": {
          "forcemerge": {
            "max_num_segments": 1
          }
        }
      },
      "cold": {
        "min_age": "90d",
        "actions": {
          "freeze": {}
        }
      },
      "delete": {
        "min_age": "180d",
        "actions": {
          "delete": {}
        }
      }
    }
  }
}
应用策略
PUT product-000001
{
  "settings": {
    "lifecycle.name": "product-policy",
    "lifecycle.rollover_alias": "product"
  }
}

数据操作

创建文档

指定ID创建
PUT product-index/_doc/1
{
  "product_id": "P001",
  "name": "iPhone 15 Pro",
  "price": 7999,
  "category": "phone",
  "description": "最新款苹果手机",
  "stock": 100,
  "created_at": "2026-03-12 10:00:00"
}
自动ID创建
POST product-index/_doc
{
  "product_id": "P002",
  "name": "MacBook Pro",
  "price": 14999,
  "category": "computer",
  "description": "苹果笔记本电脑",
  "stock": 50
}

查询文档

根据ID查询
GET product-index/_doc/1
批量查询
GET product-index/_mget
{
  "ids": ["1", "2", "3"]
}
查询所有文档
GET product-index/_search
{
  "query": {
    "match_all": {}
  }
}

更新文档

全量更新
PUT product-index/_doc/1
{
  "product_id": "P001",
  "name": "iPhone 15 Pro Max",
  "price": 8999,
  "category": "phone",
  "description": "最新款苹果手机",
  "stock": 80
}
局部更新
POST product-index/_update/1
{
  "doc": {
    "price": 8999,
    "stock": 80
  }
}
脚本更新
POST product-index/_update/1
{
  "script": {
    "source": "ctx._source.price += params.increment",
    "lang": "painless",
    "params": {
      "increment": 100
    }
  }
}

删除文档

根据ID删除
DELETE product-index/_doc/1
根据查询删除
POST product-index/_delete_by_query
{
  "query": {
    "term": {
      "category": "tablet"
    }
  }
}

批量操作

POST _bulk
{ "index": { "_index": "product-index", "_id": "1" } }
{ "product_id": "P001", "name": "iPhone 15", "price": 5999, "category": "phone" }
{ "index": { "_index": "product-index", "_id": "2" } }
{ "product_id": "P002", "name": "MacBook Pro", "price": 14999, "category": "computer" }
{ "create": { "_index": "product-index", "_id": "3" } }
{ "product_id": "P003", "name": "iPad Pro", "price": 6999, "category": "tablet" }
{ "update": { "_index": "product-index", "_id": "1" } }
{ "doc": { "stock": 100 } }
{ "delete": { "_index": "product-index", "_id": "2" } }

搜索查询

基本查询

查询所有
GET product-index/_search
{
  "query": {
    "match_all": {}
  }
}
分页查询
GET product-index/_search
{
  "from": 0,
  "size": 10,
  "query": {
    "match_all": {}
  }
}
排序
GET product-index/_search
{
  "query": {
    "match_all": {}
  },
  "sort": [
    {
      "price": {
        "order": "desc"
      }
    }
  ]
}

全文搜索

match查询
GET product-index/_search
{
  "query": {
    "match": {
      "name": "iPhone"
    }
  }
}
multi_match查询
GET product-index/_search
{
  "query": {
    "multi_match": {
      "query": "苹果",
      "fields": ["name", "description"]
    }
  }
}
phrase查询
GET product-index/_search
{
  "query": {
    "match_phrase": {
      "description": "最新款苹果"
    }
  }
}

精确查询

term查询
GET product-index/_search
{
  "query": {
    "term": {
      "category": "phone"
    }
  }
}
terms查询
GET product-index/_search
{
  "query": {
    "terms": {
      "category": ["phone", "computer"]
    }
  }
}
range查询
GET product-index/_search
{
  "query": {
    "range": {
      "price": {
        "gte": 5000,
        "lte": 10000
      }
    }
  }
}

复合查询

bool查询
GET product-index/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "name": "iPhone"
          }
        }
      ],
      "must_not": [
        {
          "term": {
            "stock": 0
          }
        }
      ],
      "should": [
        {
          "match": {
            "description": "最新款"
          }
        }
      ],
      "filter": [
        {
          "range": {
            "price": {
              "gte": 5000
            }
          }
        }
      ]
    }
  }
}

聚合查询

terms聚合
GET product-index/_search
{
  "size": 0,
  "aggs": {
    "category_count": {
      "terms": {
        "field": "category"
      }
    }
  }
}
range聚合
GET product-index/_search
{
  "size": 0,
  "aggs": {
    "price_ranges": {
      "range": {
        "field": "price",
        "ranges": [
          {
            "to": 5000
          },
          {
            "from": 5000,
            "to": 10000
          },
          {
            "from": 10000
          }
        ]
      }
    }
  }
}
metrics聚合
GET product-index/_search
{
  "size": 0,
  "aggs": {
    "avg_price": {
      "avg": {
        "field": "price"
      }
    },
    "max_price": {
      "max": {
        "field": "price"
      }
    },
    "min_price": {
      "min": {
        "field": "price"
      }
    },
    "sum_price": {
      "sum": {
        "field": "price"
      }
    }
  }
}

聚合分析

桶聚合(Bucket Aggregation)

terms聚合
GET sales-index/_search
{
  "size": 0,
  "aggs": {
    "by_category": {
      "terms": {
        "field": "category",
        "size": 10
      }
    }
  }
}
date_histogram聚合
GET logs-index/_search
{
  "size": 0,
  "aggs": {
    "by_day": {
      "date_histogram": {
        "field": "timestamp",
        "calendar_interval": "day"
      }
    }
  }
}
range聚合
GET product-index/_search
{
  "size": 0,
  "aggs": {
    "price_ranges": {
      "range": {
        "field": "price",
        "ranges": [
          {
            "to": 1000,
            "key": "cheap"
          },
          {
            "from": 1000,
            "to": 5000,
            "key": "normal"
          },
          {
            "from": 5000,
            "key": "expensive"
          }
        ]
      }
    }
  }
}

指标聚合(Metric Aggregation)

统计聚合
GET sales-index/_search
{
  "size": 0,
  "aggs": {
    "price_stats": {
      "stats": {
        "field": "price"
      }
    }
  }
}
百分位聚合
GET sales-index/_search
{
  "size": 0,
  "aggs": {
    "price_percentiles": {
      "percentiles": {
        "field": "price",
        "percents": [1, 5, 25, 50, 75, 95, 99]
      }
    }
  }
}

嵌套聚合

GET sales-index/_search
{
  "size": 0,
  "aggs": {
    "by_category": {
      "terms": {
        "field": "category"
      },
      "aggs": {
        "avg_price": {
          "avg": {
            "field": "price"
          }
        },
        "by_brand": {
          "terms": {
            "field": "brand"
          }
        }
      }
    }
  }
}

集群管理

集群状态

查看集群健康
GET _cluster/health
查看集群状态
GET _cluster/state
查看节点信息
GET _cat/nodes?v

分片管理

查看分片分配
GET _cat/shards?v
手动移动分片
POST _cluster/reroute
{
  "commands": [
    {
      "move": {
        "index": "product-index",
        "shard": 0,
        "from_node": "node1",
        "to_node": "node2"
      }
    }
  ]
}
分片分配决策
GET _cluster/allocation/explain
{
  "index": "product-index",
  "shard": 0,
  "primary": false
}

节点管理

排除节点
PUT _cluster/settings
{
  "transient": {
    "cluster.routing.allocation.exclude._host": "node1.example.com"
  }
}
包含节点
PUT _cluster/settings
{
  "transient": {
    "cluster.routing.allocation.include._host": "node2.example.com"
  }
}

集群设置

动态设置
PUT _cluster/settings
{
  "transient": {
    "indices.query.bool.max_clause_count": 2048
  }
}
持久设置
PUT _cluster/settings
{
  "persistent": {
    "cluster.routing.allocation.enable": "all"
  }
}

性能优化

索引优化

批量索引
POST _bulk
{ "index": { "_index": "product-index" } }
{ "product_id": "P001", "name": "iPhone 15", "price": 5999 }
{ "index": { "_index": "product-index" } }
{ "product_id": "P002", "name": "MacBook Pro", "price": 14999 }
刷新间隔
PUT product-index/_settings
{
  "index": {
    "refresh_interval": "30s"
  }
}
Translog配置
PUT product-index/_settings
{
  "index": {
    "translog.durability": "async",
    "translog.sync_interval": "5s"
  }
}

查询优化

使用filter替代query
GET product-index/_search
{
  "query": {
    "bool": {
      "filter": [
        {
          "term": {
            "category": "phone"
          }
        },
        {
          "range": {
            "price": {
              "gte": 5000
            }
          }
        }
      ]
    }
  }
}
使用_source过滤
GET product-index/_search
{
  "_source": ["name", "price"],
  "query": {
    "match_all": {}
  }
}
使用scroll处理大量数据
GET product-index/_search?scroll=1m
{
  "size": 1000,
  "query": {
    "match_all": {}
  }
}

// 使用scroll_id继续查询
GET _search/scroll
{
  "scroll": "1m",
  "scroll_id": "scroll_id_here"
}

最佳实践

1. 索引设计

命名规范
- 小写字母
- 使用连字符分隔
- 包含时间后缀(如需要)
示例: product-20260312, user-log, order-index
分片策略
- 单个分片大小: 10-50GB
- 分片数量: (数据总量 / 50GB) + 冗余
- 副本数量: 至少1个

2. 映射设计

字段类型选择
{
  "name": {
    "type": "text",
    "analyzer": "ik_max_word",
    "fields": {
      "keyword": {
        "type": "keyword"
      }
    }
  }
}
避免动态映射
PUT my-index/_settings
{
  "index.mapper.dynamic": false
}

3. 查询优化

使用filter缓存
{
  "query": {
    "bool": {
      "filter": [
        {
          "term": {
            "status": "active"
          }
        }
      ]
    }
  }
}
避免深度分页
// 使用search_after
GET product-index/_search
{
  "query": {
    "match_all": {}
  },
  "size": 10,
  "sort": [
    {
      "_id": "asc"
    }
  ],
  "search_after": ["last_document_id"]
}

4. 集群规划

节点配置
Master节点: 3个(奇数)
Data节点: 根据数据量
Coordinating节点: 根据查询量
硬件配置
CPU: 8核以上
内存: 16GB以上
磁盘: SSD, 多块磁盘
网络: 万兆网卡

5. 监控与维护

监控指标
- 集群健康状态
- 节点资源使用率
- 索引性能指标
- 查询性能指标
定期维护
- 清理过期索引
- 优化索引
- 备份重要数据

总结

Elasticsearch作为强大的搜索引擎,提供了丰富的功能和优秀的性能。通过本文档的学习,您应该能够:

  1. 理解Elasticsearch的核心架构和概念
  2. 掌握索引管理和数据操作
  3. 熟悉搜索查询和聚合分析
  4. 了解集群管理和性能优化
  5. 掌握最佳实践

关键要点

  • 分布式: 自动分片和副本
  • 实时: 毫秒级搜索响应
  • 灵活: 支持多种数据类型
  • 可扩展: 水平扩展
  • 易用: RESTful API