引言

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
# 使用IK分词器
POST /_analyze
{
"analyzer": "ik_max_word",
"text": "我是中国人"
}

# 结果:我 是 中国 中国人 人

总结

Elasticsearch核心:

  1. 倒排索引:快速全文搜索
  2. 分布式:水平扩展
  3. REST API:简单易用
  4. 实时搜索:近实时查询

参考资料