是什么?
elasticsearch是一个分布式搜索引擎,由Java开发,具体的描述可以自行百度
与关系型数据库比较
Elasticsearch | 关系型数据库Mysql |
---|---|
索引(index) | 数据库(databases) |
类型(type) | 表(table) |
文档(document) | 行(row) |
下载安装
下载ElasticSearch 5.6.8版本
https://www.elastic.co/downloads/past-releases/elasticsearch-5-6-8
下载后解压到你设置的一个文件夹(这里切记不要把es解压到带空格的和有中文的路径!!在后面学习ik分词器的时候就踩雷了)。
解压后进入到elasticsearch所在目录的bin目录下
直接输入以下命令即可启动。
elasticsearch
端口
elasicsearch有两个端口号:
9200作为Http协议,主要用于外部通讯
9300作为Tcp协议,jar之间就是通过tcp协议通讯
ES集群之间是通过9300进行通讯
打开浏览器,访问http://127.0.0.1:9200/ 看到以下内容即启动成功
使用Postman调用RestAPI
- 1、新建索引 【PUT】
例如我们要创建一个叫esindex的索引
*http://127.0.0.1:9200/esindex/*
- 2、新建文档 【POST】
新增了一个test的类型
*http://127.0.0.1:9200/esindex/test*
//body数据
{
"who":"baba",
"say":"i am your father"
}
提交后会看到下面的返回信息
{
"_index": "esindex",
"_type": "test",
"_id": "AW872UJhcvSY4X3GkB6z",
"_version": 1,
"result": "created",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
},
"created": true
}
这里我们关注下:
字段 | 意义 |
---|---|
_id | 自动生成的 |
_version | 第一个版本 |
created | 表明是新增的 |
- 3、查询所有文档 【GET】
- http://127.0.0.1:9200/esindex/test/_search
{
"took": 348,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 1,
"max_score": 1.0,
"hits": [
{
"_index": "esindex",
"_type": "test",
"_id": "AW872UJhcvSY4X3GkB6z",
"_score": 1.0,
"_source": {
"who": "baba",
"say": "i am your father"
}
}
]
}
}
- 4、根据id查询 【GET】
http://127.0.0.1:9200/esindex/test/刚才生成的id
可以看到自动生成的id有点太难记了,我们可以生成自定义的id
首先我们调用生成文档的接口 【POST】
http://127.0.0.1:9200/esindex/test/1
注意后面加上id号,这时,如果不存在这个id,es就会新增一个文档。
如果存在这个id,则更新文档。
可以看到我们新增了一条id为1的文档,created=true
body数据:
{
"who":"弟弟",
"say":"臭弟弟"
}
{
"_index": "esindex",
"_type": "test",
"_id": "1",
"_version": 1,
"result": "created",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
},
"created": true
}
这时再调用http://127.0.0.1:9200/esindex/test/1就可以获取刚刚的文档了
- 5、条件查询 【POST】
http://127.0.0.1:9200/esindex/test/_search?q=who:baba
如图,查到了who中包含baba的文档。
注意!!!
es的条件查询并不是说相等的查询,而是根据分词去查询的,比如这里的条件who:baba并不是说只有who等于baba的文档才符合条件,而是who包含baba的文档都满足条件。
为了验证这个,我们新建一个文档
这里跟我们第一次建立的文档的say都有father这个词,下面我们来条件查询一下
http://127.0.0.1:9200/esindex/test/_search?q=say:father
如图,查询到了两条数据。
- 6、模糊查询 【GET】
我们查询包含字母o的文档
http://127.0.0.1:9200/esindex/test/_search?q=say:*o*
同样可以找到这两条文档
- 7、根据id删除文档 【DELETE】
- http://127.0.0.1:9200/esindex/test/1
至此,elasticsearch增删改查完成