Elasticsearch基础语法 #

一、REST API概述 #

1.1 API特点 #

Elasticsearch提供了完整的RESTful API:

text
API特点
├── RESTful风格
│   ├── 使用HTTP方法表示操作
│   └── URL表示资源
├── JSON格式
│   ├── 请求体使用JSON
│   └── 响应体使用JSON
└── 统一端点
    └── 默认端口9200

1.2 HTTP方法对应操作 #

HTTP方法 操作 示例
GET 查询 获取文档、搜索
POST 创建/更新 索引文档、执行搜索
PUT 创建/替换 创建索引、更新文档
DELETE 删除 删除文档、索引
HEAD 存在检查 检查文档是否存在

二、URL约定 #

2.1 基本格式 #

text
http://host:port/<index>/<type>/<id>

简化格式(推荐)
http://host:port/<index>/_doc/<id>

2.2 常用端点 #

端点 说明
/_cluster/health 集群健康状态
/_cat/indices 索引列表
/_cat/nodes 节点列表
/<index> 索引操作
/<index>/_doc 文档操作
/<index>/_search 搜索操作
/<index>/_bulk 批量操作

2.3 URL参数 #

text
常用参数
├── pretty
│   └── 格式化JSON输出
├── format
│   └── 指定输出格式(json/yaml/smile/cbor)
├── filter_path
│   └── 过滤响应字段
├── human
│   └── 人类可读格式
└── refresh
    └── 立即刷新索引

示例:

bash
GET /products/_search?pretty
GET /products/_search?filter_path=hits.hits._source
GET /products/_search?human=true

三、请求格式 #

3.1 基本请求结构 #

bash
curl -X <METHOD> "http://localhost:9200/<endpoint>" \
  -H "Content-Type: application/json" \
  -d '{
    <request_body>
  }'

3.2 索引操作请求 #

创建索引

bash
PUT /products
{
  "settings": {
    "number_of_shards": 3,
    "number_of_replicas": 1
  },
  "mappings": {
    "properties": {
      "name": { "type": "text" },
      "price": { "type": "float" }
    }
  }
}

删除索引

bash
DELETE /products

3.3 文档操作请求 #

索引文档(创建/替换)

bash
PUT /products/_doc/1
{
  "name": "iPhone 15",
  "price": 999,
  "brand": "Apple"
}

自动生成ID

bash
POST /products/_doc
{
  "name": "iPhone 15",
  "price": 999
}

更新文档

bash
POST /products/_update/1
{
  "doc": {
    "price": 899
  }
}

删除文档

bash
DELETE /products/_doc/1

3.4 搜索请求 #

bash
GET /products/_search
{
  "query": {
    "match": {
      "name": "iPhone"
    }
  },
  "size": 10,
  "from": 0,
  "_source": ["name", "price"]
}

四、响应结构 #

4.1 文档响应 #

json
{
  "_index": "products",
  "_id": "1",
  "_version": 1,
  "_seq_no": 0,
  "_primary_term": 1,
  "found": true,
  "_source": {
    "name": "iPhone 15",
    "price": 999
  }
}

4.2 搜索响应 #

json
{
  "took": 5,
  "timed_out": false,
  "_shards": {
    "total": 3,
    "successful": 3,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": {
      "value": 100,
      "relation": "eq"
    },
    "max_score": 1.0,
    "hits": [
      {
        "_index": "products",
        "_id": "1",
        "_score": 1.0,
        "_source": {
          "name": "iPhone 15",
          "price": 999
        }
      }
    ]
  }
}

4.3 响应字段说明 #

字段 说明
took 查询耗时(毫秒)
timed_out 是否超时
_shards 分片执行情况
hits.total 匹配文档总数
hits.max_score 最高相关性得分
hits.hits 文档结果数组
_score 文档相关性得分
_source 原始文档内容

4.4 错误响应 #

json
{
  "error": {
    "root_cause": [
      {
        "type": "index_not_found_exception",
        "reason": "no such index [products]",
        "index": "products"
      }
    ],
    "type": "index_not_found_exception",
    "reason": "no such index [products]",
    "index": "products"
  },
  "status": 404
}

五、查询DSL #

5.1 查询语法结构 #

json
GET /products/_search
{
  "query": {
    <query_type>: {
      <field>: <value>
    }
  }
}

5.2 基本查询类型 #

全文搜索

json
{
  "query": {
    "match": {
      "name": "iPhone"
    }
  }
}

精确匹配

json
{
  "query": {
    "term": {
      "brand": "Apple"
    }
  }
}

范围查询

json
{
  "query": {
    "range": {
      "price": {
        "gte": 500,
        "lte": 1000
      }
    }
  }
}

5.3 复合查询 #

json
{
  "query": {
    "bool": {
      "must": [
        { "match": { "name": "iPhone" } }
      ],
      "filter": [
        { "range": { "price": { "lte": 1000 } } }
      ],
      "must_not": [
        { "term": { "status": "deleted" } }
      ],
      "should": [
        { "term": { "brand": "Apple" } }
      ]
    }
  }
}

六、批量操作 #

6.1 Bulk API格式 #

text
action_and_meta_data\n
optional_source\n
action_and_meta_data\n
optional_source\n

6.2 批量示例 #

bash
POST /_bulk
{"index": {"_index": "products", "_id": "1"}}
{"name": "iPhone 15", "price": 999}
{"index": {"_index": "products", "_id": "2"}}
{"name": "MacBook Pro", "price": 1999}
{"update": {"_index": "products", "_id": "1"}}
{"doc": {"price": 899}}
{"delete": {"_index": "products", "_id": "2"}}

6.3 批量响应 #

json
{
  "took": 30,
  "errors": false,
  "items": [
    {
      "index": {
        "_index": "products",
        "_id": "1",
        "status": 201
      }
    },
    {
      "index": {
        "_index": "products",
        "_id": "2",
        "status": 201
      }
    }
  ]
}

七、多文档操作 #

7.1 多获取(mget) #

bash
GET /_mget
{
  "docs": [
    { "_index": "products", "_id": "1" },
    { "_index": "products", "_id": "2" }
  ]
}

简化写法:

bash
GET /products/_mget
{
  "ids": ["1", "2", "3"]
}

7.2 批量查询(msearch) #

bash
GET /_msearch
{}
{"query": {"match_all": {}}}
{"index": "products"}
{"query": {"match": {"name": "iPhone"}}}

八、索引模板 #

8.1 创建模板 #

bash
PUT /_index_template/logs_template
{
  "index_patterns": ["logs-*"],
  "template": {
    "settings": {
      "number_of_shards": 3,
      "number_of_replicas": 1
    },
    "mappings": {
      "properties": {
        "@timestamp": { "type": "date" },
        "message": { "type": "text" },
        "level": { "type": "keyword" }
      }
    }
  }
}

8.2 查看模板 #

bash
GET /_index_template/logs_template

九、别名操作 #

9.1 创建别名 #

bash
POST /_aliases
{
  "actions": [
    {
      "add": {
        "index": "products_v1",
        "alias": "products"
      }
    }
  ]
}

9.2 切换别名 #

bash
POST /_aliases
{
  "actions": [
    {
      "remove": {
        "index": "products_v1",
        "alias": "products"
      }
    },
    {
      "add": {
        "index": "products_v2",
        "alias": "products"
      }
    }
  ]
}

十、常用API速查 #

10.1 集群相关 #

bash
GET /_cluster/health
GET /_cluster/state
GET /_cluster/stats
GET /_cluster/pending_tasks

10.2 节点相关 #

bash
GET /_nodes
GET /_nodes/stats
GET /_nodes/hot_threads
GET /_cat/nodes?v

10.3 索引相关 #

bash
GET /_cat/indices?v
GET /products/_settings
GET /products/_mapping
GET /products/_stats
POST /products/_close
POST /products/_open

10.4 文档相关 #

bash
GET /products/_doc/1
HEAD /products/_doc/1
GET /products/_source/1
GET /products/_count

10.5 搜索相关 #

bash
GET /products/_search
GET /products/_validate/query
GET /products/_explain/1

十一、总结 #

本章介绍了Elasticsearch的基础语法:

  1. RESTful API使用HTTP方法表示操作
  2. URL约定定义了资源路径
  3. JSON格式的请求和响应
  4. 查询DSL提供灵活的查询语法
  5. Bulk API支持高效的批量操作
  6. 别名和模板简化索引管理

下一步,我们将学习Elasticsearch的数据类型。

最后更新:2026-03-27