-
全文搜索属于最常见的需求,开源的 Elasticsearch是目前全文搜索引擎的首选。它可以快速地储存、搜索和分析海量数据。维基百科、Stack Overflow、Github 都采用它。
-
Elasticsearch 的底层是开源库 Lucene。但是,你没法直接用 Lucene,必须自己写代码去调用它的接口。Elasticsearch 是 Lucene 的封装,提供了 REST API 的操作接口,开箱即用。
1 安装
- 以v7.9.1版本为例,目前最新版本是v7.15.1
1.1 手动安装
- 文档:https://www.elastic.co/guide/en/elasticsearch/reference/current/targz.html
# 以Linux系统为例
# 下载
$ wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-7.9.1-linux-x86_64.tar.gz
# 完整性校验
$ wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-7.9.1-linux-x86_64.tar.gz.sha512
$ shasum -a 512 -c elasticsearch-7.9.1-linux-x86_64.tar.gz.sha512
# 解压
$ tar -xzf elasticsearch-7.9.1-linux-x86_64.tar.gz
# 进入解压后的目录
$ cd elasticsearch-7.9.1
# 启动
$ ./bin/elasticsearch
1.2 k8s部署
- 文档:https://www.elastic.co/guide/en/elasticsearch/reference/7.15/docker.html
# deployment.yaml
apiVersion: apps/v1beta1
kind: Deployment
metadata:
name: &PROJECT_NAME-elasticsearch
namespace: default
spec:
selector:
matchLabels:
name: &PROJECT_NAME-elasticsearch
replicas: 1
strategy:
type: RollingUpdate
template:
metadata:
labels:
author: yunfu
name: &PROJECT_NAME-elasticsearch
spec:
containers:
- image: elasticsearch:7.9.1
imagePullPolicy: IfNotPresent
securityContext:
privileged: true
name: &PROJECT_NAME-elasticsearch
volumeMounts:
- mountPath: /usr/share/elasticsearch/data
name: data
- mountPath: /usr/share/elasticsearch/plugins
name: plugins
- mountPath: /usr/share/elasticsearch/config/analysis
name: analysis
env:
- name: PROJECT_NAME
value: &PROJECT_NAME
- name: discovery.type
value: single-node
- name: indices.query.bool.max_clause_count
value: '40960'
ports:
- containerPort: 9200
nodeName: s03
volumes:
- name: data
hostPath:
path: &MOUNT_PATH/elasticsearch/data
- name: plugins
hostPath:
path: &MOUNT_PATH/elasticsearch/plugins
- name: analysis
hostPath:
path: &MOUNT_PATH/elasticsearch/analysis
---
apiVersion: v1
kind: Service
metadata:
name: &PROJECT_NAME-elasticsearch
namespace: default
spec:
type: NodePort
selector:
name: &PROJECT_NAME-elasticsearch
ports:
- port: 9200
targetPort: 9200
nodePort: 9200
1.3 验证
如果一切正常,Elasticsearch 就会在默认的9200端口运行。这时,打开另一个命令行窗口,请求该端口,会得到说明信息。
GET http://192.168.2.251:9200
# 返回一个 JSON 对象,包含当前节点、集群、版本等信息
{
"name" : "yftool-db-elasticsearch-78f7896866-6qmsn",
"cluster_name" : "docker-cluster",
"cluster_uuid" : "mb34onKKSr2InWHVNo1aAg",
"version" : {
"number" : "7.9.1",
"build_flavor" : "default",
"build_type" : "docker",
"build_hash" : "083627f112ba94dffc1232e8b42b73492789ef91",
"build_date" : "2020-09-01T21:22:21.964974Z",
"build_snapshot" : false,
"lucene_version" : "8.6.2",
"minimum_wire_compatibility_version" : "6.8.0",
"minimum_index_compatibility_version" : "6.0.0-beta1"
},
"tagline" : "You Know, for Search"
}
2 基本概念
2.1 Node 与 Cluster
-
Elasticsearch 本质上是一个分布式数据库,允许多台服务器协同工作,每台服务器可以运行多个 Elasticsearch 实例。
-
单个 Elasticsearch 实例称为一个节点(node)。
-
一组节点构成一个集群(cluster)。
2.2 Index
-
Elasticsearch 会索引所有字段,经过处理后写入一个反向索引(Inverted Index)。查找数据的时候,直接查找该索引。
-
所以,Elasticsearch 数据管理的顶层单位就叫做 Index(索引)。它是单个数据库的同义词。
-
每个 Index (即数据库)的名字必须是小写。
# 查看当前节点的所有 Index
GET 'http://192.168.2.251:9200/_cat/indices?v'
health status index uuid pri rep docs.count docs.deleted store.size pri.store.size
yellow open news Du-H_btHQ6e3t3MxJEaAWg 1 1 78565 0 262.8mb 262.8mb
yellow open nginx wFbtCIBwRaGEM7TsfBnPdA 1 1 335843 0 10.2mb 10.2mb
yellow open due_search_news yXeJv7e8T6iyTKSho1Y_8w 1 1 1696 0 374.9kb 374.9kb
yellow open nginx2 yux1FaBcRCSDpcuGyWGw2Q 1 1 64435 0 2.1mb 2.1mb
2.3 Document
-
Index 里面单条的记录称为 Document(文档)。许多条 Document 构成了一个 Index。
-
Document 使用 JSON 格式表示,下面是一个例子。
{ "user": "张三", "title": "工程师", "desc": "数据库管理" }
-
同一个 Index 里面的 Document,不要求有相同的结构(scheme),但是最好保持相同,这样有利于提高搜索效率。
2.4 Type
-
Document 可以分组,比如
weather
这个 Index 里面,可以按城市分组(北京和上海),也可以按气候分组(晴天和雨天)。这种分组就叫做 Type,它是虚拟的逻辑分组,用来过滤 Document。 -
不同的 Type 应该有相似的结构(schema),举例来说,
id
字段不能在这个组是字符串,在另一个组是数值。这是与关系型数据库的表的一个区别。 -
性质完全不同的数据(比如
products
和logs
)应该存成两个 Index,而不是一个 Index 里面的两个 Type(虽然可以做到)。 -
Elasticsearch 6.x 版只允许每个 Index 包含一个 Type,7.x 版已经彻底移除 Type。(默认为:_doc)
3 新建和删除 Index
-
新建 Index,可以直接向 Elasticsearch 服务器发出 PUT 请求。下面的例子是新建一个名叫
weather
的 Index。PUT http://192.168.2.251:9200/weather
-
服务器返回一个 JSON 对象,里面的
acknowledged
字段表示操作成功。{ "acknowledged": true, "shards_acknowledged": true, "index": "weather" }
-
然后,我们发出 DELETE 请求,删除这个 Index。
DELETE http://192.168.2.251:9200/weather { "acknowledged": true }
4 中文分词设置
-
首先,安装中文分词插件。这里使用的是 ik,也可以考虑其他插件(比如 smartcn)。
$ ./bin/elasticsearch-plugin install https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v7.9.1/elasticsearch-analysis-ik-7.9.1.zip
-
上面代码安装的是7.9.1版的插件,与 Elasticsearch 7.9.1 配合使用。
-
接着,重新启动 Elastic,就会自动加载这个新安装的插件。
-
然后,新建一个 Index,指定需要分词的字段。这一步根据数据结构而异,下面的命令只针对本文。基本上,凡是需要搜索的中文字段,都要单独设置一下。
PUT http://192.168.2.251:9200/accounts { "mappings":{ "properties":{ "user":{ "type":"text", "analyzer":"ik_max_word", "search_analyzer":"ik_max_word" }, "title":{ "type":"text", "analyzer":"ik_max_word", "search_analyzer":"ik_max_word" }, "desc":{ "type":"text", "analyzer":"ik_max_word", "search_analyzer":"ik_max_word" } } } }
-
上面代码中,首先新建一个名称为
accounts
的 Index,有三个字段:user
、title
、desc
-
这三个字段都是中文,而且类型都是文本(text),所以需要指定中文分词器,不能使用默认的英文分词器。
-
Elasticsearch 的分词器称为 analyzer。我们对每个字段指定分词器。
"user": {
"type": "text",
"analyzer": "ik_max_word",
"search_analyzer": "ik_max_word"
}
- 上面代码中,
analyzer
是字段文本的分词器,search_analyzer
是搜索词的分词器。ik_max_word
分词器是插件ik
提供的,可以对文本进行最大数量的分词。
5 数据操作
5.1 新增记录
-
向指定的 Index发送 PUT 请求,就可以在 Index 里面新增一条记录。比如,向
/accounts/person
发送请求,就可以新增一条人员记录。PUT http://192.168.2.251:9200/accounts/_doc/1 { "user": "张三", "title": "工程师", "desc": "数据库管理" }
-
服务器返回的 JSON 对象,会给出 Index、Type、Id、Version 等信息。
{ "_index": "accounts", "_type": "_doc", "_id": "1", "_version": 1, "result": "created", "_shards": { "total": 2, "successful": 1, "failed": 0 }, "_seq_no": 0, "_primary_term": 1 }
-
如果你仔细看,会发现请求路径是
/accounts/_doc/1
,最后的1
是该条记录的 Id。它不一定是数字,任意字符串(比如abc
)都可以。 -
新增记录的时候,也可以不指定 Id,这时要改成 POST 请求。
POST http://192.168.2.251:9200/accounts/_doc { "user": "李四", "title": "工程师", "desc": "系统管理" }
-
上面代码中,向
/accounts/_doc
发出一个 POST 请求,添加一个记录。这时,服务器返回的 JSON 对象里面,_id
字段就是一个随机字符串。{ "_index": "accounts", "_type": "_doc", "_id": "Ds25knwBPdZtIfHNf2y9", "_version": 1, "result": "created", "_shards": { "total": 2, "successful": 1, "failed": 0 }, "_seq_no": 1, "_primary_term": 1 }
5.2 查看记录
-
向
/Index/_doc/Id
发出 GET 请求,就可以查看这条记录。GET http://192.168.2.251:9200/accounts/_doc/1?pretty=true
-
上面代码请求查看
/accounts/_doc/1
这条记录,URL 的参数pretty=true
表示以易读的格式返回。 -
返回的数据中,
found
字段表示查询成功,_source
字段返回原始记录。{ "_index": "accounts", "_type": "_doc", "_id": "1", "_version": 1, "_seq_no": 0, "_primary_term": 1, "found": true, "_source": { "user": "张三", "title": "工程师", "desc": "数据库管理" } }
-
如果 Id 不正确,就查不到数据,
found
字段就是false
。GET http://192.168.2.251:9200/accounts/_doc/-1?pretty=true # response { "_index": "accounts", "_type": "_doc", "_id": "-1", "found": false }
5.3 删除记录
-
删除记录就是发出 DELETE 请求。
DELETE http://192.168.2.251:9200/accounts/_doc/1
5.4 更新记录
-
更新记录就是使用 PUT 请求,重新发送一次数据。
PUT http://192.168.2.251:9200/accounts/_doc/1 { "user" : "张三", "title" : "工程师", "desc" : "数据库管理,软件开发" }
{ "_index": "accounts", "_type": "_doc", "_id": "1", "_version": 2, "result": "updated", "_shards": { "total": 2, "successful": 1, "failed": 0 }, "_seq_no": 2, "_primary_term": 1 }
-
上面代码中,我们将原始数据从"数据库管理"改成"数据库管理,软件开发"。 返回结果里面,有几个字段发生了变化。
"_version" : 2, "result" : "updated"
-
可以看到,记录的 Id 没变,但是版本(version)从
1
变成2
,操作类型(result)从created
变成updated
,这次不是新建记录。
6 数据查询
6.1 返回所有记录
-
使用 GET 方法,直接请求
/Index/_doc/_search
,就会返回所有记录。GET http://192.168.2.251:9200/accounts/_doc/_search # response { "took": 1, "timed_out": false, "_shards": { "total": 1, "successful": 1, "skipped": 0, "failed": 0 }, "hits": { "total": { "value": 2, "relation": "eq" }, "max_score": 1.0, "hits": [ { "_index": "accounts", "_type": "_doc", "_id": "Ds25knwBPdZtIfHNf2y9", "_score": 1.0, "_source": { "user": "李四", "title": "工程师", "desc": "系统管理" } }, { "_index": "accounts", "_type": "_doc", "_id": "1", "_score": 1.0, "_source": { "user": "张三", "title": "工程师", "desc": "数据库管理,软件开发" } } ] } }
-
上面代码中,返回结果的
took
字段表示该操作的耗时(单位为毫秒),timed_out
字段表示是否超时,hits
字段表示命中的记录,里面子字段的含义如下:total
:返回记录数,本例是2条。max_score
:最高的匹配程度,本例是1.0
。hits
:返回的记录组成的数组。
-
返回的记录中,每条记录都有一个
_score
字段,表示匹配的程序,默认是按照这个字段降序排列。
6.2 全文搜索
-
Elasticsearch 的查询非常特别,使用自己的查询语法,要求GET请求带有数据体。
GET http://192.168.2.251:9200/accounts/_doc/_search { "query":{ "match":{ "desc":"软件" } } }
-
上面代码使用 Match 查询,指定的匹配条件是
desc
字段里面包含"软件"这个词。返回结果如下:{ "took": 70, "timed_out": false, "_shards": { "total": 1, "successful": 1, "skipped": 0, "failed": 0 }, "hits": { "total": { "value": 1, "relation": "eq" }, "max_score": 0.6235748, "hits": [ { "_index": "accounts", "_type": "_doc", "_id": "1", "_score": 0.6235748, "_source": { "user": "张三", "title": "工程师", "desc": "数据库管理,软件开发" } } ] } }
-
Elastic 默认一次返回10条结果,可以通过
size
字段改变这个设置。GET http://192.168.2.251:9200/accounts/_doc/_search { "query":{ "match":{ "desc":"软件" } } "size": 1 }
-
上面代码指定,每次只返回一条结果。
-
还可以通过
from
字段,指定位移。GET http://192.168.2.251:9200/accounts/_doc/_search { "query":{ "match":{ "desc":"软件" } } "from": 1, "size": 1 }
-
上面代码指定,从位置1开始(默认是从位置0开始),只返回一条结果。
6.3 逻辑运算
-
如果有多个搜索关键字, Elastic 认为它们是
or
关系。GET http://192.168.2.251:9200/accounts/_doc/_search { "query":{ "match":{ "desc":"软件 系统" } } }
-
上面代码搜索的是
软件 or 系统
。 -
如果要执行多个关键词的
and
搜索,必须使用布尔查询。GET http://192.168.2.251:9200/accounts/_doc/_search { "query": { "bool": { "must": [ { "match": { "desc": "软件" } }, { "match": { "desc": "系统" } } ] } } }