目录

Elasticsearch全文搜索实战

Elasticsearch 是最强大的分布式搜索引擎,本文带你从零掌握全文搜索的核心技能。

基本概念

概念 类比数据库 说明
Index Database 索引(数据库)
Type Table 类型(已废弃)
Document Row 文档(行)
Field Column 字段(列)
Shard Partition 分片

索引与映射

json
// 创建索引并定义映射
PUT /articles
{
  "mappings": {
    "properties": {
      "title": {
        "type": "text",
        "analyzer": "ik_max_word",
        "search_analyzer": "ik_smart"
      },
      "content": {
        "type": "text",
        "analyzer": "ik_max_word"
      },
      "tags": {
        "type": "keyword"
      },
      "views": {
        "type": "integer"
      },
      "published_at": {
        "type": "date",
        "format": "yyyy-MM-dd HH:mm:ss"
      }
    }
  }
}

文档操作

json
// 新增文档
POST /articles/_doc/1
{
  "title": "Docker容器化部署指南",
  "content": "本文介绍Docker的核心概念和实战部署...",
  "tags": ["Docker", "DevOps"],
  "views": 3456,
  "published_at": "2024-01-15 09:30:00"
}

// 获取文档
GET /articles/_doc/1

// 更新文档
POST /articles/_update/1
{
  "doc": { "views": 3500 }
}

// 删除文档
DELETE /articles/_doc/1

搜索查询

基础查询

json
// 全文搜索
GET /articles/_search
{
  "query": {
    "match": {
      "title": "Docker部署"
    }
  }
}

// 多字段搜索
GET /articles/_search
{
  "query": {
    "multi_match": {
      "query": "容器化",
      "fields": ["title^3", "content"]
    }
  }
}

// 精确匹配
GET /articles/_search
{
  "query": {
    "term": {
      "tags": "DevOps"
    }
  }
}

布尔查询

json
GET /articles/_search
{
  "query": {
    "bool": {
      "must": [
        { "match": { "content": "Docker" } }
      ],
      "filter": [
        { "range": { "views": { "gte": 1000 } } },
        { "term": { "tags": "DevOps" } }
      ],
      "must_not": [
        { "match": { "content": "已废弃" } }
      ],
      "should": [
        { "match": { "title": "实战" } }
      ]
    }
  }
}

高亮显示

json
GET /articles/_search
{
  "query": {
    "match": { "content": "Docker" }
  },
  "highlight": {
    "fields": {
      "content": {
        "pre_tags": ["<em>"],
        "post_tags": ["</em>"],
        "fragment_size": 150
      }
    }
  }
}

聚合分析

json
GET /articles/_search
{
  "size": 0,
  "aggs": {
    "tags_count": {
      "terms": {
        "field": "tags",
        "size": 10
      }
    },
    "avg_views": {
      "avg": { "field": "views" }
    },
    "views_by_month": {
      "date_histogram": {
        "field": "published_at",
        "calendar_interval": "month"
      }
    }
  }
}

中文分词

json
// 安装 IK 分词器
// bin/elasticsearch-plugin install https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v8.x/elasticsearch-analysis-ik-8.x.zip

// 测试分词
GET /_analyze
{
  "analyzer": "ik_max_word",
  "text": "Docker容器化部署实战指南"
}

// 结果:Docker / 容器 / 容器化 / 部署 / 实战 / 指南

总结

Elasticsearch 全文搜索的核心在于:合理的映射定义、选择合适的分词器(中文用 IK)、灵活使用 bool 查询组合条件、用 highlight 高亮关键词、用聚合做数据分析。对于海量数据,合理的分片和副本配置也至关重要。