引言
Elasticsearch是流行的分布式搜索引擎。本文讲解ES的核心概念和基本操作。
一、核心概念
1.1 基本术语
1 2 3 4 5
| Index(索引) → Database(数据库) Type(类型) → Table(表,7.x后废弃) Document(文档) → Row(行) Field(字段) → Column(列) Mapping(映射) → Schema(模式)
|
1.2 倒排索引
1 2 3 4 5
| Term | Doc IDs --------|---------- hello | 1, 3, 5 world | 1, 2 search | 2, 5
|
二、基本操作
2.1 索引操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| PUT /products { "settings": { "number_of_shards": 3, "number_of_replicas": 2 } }
DELETE /products
GET /_cat/indices?v
|
2.2 文档操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| POST /products/_doc { "name": "iPhone 14", "price": 5999, "category": "手机" }
GET /products/_doc/1
POST /products/_update/1 { "doc": { "price": 5799 } }
DELETE /products/_doc/1
|
2.3 搜索操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| GET /products/_search { "query": { "match": { "name": "iPhone" } } }
GET /products/_search { "query": { "bool": { "must": [ { "match": { "name": "iPhone" } } ], "filter": [ { "range": { "price": { "gte": 5000 } } } ] } } }
GET /products/_search { "aggs": { "avg_price": { "avg": { "field": "price" } } } }
|
三、映射定义
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| PUT /products { "mappings": { "properties": { "name": { "type": "text", "analyzer": "ik_max_word" }, "price": { "type": "double" }, "created_at": { "type": "date" } } } }
|
四、分词器
1 2 3 4 5 6 7 8
| POST /_analyze { "analyzer": "ik_max_word", "text": "我是中国人" }
|
总结
Elasticsearch核心:
- 倒排索引:快速全文搜索
- 分布式:水平扩展
- REST API:简单易用
- 实时搜索:近实时查询
参考资料