前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【从入门到精通,教你如何安装ElasticSearch】Linux版本

【从入门到精通,教你如何安装ElasticSearch】Linux版本

作者头像
趣学程序-shaofeer
发布2023-09-09 08:46:26
3260
发布2023-09-09 08:46:26
举报
文章被收录于专栏:upuptop的专栏upuptop的专栏

ElasticSearch

1.elasticsearch 概述

Elasticsearch 是一个分布式、高扩展、高实时的搜索与数据分析引擎。它能很方便的使大量数据具有搜索、分析和探索的能力。它提供可扩展的搜索,具有接近实时的搜索。ES本身扩展性很好,可以扩展到上百台服务器。ES也使用Java开发并使用Lucene作为核心来实现所有索引和搜索的功能,但是它的目的是通过简单的RESTful API来隐藏Lucene的复杂性,从而让全文检索变得简单。

据国际权威的数据库产品评测机构DB Engines的统计,在2016年1月,ElasticSearch已经超过Solr等,成为排名第一的搜索引擎类应用!

谁在使用ES:

  • 维基百科,类似百度百科,全文检索,高亮,搜索推荐。
  • Stack Overflow,国外程序异常论坛。
  • GitHub。
  • 电商网站,检索商品。
  • 国内:站内搜索(电商,招聘,门户),IT系统搜索,数据分析。

2.elasticsearch环境

2.1.安装elasticsearch

Linux普通安装

下载地址:https://www.elastic.co/cn/downloads/elasticsearch

  1. # jdk1.8最低要求!elasticsearch支持客户端,界面工具!
  2. # Java开发,elasticsearch的版本和我们之后对应的Java的核心包!版本对应!JDK环境正常
  3. # 1、下载elasticsearch-7.8.0-linux-x86_64.tar.gz,然后解压到指定文件,就可以使用了!
  4. # 2、熟悉elasticsearch目录
  5. - bin # 启动文件
  6. - config # 配置文件
  7. log4j2 # 日志配置文件
  8. jvm.options # JVM相关配置 如过内存小 修改一下JVM的配置
  9. elasticsearch.yml # ElasticSearch配置文件 默认9200端口
  10. - lib # 相关jar
  11. - modules # 功能模块
  12. - plugins # 插件
  13. - logs # 日志
  14. # 3、启动elasticsearch之前的准备工作
  15. # 由于elasticsearch-7.X不能以Root启动elasticsearch,所以需要创建用户
  16. adduser Tangs # 添加用户
  17. passwd Tangs # 设置密码
  18. chown -R Tangs /opt/elasticsearch/elasticsearch-7.8.0/ # Root个用户权限!
  19. # 4、以新的用户到bin目录启动elasticsearch脚本
  20. [Tangs@Ringo bin]$ ./elasticsearch
  21. # 5、测试连接
  22. [root@Ringo elasticsearch-7.8.0]# curl localhost:9200
  23. {
  24. "name" : "Ringo",
  25. "cluster_name" : "elasticsearch",
  26. "cluster_uuid" : "IS5Y80WYRJOj4AHmIQ32Fw",
  27. "version" : {
  28. "number" : "7.8.0",
  29. "build_flavor" : "default",
  30. "build_type" : "tar",
  31. "build_hash" : "757314695644ea9a1dc2fecd26d1a43856725e65",
  32. "build_date" : "2020-06-14T19:35:50.234439Z",
  33. "build_snapshot" : false,
  34. "lucene_version" : "8.5.1",
  35. "minimum_wire_compatibility_version" : "6.8.0",
  36. "minimum_index_compatibility_version" : "6.0.0-beta1"
  37. },
  38. "tagline" : "You Know, for Search"
  39. }

Docker安装

  1. # 1、需要将elasticsearch的config文件夹拷贝到挂载目录下
  2. # 2、修改elasticsearch.yml 文件
  3. network.host: 0.0.0.0
  4. http.port: 9200
  5. # 3、启动并运行
  6. docker run -e "ES_JAVA_OPTS=-Xms256m -Xmx256m" \
  7. --name elasticsearch -p 9200:9200 -p 9300:9300 \
  8. -e "discovery.type=single-node" \
  9. -v /root/elasticsearch/config:/usr/share/elasticsearch/config \
  10. -d elasticsearch:7.8.0
  11. # 4、测试连接
  12. [root@Ringo config]# curl localhost:9200
  13. {
  14. "name" : "78f3957f5cb9",
  15. "cluster_name" : "elasticsearch",
  16. "cluster_uuid" : "-IsEt9kXQxKemftK6b8RaA",
  17. "version" : {
  18. "number" : "7.8.0",
  19. "build_flavor" : "default",
  20. "build_type" : "docker",
  21. "build_hash" : "757314695644ea9a1dc2fecd26d1a43856725e65",
  22. "build_date" : "2020-06-14T19:35:50.234439Z",
  23. "build_snapshot" : false,
  24. "lucene_version" : "8.5.1",
  25. "minimum_wire_compatibility_version" : "6.8.0",
  26. "minimum_index_compatibility_version" : "6.0.0-beta1"
  27. },
  28. "tagline" : "You Know, for Search"
  29. }

2.2.安装elasticsearch-head

下载地址:https://github.com/mobz/elasticsearch-head

  1. # 1、安装node.js
  2. # 2、安装grunt
  3. npm install -g grunt-cli
  4. # 查看grunt是否安装成功
  5. grunt -version
  6. # 3、克隆elasticsearch-head项目
  7. # 4、到elasticsearch-head目录下安装依赖
  8. npm install
  9. # 5、运行elasticsearch-head
  10. npm run start
  11. # 6、开启elasticsearch服务端的跨域支持,进入elasticsearch.yml
  12. # 在文件末尾添加如下配置
  13. http.cors.enabled: true
  14. http.cors.allow-origin: "*"
  15. node.master: true
  16. node.data: true
  17. # 取消以下两行的注释
  18. cluster.name: my-application
  19. node.name: node-1
  20. # 7、测试连接
  21. http://localhost:9100/

2.3.安装kibana

下载地址:https://www.elastic.co/cn/downloads/kibana

Kibana的版本要和elasticsearch版本对应!

Docker安装

  1. # 1、拉取kibana镜像
  2. docker pull kibana:7.8.0
  3. # 2、修改kibana.yml
  4. server.port: 5601
  5. server.name: "kibana"
  6. server.host: "0.0.0.0"
  7. elasticsearch.hosts: ["http://172.18.0.5:9200"]
  8. # 3、运行kibana
  9. docker run --name kibana --privileged=true -p 5601:5601 \
  10. -v /root/kibana/config:/usr/share/kibana/config \
  11. -d kibana:7.8.0
  12. # 4、测试连接
  13. http://39.97.3.60:5601
  14. # 5、kibana汉化 打开kibana.yml
  15. i18n.locale: "zh-CN" # 重启docker容器这样就可以将kibana汉化了!

3.ES核心概念

3.1.基本介绍

elasticsearch是面向文档的。

关系型数据库 和 elasticsearch客观对比!一切都是JSON!

Relational DB

Elasticsearcg

数据库(database)

索引(index)

表(tables)

types

行(rows)

documents

字段(columns)

fields

elasticsearch(集群)中可以包含多个索引(数据库),每个索引中可以包含多个类型(表),每个类型下又包含多个文档(行),每个文档中又包含多个字段(列)。

物理设计:

elasticsearch在后台把每个索引划分成多个分片,每分分片可以在集群中的不同服务器之间迁移!

一个elasticsearch就是一个集群。默认的集群名称就是 elasticsearch

逻辑设计:

一个索引类型中,包含多个文档,比如说文档1,文档2。当我们索引一篇文档时,可以通过这样的一个序列找到它: 索引>类型>文档ID,通过这个组合我们就能索引到某个具体的文档。注意:ID不必是整数,实际上它是个字符串!

3.2.文档

文档就类比表中的一条条数据。

  1. user
  2. 1 zangsan 18
  3. 2 lisi 3

之前说 elasticsearch是面向文档的,那么就意味着索引和搜索数据的最小单位是文档, elasticsearch中,文档有几个重要的属性:

  • 自我包含,一篇文档同时包含字段和对应的值,也就是同时包含 key-value
  • 可以是层次型的,一个文档中包含自文档,复杂的逻辑实体就是这么来的!
  • 灵活的结构,文档不依赖预先定义的模式,我们知道关系型数据库中,要提前定义字段才能使用,在 elasticsearch中,对于字段是非常灵活的,有时候,我们可以忽略该字段,或者动态的添加一个新的字段。

3.3.类型

类型是文档的逻辑容器,就像关系型数据库一样,表格是行的容器。类型中对于字段的定义成为映射,比如 name映射为字符串类型。我们说文档是无模式的,他们不需要拥有映射中所定义的所有字段,比如新增一个字段,那么 elasticsearch是怎么做的呢? elasticsearch会自动的将新字段加入映射,但是这个字段的不确定它是什么类型, elasticsearch就开始猜,如果这个值是18,那么 elasticsearch就会认为它是整型,但是 elasticsearch也可能猜不对,所以最安全的办法的是提前定义好所需要的映射,这点跟关系型数据库殊途同归了,先是定义好字段,然后再使用。

3.4.索引

索引就类比数据库!

索引是映射类型的容器, elasticsearch中的索引是一个非常大的文档集合。索引存储了映射类型的字段和其他设置。然后它们被存储到了各个分片上。我们来研究下分片是如何工作的。

物理设计:节点和分片 如何工作

一个集群至少有一个节点,而一个节点就是一个 elasticsearch进程,节点可以有多个索引,如果创建索引,那么索引将会有5个分片( primary shard,又称主分片)构成,每一个主分片会有一个副本( replica shard,又称复制分片)。

上图是一个有3个节点的集群,可以直接看到主分片[P]和对应的复制分片[R]都不会在同一个节点内,这样有利于某个节点挂掉了,数据也不会丢失。实际上,一个分片是一个 Lucene索引,一个包含倒排索引的文件目录,倒排索引的结构使得 elasticsearch在不扫描全部文档的情况下,就能告诉你哪些文档包含特定的关键字。不过,倒排索引是什么?

3.5.倒排索引

倒排索引基本介绍

elasticsearch使用的是一种称为倒排索引的结构,采用 Lucene倒排索引作为底层。这种结构适用于快速的全文检索,一个索引由文档中所有不重复的列表构成,对于每一个词,都有一个包含它的文档列表。例如,现在有两个文档,每个文档包含如下内容:

  1. Study every day,good good up to forever # 文档1包含的内容
  2. To forever,study every day, good good up # 文档2包含的内容

为了创建倒排索引,我们首先要将每个文档拆分成独立的词(或称为词条或者tokens),然后创建一个包含所有不重复的词条的排序列表,然后列出每个词条出现在哪个文档!

term

doc.1

doc.2

Study

×

To

×

every

forever

day

study

×

good

every

to

×

up

现在我们试图搜索to forever,只需要查看包含每个词条的文档

term

doc.1

doc.2

to

×

forever

total

2

1

两个文档都匹配,但是第一个文档比第二个匹配程度更高。如果没有别的条件,现在,这两个包含关键字的都将返回。

创建倒排索引步骤

1、创建文档列表: Lucene首先对原始文档数据进行编号,形成列表,就是一个文档列表。

2、创建倒排索引列表:対原始文档中的数据进行分词,得到词条。対词条进行编号,以词条创建索引。然后记录下包含该词条的所有文档编号及其他信息。

搜索的过程:

当用户输入任意的词条时,首先对用户输入的数据进行分词,得到用户要搜索的所有词条,然后拿着这些词条去倒排索引列表中进行匹配。找到这些词条就能找到包含这些词条的所有文档的编号。

然后根据这些编号去文档列表中找到文档。

4.IK分词器插件

4.1.什么是IK分词器?

分词:即把一段中文或者别的划分为一个个的关键字,我们在搜索时候会把自己的信息进行分词,会把数据库中或者索引库中的数据进行分词,然后进行一个匹配操作,默认的中文分词是将每个字看成一个词,比如"我喜欢你"会被分为"我","喜","欢","你",这显然是不符合要求的,所以我们需要安装中文分词器ik来解决这个问题。

如果要使用中文,建议使用ik分词器。

IK提供了两个分词算法: ik_smartik_max_word,其中 ik_smart为最少切分, ik_max_word为最细粒度划分!

4.2.安装IK分词器插件

Docker安装

压缩文件下载地址:https://github.com/medcl/elasticsearch-analysis-ik/releases

代码语言:javascript
复制
  1. # 注意IK要和ES版本一直
  2. # 1、进入Docker容器执行
  3. ./bin/elasticsearch-plugin install https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v7.8.0/elasticsearch-analysis-ik-7.8.0.zip
  4. # 2、查看IK是否安装成功
  5. [root@a2fa79fcb8ef bin]# ./elasticsearch-plugin list
  6. analysis-ik

4.3.查看不同的分词器

ik_smart最少切分

ikmaxword为最细粒度划分!穷尽所有可能!

4.3.自定义字典

给IK增加字典

  1. 棠时
  2. <?xml version="1.0" encoding="UTF-8"?>
  3. <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
  4. <properties>
  5. <comment>IK Analyzer 扩展配置</comment>
  6. <entry key="ext_dict">ringo.dic</entry>
  7. <entry key="ext_stopwords"></entry>
  8. </properties>

测试

  1. # 1、没有增加自己定义的字典之前
  2. # 测试样例
  3. GET _analyze
  4. {
  5. "analyzer": "ik_smart",
  6. "text": "棠时"
  7. }
  8. # 结果
  9. {
  10. "tokens" : [
  11. {
  12. "token" : "棠",
  13. "start_offset" : 0,
  14. "end_offset" : 1,
  15. "type" : "CN_CHAR",
  16. "position" : 0
  17. },
  18. {
  19. "token" : "时",
  20. "start_offset" : 1,
  21. "end_offset" : 2,
  22. "type" : "CN_CHAR",
  23. "position" : 1
  24. }
  25. ]
  26. }
  27. # 2、增加自己自定义的词典并重启elasticsearch之后
  28. # 测试样例
  29. GET _analyze
  30. {
  31. "analyzer": "ik_smart",
  32. "text": "棠时"
  33. }
  34. # 结果
  35. {
  36. "tokens" : [
  37. {
  38. "token" : "棠时",
  39. "start_offset" : 0,
  40. "end_offset" : 2,
  41. "type" : "CN_WORD",
  42. "position" : 0
  43. }
  44. ]
  45. }

5.关于索引的基本操作

5.1.Rest模板

method

url地址

描述

PUT

localhost:9200/索引名称/类型名称/文档id

创建文档(指定文档id)

POST

localhost:9200/索引名称/类型名称

创建文档(随机文档id)

POST

localhost:9200/索引名称/类型名称/文档id/_update

修改文档

DELETE

localhost:9200/索引名称/类型名称/文档id

删除文档

GET

localhost:9200/索引名称/类型名称/文档id

通过文档id查询文档

POST

localhost:9200/索引名称/类型名称/_search

查询所有数据

5.2.添加索引

当然不是只有 kibana可以测试,使用其他软件如 Postman或者T alend APTTester都可以。

  1. # 使用Postman测试
  2. # 基本语法
  3. POST请求 http://39.97.3.60:9200/索引名/~类型名~/文档id
  4. {请求体}
  5. # 1、测试创建索引(添加了文档)
  6. POST请求 http://39.97.3.60:9200/test1/_doc/1
  7. {
  8. "name": "Ringo",
  9. "age": 3
  10. }
  11. # 2、测试创建索引规则(不添加文档)
  12. PUT请求 http://39.97.3.60:9200/test2
  13. {
  14. "mappings": {
  15. "properties": {
  16. "name": {
  17. "type": "text"
  18. },
  19. "age": {
  20. "type": "long"
  21. },
  22. "birthday": {
  23. "type": "date"
  24. }
  25. }
  26. }
  27. }
  28. # 3、获取索引具体的信息
  29. GET请求 http://39.97.3.60:9200/test2

5.3.查看索引默认信息

  1. # 1、创建索引并添加数据
  2. POST请求 http://39.97.3.60:9200/test3/_doc/1
  3. {
  4. "name": "Ringo",
  5. "age": 18,
  6. "birth": "1997-11-13"
  7. }
  8. # 2、我们自己没有为索引写mapping映射查看索引默认的信息
  9. GET请求 http://39.97.3.60:9200/test3
  10. # 返回的结果,ES给我们的字段自动加上了类型
  11. {
  12. "test3": {
  13. "aliases": {},
  14. "mappings": {
  15. "properties": {
  16. "age": {
  17. "type": "long"
  18. },
  19. "birth": {
  20. "type": "date"
  21. },
  22. "name": {
  23. "type": "text",
  24. "fields": {
  25. "keyword": {
  26. "type": "keyword",
  27. "ignore_above": 256
  28. }
  29. }
  30. }
  31. }
  32. },
  33. }
  34. }

如果自己的文档字段没有指定类型,那么 elasticsearch就会给我们默认配置字段类型!

5.4.扩展命令

  1. # 1、查看ElasticSearch健康状态
  2. GET请求 http://39.97.3.60:9200/_cat/health
  3. # 2、查看ElasticSearch详细信息
  4. GET请求 http://39.97.3.60:9200/_cat/indices?v

5.5.修改索引

  1. # 方式一:修改文档
  2. PUT请求 http://39.97.3.60:9200/test3/_doc/1
  3. {
  4. "name": "Ringo",
  5. "age": 18,
  6. "birth": "1997-11-13"
  7. }
  8. # 返回结果
  9. {
  10. "_index": "test3",
  11. "_type": "_doc",
  12. "_id": "1",
  13. "_version": 3, # 发现修改一次之后版本号会增加1
  14. "result": "updated",
  15. "_shards": {
  16. "total": 2,
  17. "successful": 1,
  18. "failed": 0
  19. },
  20. }
  21. # 方式二:修改文档
  22. POST请求 http://39.97.3.60:9200/test3/_doc/1/_update
  23. {
  24. "doc": {
  25. "name": "Ringo",
  26. "age": 19,
  27. "birth": "1997-11-13"
  28. }
  29. }
  30. # 返回结果
  31. {
  32. "_index": "test3",
  33. "_type": "_doc",
  34. "_id": "1_update",
  35. "_version": 3,
  36. "result": "updated",
  37. "_shards": {
  38. "total": 2,
  39. "successful": 1,
  40. "failed": 0
  41. },
  42. }

5.6.删除索引

  1. # 1、删除索引
  2. DELETE请求 http://39.97.3.60:9200/test1
  3. # 2、删除文档
  4. DELETE请求 http://39.97.3.60:9200/test3/_doc/1

6.关于文档的基本操作

6.1.基本操作

  1. # 1、创建文档
  2. POST请求 http://39.97.3.60:9200/ringo/_doc/1
  3. {
  4. "name": "RingoTangs",
  5. "age": 18,
  6. "describe": "铃铃铃",
  7. "tags": ["阳光","喜欢篮球","喜欢学习"]
  8. }
  9. # 2、获取数据
  10. GET请求 http://39.97.3.60:9200/ringo/_doc/1
  11. # 3、更新数据,PUT如果不写全字段就会被覆盖
  12. PUT请求 http://39.97.3.60:9200/ringo/_doc/3
  13. {
  14. "name": "李四233",
  15. "age": 30,
  16. "describe": "法外狂徒,李四",
  17. "tags": ["靓仔","喜欢唱歌","喜欢学习"]
  18. }
  19. # 4、推荐使用POST来更新,自由度很高,携带的JSON可以只写修改字段
  20. POST请求 http://39.97.3.60:9200/ringo/_doc/3/_update
  21. {
  22. "doc": {
  23. "name": "李四999"
  24. }
  25. }

6.2.简单查询

  1. # 1、简单的条件查询
  2. GET请求 http://39.97.3.60:9200/ringo/_search?q=name:张三
  3. GET请求 http://39.97.3.60:9200/ringo/_search?q=tags:篮球

6.3.复杂查询

  1. # 1、带上查询条件,match只要名字中有"张三"的都会被检索出来
  2. POST请求 http://39.97.3.60:9200/ringo/_search
  3. {
  4. "query": {
  5. "match": {
  6. "name": "张三"
  7. }
  8. }
  9. }
  10. # 2、查询结果返回具体的字段,使用"_source"
  11. POST请求 http://39.97.3.60:9200/ringo/_search
  12. {
  13. "query": {
  14. "match": {
  15. "name": "张三"
  16. }
  17. },
  18. "_source": ["name", "age"]
  19. }
  20. # 3、查询结果排序,使用"sort",通过某个字段进行排序
  21. POST请求 http://39.97.3.60:9200/ringo/_search
  22. {
  23. "query": {
  24. "match": {
  25. "name": "张三"
  26. }
  27. },
  28. "_source": ["name", "age"],
  29. "sort": [{
  30. "age": {
  31. "order": "asc"
  32. }
  33. }]
  34. }
  35. # 4、分页查询 "from"从哪里开始,“size"每页显示几条数据
  36. POST请求 http://39.97.3.60:9200/ringo/_search
  37. {
  38. "query": {
  39. "match": {
  40. "name": "张三"
  41. }
  42. },
  43. "_source": ["name", "age"],
  44. "from": 0,
  45. "size": 1
  46. }
  47. # 5、通过"bool"和"must"组合使用,可以多条件组合查询,等价于and
  48. # 会把name="张三"和age=30的文档查出来
  49. POST请求 http://39.97.3.60:9200/ringo/_search
  50. {
  51. "query": {
  52. "bool": {
  53. "must": [{
  54. "match": {
  55. "name": "张三"
  56. }
  57. }, {
  58. "match": {
  59. "age": 30
  60. }
  61. }]
  62. }
  63. }
  64. }
  65. # 4、"should"有一个条件符合即可,等价于or
  66. # 会把name="张三"或者age=18的文档查出来
  67. POST请求 http://39.97.3.60:9200/ringo/_search
  68. {
  69. "query": {
  70. "bool": {
  71. "should": [{
  72. "match": {
  73. "name": "张三"
  74. }
  75. }, {
  76. "match": {
  77. "age": 18
  78. }
  79. }]
  80. }
  81. }
  82. }
  83. # 5、"must_not"查询年龄不是18岁的人
  84. POST请求 http://39.97.3.60:9200/ringo/_search
  85. {
  86. "query": {
  87. "bool": {
  88. "must_not": [{
  89. "match": {
  90. "age": 18
  91. }
  92. }]
  93. }
  94. }
  95. }
  96. # 6、查询结果过滤,范围查询
  97. # gt:大于
  98. # gte:大于等于
  99. # lt:小于
  100. # lte:小于等于
  101. POST请求 http://39.97.3.60:9200/ringo/_search
  102. {
  103. "query": {
  104. "bool": {
  105. "must":[{
  106. "match": {
  107. "name": "张三"
  108. }
  109. }],
  110. "filter": {
  111. "range": {
  112. "age": {
  113. "gt": 19
  114. }
  115. }
  116. }
  117. }
  118. }
  119. }
  120. # 7、多条件使用空格隔开,只要满足其中一个结果就可以被查出
  121. POST请求 http://39.97.3.60:9200/ringo/_search
  122. {
  123. "query": {
  124. "match": {
  125. "tags": "喜欢 阳光"
  126. }
  127. }
  128. }
  129. # 8、精确查询term "term"输入的词不会被分词,"match"会使用分词器解析
  130. # term查询是直接通过倒排索引指定的词条进行精确查找的!
  131. # 注意:keyword类型的字段不会被分词器解析!!!
  132. PUT /testdb
  133. {
  134. "mappings": {
  135. "properties": {
  136. "name": {
  137. "type": "text" # text类型会走分词器
  138. },
  139. "describe": {
  140. "type": "keyword" # keyword不会走分词器,当成一个整体
  141. }
  142. }
  143. }
  144. }
  145. GET /testdb/_search
  146. {
  147. "query": {
  148. "term": {
  149. "describe": "Ringo 每天都要好好学习"
  150. }
  151. }
  152. }
  153. # 9、高亮查询
  154. # 测试样例
  155. GET /testdb/_search
  156. {
  157. "query": {
  158. "match": {
  159. "name": "棠时"
  160. }
  161. },
  162. "highlight": {
  163. "pre_tags": "<p class='key' style='color:red'>",
  164. "post_tags": "</p>",
  165. "fields": {
  166. "name": {}
  167. }
  168. }
  169. }
  170. # 结果
  171. "highlight" : {
  172. "name" : [
  173. "<p class='key' style='color:red'>棠</p><p class='key' style='color:red'>时</p>每天都要开心"
  174. ]
  175. }

7.SpringBoot整合ES

官方文档地址:https://www.elastic.co/guide/en/elasticsearch/client/index.html

7.1.基本环境和配置

pom

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <groupId>com.ymy</groupId>
  7. <artifactId>elastic-search-api</artifactId>
  8. <version>1.0-SNAPSHOT</version>
  9. <properties>
  10. <elasticsearch.version>7.8.0</elasticsearch.version>
  11. </properties>
  12. <parent>
  13. <groupId>org.springframework.boot</groupId>
  14. <artifactId>spring-boot-starter-parent</artifactId>
  15. <version>2.2.4.RELEASE</version>
  16. </parent>
  17. <dependencies>
  18. <dependency>
  19. <groupId>org.springframework.boot</groupId>
  20. <artifactId>spring-boot-starter-web</artifactId>
  21. </dependency>
  22. <dependency>
  23. <groupId>org.springframework.boot</groupId>
  24. <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
  25. </dependency>
  26. <dependency>
  27. <groupId>org.springframework.boot</groupId>
  28. <artifactId>spring-boot-starter-test</artifactId>
  29. <scope>test</scope>
  30. </dependency>
  31. </dependencies>
  32. <build>
  33. <plugins>
  34. <plugin>
  35. <groupId>org.springframework.boot</groupId>
  36. <artifactId>spring-boot-maven-plugin</artifactId>
  37. <version>2.2.6.RELEASE</version>
  38. <configuration>
  39. <fork>true</fork>
  40. <addResources>true</addResources>
  41. </configuration>
  42. </plugin>
  43. </plugins>
  44. </build>
  45. </project>

SpringBoot的依赖中,默认用的 elasticsearch版本还是6.8.6。我们只需要在我们自己的 pom文件的 <properties>修改 elasticsearch版本为 Linux服务器上的版本即可。

  1. <properties>
  2. <elasticsearch.version>6.8.6</elasticsearch.version>
  3. </properties>
  4. <dependencyManagement>
  5. <dependencies>
  6. <dependency>
  7. <groupId>org.elasticsearch</groupId>
  8. <artifactId>elasticsearch</artifactId>
  9. <version>${elasticsearch.version}</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.elasticsearch.client</groupId>
  13. <artifactId>transport</artifactId>
  14. <version>${elasticsearch.version}</version>
  15. </dependency>
  16. ....
  17. </dependencies>
  18. </dependencyManagement>

elasticsearch配置

  1. import org.apache.http.HttpHost;
  2. import org.elasticsearch.client.RestClient;
  3. import org.elasticsearch.client.RestHighLevelClient;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.Configuration;
  6. @Configuration
  7. public class ElasticSearchConf {
  8. @Bean(name = "client")
  9. public RestHighLevelClient restHighLevelClient() {
  10. RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("39.97.3.60", 9200, "http")));
  11. return client;
  12. }
  13. }

ES自动配置

SpringBoot默认将 RestHighLevelClient加到了容器中,详情见 org.springframework.boot.autoconfigure.elasticsearch.rest.RestClientConfigurations

  1. package org.springframework.boot.autoconfigure.elasticsearch.rest;
  2. class RestClientConfigurations {
  3. @Configuration(proxyBeanMethods = false)
  4. @ConditionalOnClass(RestHighLevelClient.class)
  5. static class RestHighLevelClientConfiguration {
  6. @Bean
  7. @ConditionalOnMissingBean
  8. RestHighLevelClient elasticsearchRestHighLevelClient(RestClientBuilder restClientBuilder) {
  9. return new RestHighLevelClient(restClientBuilder);
  10. }
  11. }
  12. }

7.2.关于索引的API操作

  1. package com.ymy.elasticsearch;
  2. import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
  3. import org.elasticsearch.action.support.master.AcknowledgedResponse;
  4. import org.elasticsearch.client.RequestOptions;
  5. import org.elasticsearch.client.RestHighLevelClient;
  6. import org.elasticsearch.client.indices.CreateIndexRequest;
  7. import org.elasticsearch.client.indices.CreateIndexResponse;
  8. import org.elasticsearch.client.indices.GetIndexRequest;
  9. import org.elasticsearch.client.indices.GetIndexResponse;
  10. import org.junit.Test;
  11. import org.junit.runner.RunWith;
  12. import org.springframework.boot.test.context.SpringBootTest;
  13. import org.springframework.test.context.junit4.SpringRunner;
  14. import javax.annotation.Resource;
  15. /**
  16. * ES关于索引的操作
  17. */
  18. @RunWith(SpringRunner.class)
  19. @SpringBootTest
  20. public class TestESIdxAPI {
  21. @Resource
  22. private RestHighLevelClient client;
  23. public static final String INDEX_NAME = "test_es_idx_api";
  24. /**
  25. * 1、创建索引
  26. */
  27. @Test
  28. public void createIndex() throws Exception {
  29. // 1、创建索引请求
  30. CreateIndexRequest request = new CreateIndexRequest(INDEX_NAME);
  31. // 2、执行请求 client.indices()返回対索引操作的对象
  32. CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
  33. // 3、打印响应
  34. System.out.println(response.isAcknowledged());
  35. }
  36. /**
  37. * 2、获取索引
  38. */
  39. @Test
  40. public void getIndex() throws Exception {
  41. // 1、获取索引请求
  42. GetIndexRequest request = new GetIndexRequest(INDEX_NAME);
  43. // 2、判断索引是否存在
  44. boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
  45. System.out.println(exists);
  46. // 3、执行请求
  47. GetIndexResponse response = client.indices().get(request, RequestOptions.DEFAULT);
  48. // 4、获得索引信息
  49. System.out.println(response.getSettings());
  50. }
  51. /**
  52. * 3、删除索引
  53. */
  54. @Test
  55. public void deleteIndex() throws Exception{
  56. // 1、删除索引请求
  57. DeleteIndexRequest request = new DeleteIndexRequest(INDEX_NAME);
  58. // 2、执行请求
  59. AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
  60. // 3、返回结果
  61. System.out.println(response.isAcknowledged());
  62. }
  63. }

7.3.关于文档的API操作

  1. package com.ymy.elasticsearch;
  2. import com.fasterxml.jackson.databind.ObjectMapper;
  3. import com.ymy.elasticsearch.entity.User;
  4. import org.elasticsearch.action.bulk.BulkRequest;
  5. import org.elasticsearch.action.bulk.BulkResponse;
  6. import org.elasticsearch.action.delete.DeleteRequest;
  7. import org.elasticsearch.action.delete.DeleteResponse;
  8. import org.elasticsearch.action.get.GetRequest;
  9. import org.elasticsearch.action.get.GetResponse;
  10. import org.elasticsearch.action.index.IndexRequest;
  11. import org.elasticsearch.action.index.IndexResponse;
  12. import org.elasticsearch.action.search.SearchRequest;
  13. import org.elasticsearch.action.search.SearchResponse;
  14. import org.elasticsearch.action.update.UpdateRequest;
  15. import org.elasticsearch.action.update.UpdateResponse;
  16. import org.elasticsearch.client.RequestOptions;
  17. import org.elasticsearch.client.RestHighLevelClient;
  18. import org.elasticsearch.common.unit.TimeValue;
  19. import org.elasticsearch.common.xcontent.XContentType;
  20. import org.elasticsearch.index.query.QueryBuilders;
  21. import org.elasticsearch.search.SearchHit;
  22. import org.elasticsearch.search.builder.SearchSourceBuilder;
  23. import org.junit.Test;
  24. import org.junit.runner.RunWith;
  25. import org.springframework.beans.factory.annotation.Autowired;
  26. import org.springframework.boot.test.context.SpringBootTest;
  27. import org.springframework.test.context.junit4.SpringRunner;
  28. import javax.annotation.Resource;
  29. import java.util.ArrayList;
  30. import java.util.Arrays;
  31. import java.util.List;
  32. /**
  33. * ES关于文档的操作
  34. */
  35. @RunWith(SpringRunner.class)
  36. @SpringBootTest
  37. public class TestESDocAPI2 {
  38. @Resource
  39. private RestHighLevelClient client;
  40. @Autowired
  41. private ObjectMapper objectMapper;
  42. public static final String INDEX_NAME = "test_es_idx_api";
  43. /**
  44. * 1、添加文档
  45. */
  46. @Test
  47. public void addDocument() throws Exception {
  48. // 1、创建对象
  49. User user = new User("张三", "234");
  50. // 2、创建请求
  51. IndexRequest request = new IndexRequest(INDEX_NAME);
  52. // 3、设置规格
  53. request.id("1").timeout(TimeValue.timeValueSeconds(5));
  54. // 4、将数据放入请求
  55. request.source(objectMapper.writeValueAsString(user), XContentType.JSON);
  56. // 5、发送请求
  57. IndexResponse response = client.index(request, RequestOptions.DEFAULT);
  58. // 6、打印响应
  59. System.out.println(response.status()); // CREATED 创建成功
  60. System.out.println(response.toString());
  61. }
  62. /**
  63. * 2、获取文档信息
  64. */
  65. @Test
  66. public void getDocument() throws Exception {
  67. // 1、创建请求
  68. GetRequest request = new GetRequest(INDEX_NAME, "1");
  69. // 不获取"_source"的上下文
  70. //request.fetchSourceContext(new FetchSourceContext(false));
  71. // 2、判断文档是否存在
  72. boolean exists = client.exists(request, RequestOptions.DEFAULT);
  73. System.out.println(exists);
  74. // 3、执行请求
  75. GetResponse response = client.get(request, RequestOptions.DEFAULT);
  76. // 4、打印响应结果
  77. System.out.println(response.isExists());
  78. System.out.println(response.getSourceAsMap()); // {password=234, username=张三}
  79. System.out.println(response.getSource()); // {password=234, username=张三}
  80. System.out.println(response.getSourceAsString()); // {"username":"张三","password":"234"}
  81. }
  82. /**
  83. * 3、更新文档信息
  84. */
  85. @Test
  86. public void updateDocument() throws Exception {
  87. // 1、创建请求
  88. UpdateRequest request = new UpdateRequest(INDEX_NAME, "1");
  89. // 2、创建更新的对象
  90. User user = new User("李四44", "234");
  91. // 3、将更新对象放入请求
  92. request.doc(objectMapper.writeValueAsString(user), XContentType.JSON);
  93. // 4、执行请求
  94. UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
  95. // 5、打印结果
  96. System.out.println(response.status()); // OK 表示修改成功!
  97. System.out.println(response.toString());
  98. }
  99. /**
  100. * 4、删除文档信息
  101. */
  102. @Test
  103. public void deleteDocument() throws Exception {
  104. // 1、创建请求
  105. DeleteRequest request = new DeleteRequest(INDEX_NAME, "1");
  106. request.timeout(TimeValue.timeValueSeconds(2));
  107. // 2、执行请求
  108. DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
  109. // 3、打印结果
  110. System.out.println(response.status()); // OK 删除成功
  111. System.out.println(response.toString());
  112. }
  113. /**
  114. * 5、批量插入数据
  115. */
  116. @Test
  117. public void bulkAddDocs() throws Exception {
  118. // 1、创建请求
  119. BulkRequest request = new BulkRequest();
  120. request.timeout("10s");
  121. // 2、创建数据
  122. List<User> users = new ArrayList<>();
  123. users.add(new User("张三", "123"));
  124. users.add(new User("李四", "123"));
  125. users.add(new User("王五", "123"));
  126. users.add(new User("赵六", "123"));
  127. users.add(new User("王二狗", "123"));
  128. // 3、将数据放到请求中
  129. for (int i = 0; i < users.size(); i++) {
  130. request.add(new IndexRequest(INDEX_NAME)
  131. .id(String.valueOf(i + 1))
  132. .source(objectMapper.writeValueAsString(users.get(i)), XContentType.JSON)
  133. );
  134. }
  135. // 4、执行请求
  136. BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
  137. // 5、打印结果
  138. System.out.println(response.status()); // OK 批量插入成功!
  139. System.out.println(response.hasFailures()); // false 表示批量插入成功!
  140. }
  141. /**
  142. * 6、查询
  143. */
  144. @Test
  145. public void query() throws Exception {
  146. // 1、创建请求
  147. SearchRequest request = new SearchRequest(INDEX_NAME);
  148. // 2、构建搜索条件
  149. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder()
  150. .query(QueryBuilders.matchQuery("username", "张三"))// 查询条件
  151. .timeout(TimeValue.timeValueSeconds(5)) // 设置超时时间
  152. .from(0) // 分页查询
  153. .size(3);
  154. // 3、请求中添加搜索条件
  155. request.source(searchSourceBuilder);
  156. // 4、执行请求
  157. SearchResponse response = client.search(request, RequestOptions.DEFAULT);
  158. // 5、打印结果
  159. System.out.println(response.status()); // OK
  160. /**
  161. * {
  162. * "_index" : "test_es_idx_api",
  163. * "_type" : "_doc",
  164. * "_id" : "1",
  165. * "_score" : 2.8796844,
  166. * "_source" : {
  167. * "username" : "张三",
  168. * "password" : "123"
  169. * }
  170. * }
  171. */
  172. response.getHits().forEach(System.out::println);
  173. // 这个SearchHits是返回的全部信息
  174. // System.out.println(objectMapper.writeValueAsString(response.getHits()));
  175. // SearchHit主要包装"_source"
  176. SearchHit[] hits = response.getHits().getHits();
  177. // {"username":"张三","password":"123"}
  178. Arrays.stream(hits).forEach(hit -> System.out.println(hit.getSourceAsString()));
  179. }
  180. }
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2023-06-28,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 趣学程序 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • ElasticSearch
  • 1.elasticsearch 概述
  • 2.elasticsearch环境
    • 2.1.安装elasticsearch
      • 2.2.安装elasticsearch-head
        • 2.3.安装kibana
        • 3.ES核心概念
          • 3.1.基本介绍
            • 3.2.文档
              • 3.3.类型
                • 3.4.索引
                  • 3.5.倒排索引
                  • 4.IK分词器插件
                    • 4.1.什么是IK分词器?
                      • 4.2.安装IK分词器插件
                        • 4.3.查看不同的分词器
                          • 4.3.自定义字典
                          • 5.关于索引的基本操作
                            • 5.1.Rest模板
                              • 5.2.添加索引
                                • 5.3.查看索引默认信息
                                  • 5.4.扩展命令
                                    • 5.5.修改索引
                                      • 5.6.删除索引
                                      • 6.关于文档的基本操作
                                        • 6.1.基本操作
                                          • 6.2.简单查询
                                            • 6.3.复杂查询
                                            • 7.SpringBoot整合ES
                                              • 7.1.基本环境和配置
                                                • 7.2.关于索引的API操作
                                                  • 7.3.关于文档的API操作
                                                  相关产品与服务
                                                  Elasticsearch Service
                                                  腾讯云 Elasticsearch Service(ES)是云端全托管海量数据检索分析服务,拥有高性能自研内核,集成X-Pack。ES 支持通过自治索引、存算分离、集群巡检等特性轻松管理集群,也支持免运维、自动弹性、按需使用的 Serverless 模式。使用 ES 您可以高效构建信息检索、日志分析、运维监控等服务,它独特的向量检索还可助您构建基于语义、图像的AI深度应用。
                                                  领券
                                                  问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档