Skip to content

小项目实战

本节用两个小需求串联前面学过的内容:博客/商品搜索日志检索,并在最后简述与程序集成的方式。


需求一:简单博客/商品搜索

目标:支持关键词搜索 + 分类筛选 + 分页

1. 设计索引与 Mapping

http
PUT /blog
{
  "settings": { "number_of_shards": 1, "number_of_replicas": 0 },
  "mappings": {
    "properties": {
      "title": {
        "type": "text",
        "analyzer": "ik_max_word",
        "fields": { "keyword": { "type": "keyword" } }
      },
      "content": { "type": "text", "analyzer": "ik_max_word" },
      "category": { "type": "keyword" },
      "author": { "type": "keyword" },
      "created_at": { "type": "date" }
    }
  }
}
  • 若未装 IK,可把 analyzer 改为 standard 或删掉使用默认。
  • categoryauthor 用 keyword,便于 term 筛选和聚合。

2. 写入示例数据

http
POST _bulk
{"index":{"_index":"blog","_id":"1"}}
{"title":"Elasticsearch 入门","content":"介绍 ES 基本概念","category":"技术","author":"张三","created_at":"2024-01-01"}
{"index":{"_index":"blog","_id":"2"}}
{"title":"Kibana 使用技巧","content":"Dev Tools 与可视化","category":"技术","author":"李四","created_at":"2024-01-02"}
{"index":{"_index":"blog","_id":"3"}}
{"title":"日志分析实战","content":"用 ES 做日志检索","category":"运维","author":"王五","created_at":"2024-01-03"}

3. 实现:关键词 + 分类 + 分页

http
GET /blog/_search
{
  "from": 0,
  "size": 10,
  "query": {
    "bool": {
      "must": [
        { "match": { "title": "Elasticsearch 入门" } }
      ],
      "filter": [
        { "term": { "category": "技术" } }
      ]
    }
  },
  "sort": [ { "created_at": "desc" } ],
  "_source": ["title", "category", "author", "created_at"]
}

按需把 match 的查询词改为变量,category 改为前端传入的分类,from/size 改为分页参数即可。


需求二:日志检索

目标:按时间范围级别关键词查询,并做简单聚合(如按级别统计、按小时统计)。

1. 索引与数据

使用 索引模板 或直接创建索引,例如:

http
PUT /logs-2024-01
{
  "mappings": {
    "properties": {
      "message": { "type": "text", "analyzer": "standard" },
      "level": { "type": "keyword" },
      "@timestamp": { "type": "date" }
    }
  }
}

写入几条示例日志后,做组合查询:

2. 查询:时间 + 级别 + 关键词

http
GET /logs-2024-01/_search
{
  "size": 20,
  "query": {
    "bool": {
      "filter": [
        { "range": { "@timestamp": { "gte": "2024-01-01", "lte": "2024-01-31" } } },
        { "term": { "level": "ERROR" } }
      ],
      "must": [
        { "match": { "message": "timeout" } }
      ]
    }
  },
  "sort": [ { "@timestamp": "desc" } ]
}

3. 简单聚合:按级别统计、按小时统计

http
GET /logs-2024-01/_search
{
  "size": 0,
  "query": {
    "range": { "@timestamp": { "gte": "2024-01-01", "lte": "2024-01-31" } }
  },
  "aggs": {
    "by_level": {
      "terms": { "field": "level" }
    },
    "by_hour": {
      "date_histogram": {
        "field": "@timestamp",
        "calendar_interval": "hour"
      }
    }
  }
}

与程序集成

  • REST API:任何语言都可发 HTTP 请求(如 curl、axios、fetch)。Kibana Dev Tools 里的请求可等价改成你所用语言的 HTTP 调用。
  • 官方/社区客户端
    • Java:High Level REST Client 或 Elasticsearch Java API Client。
    • Pythonelasticsearch 库。
    • Node.js@elastic/elasticsearch

在代码中构造与上面示例等价的 JSON body,发到对应 _search_bulk 等端点即可。建议先在本教程中用 Dev Tools 把 query、aggs 调通,再在程序中复用相同 DSL。