10. Elasticsearch 搜索引擎

Elasticsearch 核心原理:倒排索引、分词与 Mapping、查询优化、集群架构与调优实践

Elasticsearch 是全球最流行的分布式搜索引擎,基于 Lucene 构建,提供近实时搜索、聚合分析与全文检索能力。

1. 核心概念

概念类比 RDBMS说明
IndexDatabase索引,逻辑命名空间
TypeTable7.x 已废弃,8.x 移除
DocumentRow一条 JSON 记录
FieldColumn字段
MappingSchema字段类型定义
ShardPartition分片
ReplicaReplica副本

2. 倒排索引

文档:
  Doc1: "Elasticsearch is a search engine"
  Doc2: "Lucene is the core of Elasticsearch"

倒排索引:
  "elasticsearch" → [Doc1, Doc2]
  "search"        → [Doc1]
  "engine"        → [Doc1]
  "lucene"        → [Doc2]
  "core"          → [Doc2]

ES 还存储:

  • Term Frequency (TF):词在文档中出现次数
  • Document Frequency (DF):包含该词的文档数
  • Norms:字段长度归一化因子
  • Positions:词在文档中的位置(用于短语查询)
  • Offsets:字符偏移(用于高亮)

3. 分词与分析器

// 自定义 IK 分词器 + 拼音过滤器
PUT /products
{
  "settings": {
    "analysis": {
      "analyzer": {
        "ik_pinyin": {
          "tokenizer": "ik_max_word",
          "filter": ["pinyin_filter"]
        }
      },
      "filter": {
        "pinyin_filter": {
          "type": "pinyin",
          "keep_separate_first_letter": false,
          "keep_full_pinyin": true,
          "keep_original": true
        }
      }
    }
  },
  "mappings": {
    "properties": {
      "title": {
        "type": "text",
        "analyzer": "ik_max_word",
        "search_analyzer": "ik_smart"
      },
      "price": { "type": "float" },
      "category": { "type": "keyword" },
      "tags": { "type": "keyword" },
      "create_time": { "type": "date" }
    }
  }
}

4. 查询 DSL

// Bool 复合查询
GET /products/_search
{
  "query": {
    "bool": {
      "must": [
        { "multi_match": {
          "query": "手机",
          "fields": ["title^3", "description"]
        }}
      ],
      "filter": [
        { "range": { "price": { "gte": 1000, "lte": 5000 } }},
        { "term": { "category": "电子产品" }}
      ]
    }
  },
  "sort": [
    { "_score": "desc" },
    { "sales": "desc" }
  ],
  "from": 0,
  "size": 20,
  "highlight": {
    "fields": {
      "title": { "pre_tags": ["<em>"], "post_tags": ["</em>"] }
    }
  },
  "aggs": {
    "by_category": {
      "terms": { "field": "category" }
    },
    "price_stats": {
      "stats": { "field": "price" }
    }
  }
}

5. 集群架构

Node 类型:
  - Master: 管理集群状态(3 个候选)
  - Data:   存储数据和执行查询
  - Ingest: 预处理文档(Pipeline)
  - Coordinating: 仅路由请求(大集群专用)
  - ML:     机器学习节点

5.1 分片规划

# 黄金法则
# 分片大小: 10-50GB
# 分片数/节点: < 20
# 堆内存: ≤ 30GB(压缩指针优化)
# 总分片数 ≈ 数据量(GB) / 30

# 创建索引时指定
PUT /logs-2024-01
{
  "settings": {
    "number_of_shards": 3,
    "number_of_replicas": 1,
    "refresh_interval": "30s"
  }
}

5.2 ILM (Index Lifecycle Management)

PUT _ilm/policy/logs_policy
{
  "policy": {
    "phases": {
      "hot": {
        "actions": {
          "rollover": {
            "max_size": "50GB",
            "max_age": "30d"
          }
        }
      },
      "warm": {
        "min_age": "7d",
        "actions": {
          "shrink": { "number_of_shards": 1 },
          "forcemerge": { "max_num_segments": 1 }
        }
      },
      "cold": {
        "min_age": "30d",
        "actions": {
          "allocate": { "require": { "data": "cold" }},
          "freeze": {}
        }
      },
      "delete": {
        "min_age": "90d"
      }
    }
  }
}

6. 性能优化

优化点方法
写入吞吐批量写入 (bulk)、增大 refresh_interval、使用 _bulk
查询性能使用 filter(缓存)、避免深分页 (search_after)、预加载 fielddata
存储禁用 _all、使用 _source filtering、force merge
集群专用协调节点、跨集群复制、冷热分离

总结

  • 分词:中文用 IK,搜索用 ik_smart,索引用 ik_max_word
  • Mapping:能用 keyword 不用 text(聚合、排序、过滤)
  • 查询:must + filter 分离,filter 走缓存
  • 集群:Master 和数据节点分离,监控分片分布

继续阅读

探索更多技术文章

浏览归档,发现更多关于系统设计、工具链和工程实践的内容。

全部文章 返回首页

「distributed-systems」更多文章

  1. 分布式高可用架构模式:多活、容灾、降级与 K8s 编排高可用
  2. 分布式链路追踪实战:OpenTelemetry、Jaeger 与 W3C Trace Context
  3. 分布式缓存深度策略:Redis Cluster、一致性哈希与多级缓存架构