ElasticSearch分布式搜索引擎

一、ElasticSearch

KuangStudy

ElasticSearch学习视频:狂神说ElasticSearch教程

KuangStudy
https://www.kuangstudy.com/course

ElasticSearch学习视频(狂神说):
https://www.bilibili.com/video/BV17a4y1x7zq?p=1

狂神说ElasticSearch笔记:
https://www.kuangstudy.com/bbs/1354069127022583809

ElasticSearch官方分布式搜索和分析引擎:
https://www.elastic.co/cn/elasticsearch/

Java REST Client:
https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/index.html

京东官网:
https://www.jd.com/

模仿京东前端资料:
链接:https://pan.baidu.com/s/15mqnRdy5OVuBe9-dz4kg5w 
提取码:3r7l

一、概述

1、官网
 官网:https://www.elastic.co/cn/downloads/elasticsearch 

Elaticsearch,简称为es,es是一个开源的高扩展分布式全文检索引擎,它可以近乎实时的存储检索数据;本身扩展性很好,可以扩展到上百台服务器,处理PB级别(大数据时代)的数据。es也使用java开发并使用Lucene作为其核心来实现所有索引和搜索的功能,但是它的目的通过简单的RESTful API来隐藏Lucene的复杂性,从而让全文搜索变得简单

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


2、历史

多年前,一个叫做Shay Banon的刚结婚不久的失业开发者,由于妻子要去伦敦学习厨师,他便跟着也去了。在他找工作的过程中,为了给妻子构建一个食谱的搜索引擎,他开始构建一个早期版本的Lucene。

直接基于Lucene工作会比较困难,所以Shay开始抽象Lucene代码以便lava程序员可以在应用中添加搜索功能。他发布了他的第一个开源项目,叫做“Compass”。

后来Shay找到一份工作,这份工作处在高性能和内存数据网格的分布式环境中,因此高性能的、实时的、分布式的搜索引擎也是理所当然需要的。然后他决定重写Compass库使其成为一个独立的服务叫做Elasticsearch。

第一个公开版本出现在2010年2月,在那之后Elasticsearch已经成为Github上最受欢迎的项目之一,代码贡献者超过300人。一家主营Elasticsearch的公司就此成立,他们一边提供商业支持一边开发新功能,不过Elasticsearch将永远开源且对所有人可用。

Shay的妻子依旧等待着她的食谱搜索……


3、谁在使用

1、维基百科,类似百度百科,全文检索,高亮,搜索推荐/2
2、The Guardian (国外新闻网站) ,类似搜狐新闻,用户行为日志(点击,浏览,收藏,评论) +社交网络数据(对某某新闻的相关看法) ,数据分析,给到每篇新闻文章的作者,让他知道他的文章的公众反馈(好,坏,热门,垃圾,鄙视,崇拜)
3、Stack Overflow (国外的程序异常讨论论坛) , IT问题,程序的报错,提交上去,有人会跟你讨论和回答,全文检索,搜索相关问题和答案,程序报错了,就会将报错信息粘贴到里面去,搜索有没有对应的答案
4、GitHub (开源代码管理),搜索 上千亿行代码
5、电商网站,检索商品
6、日志数据分析, logstash采集日志, ES进行复杂的数据分析, ELK技术, elasticsearch+logstash+kibana
7、商品价格监控网站,用户设定某商品的价格阈值,当低于该阈值的时候,发送通知消息给用户,比如说订阅牙膏的监控,如果高露洁牙膏的家庭套装低于50块钱,就通知我,我就去买
8、BI系统,商业智能, Business Intelligence。比如说有个大型商场集团,BI ,分析一下某某区域最近3年的用户消费 金额的趋势以及用户群体的组成构成,产出相关的数张报表, **区,最近3年,每年消费金额呈现100%的增长,而且用户群体85%是高级白领,开-个新商场。ES执行数据分析和挖掘, Kibana进行数据可视化
9、国内:站内搜索(电商,招聘,门户,等等),IT系统搜索(OA,CRM,ERP,等等),数据分析(ES热门
的一一个使用场景)

二、ES和Solr

1、ElasticSearch简介

  • Elasticsearch是一个实时分布式搜索和分析引擎。 它让你以前所未有的速度处理大数据成为可能。
  • 它用于全文搜索、结构化搜索、分析以及将这三者混合使用:
  • 维基百科使用Elasticsearch提供全文搜索高亮关键字,以及输入实时搜索(search-asyou-type)和搜索纠错(did-you-mean)等搜索建议功能。
  • 英国卫报使用Elasticsearch结合用户日志和社交网络数据提供给他们的编辑以实时的反馈,以便及时了解公众对新发表的文章的回应。
  • StackOverflow结合全文搜索与地理位置查询,以及more-like-this功能来找到相关的问题和答案。
  • Github使用Elasticsearch检索1300亿行的代码。
  • 但是Elasticsearch不仅用于大型企业,它还让像DataDog以及Klout这样的创业公司将最初的想法变成可扩展的解决方案。
  • Elasticsearch可以在你的笔记本上运行,也可以在数以百计的服务器上处理PB级别的数据。
  • Elasticsearch是一个基于Apache Lucene™的开源搜索引擎。无论在开源还是专有领域, Lucene可被认为是迄今为止最先进、性能最好的、功能最全的搜索引擎库。
    • 但是, Lucene只是一个库。 想要使用它,你必须使用Java来作为开发语言并将其直接集成到你的应用中,更糟糕的是, Lucene非常复杂,你需要深入了解检索的相关知识来理解它是如何工作的。
  • Elasticsearch也使用Java开发并使用Lucene作为其核心来实现所有索引和搜索的功能,但是它的目的通过简单的RESTful API来隐藏Lucene的复杂性,从而让全文搜索变得简单。

2、Solr简介

  • Solr是Apache下的一个顶级开源项目,采用Java开发,它是基于Lucene的全文搜索服务器。Solr提供了比Lucene更为丰富的查询语言,同时实现了可配置可扩展,并对索引、搜索性能进行了优化
  • Solr可以独立运行,运行在letty. Tomcat等这些Selrvlet容器中 , Solr 索引的实现方法很简单,用POST方法向Solr服务器发送一个描述Field及其内容的XML文档, Solr根据xml文档添加、删除、更新索引。Solr 搜索只需要发送HTTP GET请求,然后对Solr返回xml、json等格式的查询结果进行解析,组织页面布局。
  • Solr不提供构建UI的功能, Solr提供了一个管理界面,通过管理界面可以查询Solr的配置和运行情况。
  • Solr是基于lucene开发企业级搜索服务器,实际上就是封装了lucene.
  • Solr是一个独立的企业级搜索应用服务器,它对外提供类似于Web-service的API接口。用户可以通过http请求,向搜索引擎服务器提交-定格式的文件,生成索引;也可以通过提出查找请求,并得到返回结果。

3、ElasticSearch与Solr比较

1、当单纯的对已有数据进行搜索时,Solr更快

1641458940549

2、当实时建立索引时,Solr会产生io阻塞,查询性能较差,ElasticSearch具有明显的优势

1641458985914

3、随着数据量的增加,Solr的搜索效率会变得更低,而ElasticSearch却没有明显的变化

1641459013567

4、转变我们的搜索基础设施后从Solr ElasticSearch,我们看见一个即时~ 50x提高搜索性能!

1641459038741

4、总结

1、es基本是开箱即用(解压就可以用!) ,非常简单。Solr安装略微复杂一丢丢!
2、Solr 利用Zookeeper进行分布式管理,而Elasticsearch自身带有分布式协调管理功能。
3、Solr 支持更多格式的数据,比如JSON、XML、 CSV ,而Elasticsearch仅支持json文件格式
4、Solr 官方提供的功能更多,而Elasticsearch本身更注重于核心功能,高级功能多有第三方插件提供,例如图形化界面需要kibana友好支撑
5、Solr 查询快,但更新索引时慢(即插入删除慢) ,用于电商等查询多的应用;

  • ES建立索引快(即查询慢) ,即实时性查询快,用于facebook新浪等搜索。
  • Solr是传统搜索应用的有力解决方案,但Elasticsearch更适用于新兴的实时搜索应用。

6、Solr比较成熟,有一个更大,更成熟的用户、开发和贡献者社区,而Elasticsearch相对开发维护者较少,更新太快,学习使用成本较高。

三、ElasticSearch(7.16.2版本)

一、安装ElasticSearch(9200)

1、安装ElasticSearch

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

ElasticSearch历史版本下载: https://mirrors.huaweicloud.com/elasticsearch/?C=N&O=D

logstash: https://mirrors.huaweicloud.com/logstash/?C=N&O=D

可视化界面elasticsearch-head.https://github.com/mobz/elasticsearch-head

kibana: https://mirrors.huaweicloud.com/kibana/?C=N&O=D

ik分词器 https://github.com/medcl/elasticsearch-analysis-ik

2、熟悉目录
bin		启动文件
config	配置文件
	log4j2.proerties	日志配置文件
	jvm.opjvm.options	虚拟机相关配置
	elasticsearch.yml	electicsearch的配置文件,默认端口:9200
jdk		环境
lib		相关jar包
logs	日志
modules	功能模块
plugins	插件

1641462341710

1641479909249

3、启动

启动D:\ElasticSearch\elasticsearch-7.16.2\bin下的elasticsearch.bat(双击)

1641479048133

4、访问测试

在浏览器输入默认的端口号(9200)http://127.0.0.1:9200/得到一段json字符串

1641479089807

二、安装ElasticSearch-head(9100)

1、安装可视化界面(ElasticSearch-head)

可视化界面ElasticSearch-head:https://github.com/mobz/elasticsearch-head

1641479958978

2、安装依赖

查看D:\ElasticSearch\elasticsearch-head-master目录下的package.json文件

1641480164288

在D:\ElasticSearch\elasticsearch-head-master目录下,编写cmd,输入cnpm install

1641480418745

输入cls清屏,输入npm run start

1641480587882

访问http://localhost:9100/

1641480819289

3、配置跨域,解决9100连接9200的跨域问题

关闭ElasticSearch的服务,并进入D:\ElasticSearch\elasticsearch-7.16.2\config下,修改elasticsearch.yml配置,解决跨域问题,开启跨域和允许所有人访问

1641481644717

启动D:\ElasticSearch\elasticsearch-7.16.2\bin下的elasticsearch.bat(双击)

1641481747669

在浏览器输入默认的端口号(9200)http://127.0.0.1:9200/仍然可以得到一段json字符串,说明配置没有问题

1641481799026

返回http://localhost:9100/,点击连接,界面显示

1641481982989

  • 初学者可以理解为
    • 索引 可以看做 “数据库”
    • 类型 可以看做 “表”
    • 文档 可以看做 “库中的数据(表中的行)”
  • 这个head,我们只是把它当做可视化数据展示工具,之后所有的查询都在kibana中进行
    • 因为不支持json格式化,不方便

三、安装kibana(5601)

Kibana是一个针对ElasticSearch的开源分析及可视化平台,用来搜索、查看交互存储在Elasticsearch索引中的数据。使用Kibana ,可以通过各种图表进行高级数据分析及展示。Kibana让海量数据更容易理解。它操作简单,基于浏览器的用户界面可以快速创建仪表板( dashboard )实时显示Elasticsearch查询动态。设置Kibana非常简单。无需编码或者额外的基础架构,几分钟内就可以完成Kibana安装并启动Elasticsearch索引监测。

1、安装kibana
版本要与ElasticSearch版本对应

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

kibana历史版本下载: https://mirrors.huaweicloud.com/kibana/?C=N&O=D

1641520219249

2、启动

不知道为啥,我的双击不了,就在D:\ElasticSearch\kibana-7.16.2-windows-x86_64\bin目录下打开cmd,输入kibana.bat,但是启动一直在循环一段代码,用浏览器访问5601端口却可以访问 (出问题)

1641537234574

进入D:\ElasticSearch\elasticsearch-7.16.2\config下,修改elasticsearch.yml配置,增加关闭security即可解决(莫名解决一个bug)

1641540785473

在D:\ElasticSearch\kibana-7.16.2-windows-x86_64\bin目录下打开cmd,输入kibana.bat,启动运行正常,不再循环代码

1641541124650

3、访问测试

1641537307852

4、开发工具

(Postman、curl、head、谷歌浏览器插件)

1641537336204

5、修改配置文件汉化

1641537359229

1641537404499

四、了解ELK

  • ELK是

    Elasticsearch、Logstash、 Kibana三大开源框架首字母大写简称

    。市面上也被成为Elastic Stack。

    • 其中Elasticsearch是一个基于Lucene、分布式、通过Restful方式进行交互的近实时搜索平台框架。
      • 像类似百度、谷歌这种大数据全文搜索引擎的场景都可以使用Elasticsearch作为底层支持框架,可见Elasticsearch提供的搜索能力确实强大,市面上很多时候我们简称Elasticsearch为es。
    • Logstash是ELK的中央数据流引擎,用于从不同目标(文件/数据存储/MQ )收集的不同格式数据,经过过滤后支持输出到不同目的地(文件/MQ/redis/elasticsearch/kafka等)。
    • Kibana可以将elasticsearch的数据通过友好的页面展示出来 ,提供实时分析的功能。
  • 市面上很多开发只要提到ELK能够一致说出它是一个日志分析架构技术栈总称 ,但实际上ELK不仅仅适用于日志分析,它还可以支持其它任何数据分析和收集的场景,日志分析和收集只是更具有代表性。并非唯一性。

收集清洗数据(Logstash) ==> 搜索、存储(ElasticSearch) ==> 展示(Kibana)

1641522301743

四、ElasticSearch核心概念

一、概述

1、索引(ElasticSearch)

  • 包多个分片

2、字段类型(映射)

  • 字段类型映射(字段是整型,还是字符型…)

3、文档

4、分片(Lucene索引,倒排索引)

二、 ElasticSearch是面向文档

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

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

1641522578637

三、物理设计

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

一个人就是一个集群! ,即启动的ElasticSearch服务,默认就是一个集群,且默认集群名为elasticsearch

四、逻辑设计

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

1、文档(”行“)

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

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

尽管我们可以随意的新增或者忽略某个字段,但是,每个字段的类型非常重要,比如一个年龄字段类型,可以是字符串也可以是整形。因为elasticsearch会保存字段和类型之间的映射及其他的设置。这种映射具体到每个映射的每种类型,这也是为什么在elasticsearch中,类型有时候也称为映射类型。

2、类型(“表”)

类型是文档的逻辑容器,就像关系型数据库一样,表格是行的容器。类型中对于字段的定义称为映射,比如name映射为字符串类型。我们说文档是无模式的,它们不需要拥有映射中所定义的所有字段,比如新增一个字段,那么elasticsearch是怎么做的呢?

  • elasticsearch会自动的将新字段加入映射,但是这个字段的不确定它是什么类型,elasticsearch就开始猜,如果这个值是18,那么elasticsearch会认为它是整形。但是elasticsearch也可能猜不对,所以最安全的方式就是提前定义好所需要的映射,这点跟关系型数据库殊途同归了,先定义好字段,然后再使用,别整什么幺蛾子。
3、索引(“库”)

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

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

创建新索引

1641536382228

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

1641536644958

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

六、 倒排索引(Lucene索引底层)

简单说就是 按(文章关键字,对应的文档<0个或多个>)形式建立索引,根据关键字就可直接查询对应的文档(含关键字的),无需查询每一个文档,如下图

1641536698143

五、IK分词器(elasticsearch插件)

一、IK分词器:中文分词器

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

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

二、安装IK分词器(elasticsearch插件)

版本要与ElasticSearch版本对应
1、安装IK分词器(elasticsearch插件)

ik分词器下载地址: https://github.com/medcl/elasticsearch-analysis-ik

将下载的zip文件解压到D:\ElasticSearch\elasticsearch-7.16.2\plugins目录下

1641539267329

2、重启ElasticSearch,查看plugin里有了ik插件

1641539375369

3、elasticsearch-plugin list查看插件

在D:\ElasticSearch\elasticsearch-7.16.2\bin目录下输入cmd,输入elasticsearch-plugin list可以看到elasticsearch-analysis-ik-7.16.2

1641539589265

1641539694054

4、使用kibana测试

ik_smart最少切分

1641541396815

ik_max_word最细粒度划分) ----穷尽词库的可能

1641541548042

5、 大多数分词满足不了我们的想法,手动 将该词添加到分词器的词典当中

进行测试,输出不了“Jin之伤”词语

1641542668363

在此目录下打开IKAnalyzer.cfg.xml文件进行配置,自定义Jin.dic文件进行编写词语

1641543058719

1641543103116

1641543139599

六、RestFul风格

一种软件架构风格,而不是标准,只是提供了一组设计原则和约束条件。它主要用于客户端和服务器交互类的软件。基于这个风格设计的软件可以更简洁更有层次更易于实现缓存等机制。

一、基本Rest命令说明:

methodurl地址描述
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/索引名称/类型名称/文档id/_search查询所有数据

二、测试

1、(5601)创建一个索引,添加一个test1的索引
PUT /索引名/~类型名~/文档id
{
	请求体
}

1641546855754

2、(9100)查看索引数据

1641546921639

三、字段数据类型测试

  • 字符串类型

    • text、

      keyword

      • text:支持分词,全文检索,支持模糊、精确查询,不支持聚合,排序操作;text类型的最大支持的字符长度无限制,适合大字段存储;
      • keyword:不进行分词,直接索引、支持模糊、支持精确匹配,支持聚合、排序操作。keyword类型的最大支持的长度为——32766个UTF-8类型的字符,可以通过设置ignore_above指定自持字符长度,超过给定长度后的数据将不被索引,无法通过term精确匹配检索返回结果。
  • 数值型

    • long、Integer、short、byte、double、float、half floatscaled float
  • 日期类型

    • date
  • te布尔类型

    • boolean
  • 二进制类型

    • binary
  • 等等

1、指定字段的类型

(5601)创建一个索引,添加一个test2的索引

1641548086306

(9100)查看索引数据

1641548119867

(5601)获取test2索引库里的规则信息

1641548246403

2、 doc 默认类型(default type)
如果自己的文档字段没有被指定,那么ElasticSearch就会给我们默认配置字段类型

(5601)设置一个默认(_doc)的test3

1641548489799

(9100)查看索引数据

1641548553945

(5601)获取test3索引库里的信息

1641548664183

扩展:通过get _cat/ 可以获取ElasticSearch的当前的很多信息!

GET _cat/indices
GET _cat/aliases
GET _cat/allocation
GET _cat/count
GET _cat/fielddata
GET _cat/health
GET _cat/indices
GET _cat/master
GET _cat/nodeattrs
GET _cat/nodes
GET _cat/pending_tasks
GET _cat/plugins
GET _cat/recovery
GET _cat/repositories
GET _cat/segments
GET _cat/shards
GET _cat/snapshots
GET _cat/tasks
GET _cat/templates
GET _cat/thread_pool
3、修改

①旧的(使用put覆盖原来的值)

  • 版本+1(_version)
  • 但是如果漏掉某个字段没有写,那么更新是没有写的字段 ,会消失

开始

1641548489799

修改一次后

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-jE9zGAj6-1679745736698)(https://gitee.com/happy_sad/typora-image/raw/master/images/1641549183734.png)]

②新的(使用post的update)

  • version不会改变
  • 需要注意doc
  • 不会丢失字段

1641549937569

1641549974325

4、删除
通过DELETE命令实现删除、根据请求来判断删除索引还是删除文档记录。

1641550060476

1641550345572

1641550088532

七、关于文档的基本操作(重点)

一、基本操作

PUT /jin/user/1
{
  "name": "进",
  "age": 22,
  "desc": "活成个人!"
}
PUT /jin/user/2
{
  "name": "张三",
  "age": 15,
  "desc": "法外狂徒!"
}
PUT /jin/user/3
{
  "name": "李四",
  "age": 18,
  "desc": "李代桃僵"
}
GET /jin/user/2
PUT /jin/user/3
{
  "name": "李四233",
  "age": 18,
  "desc": "李代桃僵"
}
POST /jin/user/1/_update
{
  "doc":{
    "name": "Jin进56"
  }
}
GET /jin/user/_search?q=name:Jin进56
1、添加数据

(注:这里的jin必须为小写jin开头,大写Jin报错)

1641572690991

1641572501766

1641572711038

2、查询获取数据

1641572838051

3、更新/修改

老版本用

PUT /索引名/类型名/文档id
{
	属性:value,
	属性:修改的value
}

1641573054199

新版本用

POST /索引名/类型名/文档id/_uodate
{
	"doc":{
		属性:修改的value
	}
}

1641573261237

(9001)结果显示

1641573301889

4、简单的搜索
GET /索引名/类型名/_search?q=属性:value

1641573831870

二、复杂操作(select 排序、分页、高亮、模糊查询、精准查询)

1、查询匹配
  • match:匹配(会使用分词器解析(先分析文档,然后进行查询))
  • _source:过滤字段
  • sort:排序
  • formsize 分页
①先插入一个数据

1641713502933

match:匹配(会使用分词器解析(先分析文档,然后进行查询))
hit:
	索引和文档的信息
	查询的结果总数
	查询出来的具体文档信息
	便利数据中的信息
	分数越高权重越大

1641713663608

③**_source**:过滤字段(只查询填写的字段,其他的过滤掉)

1641714167446

sort:排序(asc、desc)

1641721580798

form、size 分页

1641721938967

1641721833407

2、多条件查询(bool)
  • must 相当于 and
  • should 相当于 or
  • must_not 相当于 not (... and ...)
  • filter 过滤
must: 相当于 and(多条件查询,所有的条件都需要符合)

1641722437380

should:相当于 or

1641722608469

must_not:相当于 not (... and ...)

1641722800274

filter: 过滤
gt :>
gte :>=
lt :<
lte :<=

1641723100967

3、匹配数组
  • 貌似不能与其它字段一起使用
  • 可以多关键字查(空格隔开)— 匹配字段也是符合的
  • **match **会使用分词器解析(先分析文档,然后进行查询)

1641723539384

4、精确查询
  • term 直接通过 倒排索引 指定词条查询
  • 适合查询 number、date、keyword ,不适合text
1、定义索引testdb和添加数据

1641731965388

1641732065532

1641732118543

2、analyzer为keyword和standard时的查询

analyzer:类型为keyword时被当成一个整体,没有被解析

1641732255732

analyzer:类型为standard时被ik分词器解析,可以看到被拆分了

1641732330589

analyzer:类型为ik_max_word时被ik分词器解析,可以看到被拆分了

1641733400937

3、type类型为text和keyword时的查询
  • text:
    • 支持分词全文检索、支持模糊、精确查询,不支持聚合,排序操作;
    • text类型的最大支持的字符长度无限制,适合大字段存储;
  • keyword:
    • 不进行分词直接索引、支持模糊、支持精确匹配,支持聚合、排序操作。
    • keyword类型的最大支持的长度为——32766个UTF-8类型的字符,可以通过设置ignore_above指定自持字符长度,超过给定长度后的数据将不被索引,无法通过term精确匹配检索返回结果

name的type被定义为text类型,可以查出多条**(text会被分词器解析)**

1641732629387

desc的type被定义为keyword类型,精确查询只能查出一条**(keyword不会被分词器解析,精确查询)**

1641732726096

4、term的精确查询

1641733167578

5、高亮查询

搜索的相关结果都可以高亮显示,标签默认问

1641734020936

自定义标签

1641734207852

八、SpringBoot集成ES

官网文档地址:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/index.html

1641801759015

一、查看官网文档

1、查看官方文档

1641776199124

1641776295345

1641776359357

1641776531894

2、找到原生的依赖
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.15.2</version>
</dependency>

1641776901090

3、dependencies

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-JYZMYuRy-1679745736712)(https://gitee.com/happy_sad/typora-image/raw/master/images/1641776998012.png)]

4、找对象,初始化

1641777127803

二、创建项目

一、创建项目
1、创建项目

1641777805792

2、确保导入的elasticsearch依赖与下载的elasticsearch版本包一致
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.Jin</groupId>
    <artifactId>springboot-elasticsearch-api</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-elasticsearch-api</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
        <elasticsearch.version>7.16.2</elasticsearch.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <!--<dependency>-->
        <!--<groupId>com.alibaba</groupId>-->
        <!--<artifactId>fastjson</artifactId>-->
        <!--<version>1.2.70</version>-->
        <!--</dependency>-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

1641778975778

3、编写ElasticSearchConfig.java
package com.jin.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticSearchConfig {
    @Bean
    public RestHighLevelClient restHighLevelClient(){
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("127.0.0.1", 9200, "http")));
        return client;
    }
}
二、创建索引
1、创建索引:编写测试方法testCreateIndexRequest,创建索引
package com.jin;

import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;

@SpringBootTest
class SpringbootElasticsearchApiApplicationTests {

    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient restHighLevelClient;

    @Test
    void contextLoads() {

    }

    //测试索引的创建 Request
    @Test
    void testCreateIndexRequest() throws IOException {
        //1、创建索引请求(索引名必须全部是小写)
        CreateIndexRequest request = new CreateIndexRequest("jin_index");
        //2、客户端执行请求CreateIndexResponse,请求后获得响应
        CreateIndexResponse createIndexResponse =
                restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
        System.out.println(createIndexResponse);
    }
}
2、执行结果

1641783634911

1641783649288

三、获取索引
1、获取索引:编写测试方法testExistIndex,测试索引是否存在
//测试获取索引 判断索引是否存在
@Test
void testExistIndex() throws IOException {
    GetIndexRequest request = new GetIndexRequest("jin_index");
    boolean exists = restHighLevelClient.indices().exists(request,RequestOptions.DEFAULT);
    System.out.println(exists);
}
2、执行结果

1641784303674

四、删除索引
1、删除索引:编写测试方法testDeleteIndex,测试删除索引
//测试删除索引
@Test
void testDeleteIndex() throws IOException {
    DeleteIndexRequest request = new DeleteIndexRequest("jin_index");
    AcknowledgedResponse delete = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
    System.out.println(delete.isAcknowledged());
}
2、测试结果

1641784933697

1641784988983

三、文档操作

一、前期操作
1、前期操作,删除多余索引库(余下默认)

1641792230096

2、还是执行之前的创建索引jin_index

1641792351485

1641792398748

二、导入alibaba的fastjson依赖
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.70</version>
</dependency>
三、编写实体类User.java
package com.jin.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;

@Component
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private String name;
    private int age;
}
四、添加文档
1、添加文档:编写添加文档的方法testAddDocument
//测试添加文档,put /jin_index/_doc/1
@Test
void testAddDocument() throws IOException {
    //创建对象
    User user = new User("Jin",22);
    //创建请求
    IndexRequest request = new IndexRequest("jin_index");
    //规则 put /jin_index/_doc/1
    request.id("1");
    request.timeout(TimeValue.timeValueSeconds(1));
    request.timeout("1s");
    //将数据放入请求
    request.source(JSON.toJSONString(user), XContentType.JSON);

    //客户端发送请求,获取响应的结果
    IndexResponse indexResponse = restHighLevelClient.index(request, RequestOptions.DEFAULT);
    System.out.println(indexResponse.toString());
    System.out.println(indexResponse.status());     //对应命令返回的
}
6、输出结果

1641793409921

1641793427656

五、获取文档
1、获取文档:编写获取文档的方法testIsExists
//获取文档,判断是否存在get /jin_index/_doc/1
@Test
void testIsExists() throws IOException {
    GetRequest getRequest = new GetRequest("jin_index", "1");
    //不获取返回的_source的上下文
    getRequest.fetchSourceContext(new FetchSourceContext(false));
    getRequest.storedFields("_none_");

    boolean exists = restHighLevelClient.exists(getRequest, RequestOptions.DEFAULT);
    System.out.println(exists);
}
2、输出结果

1641794234908

六、获取文档的信息
1、获取文档的信息:编写获取文档信息的方法testIsgetDocument
//获取文档的信息
@Test
void testGetDocument() throws IOException {
    GetRequest getRequest = new GetRequest("jin_index", "1");

    GetResponse getResponse = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
    System.out.println(getResponse.getSourceAsString());    //打印文档的内容
    System.out.println(getResponse);            //返回的全部内容和kabana命令式一样
}
2、输出结果

1641794522861

七、更新文档信息
1、更新文档信息:编写更新文档信息的方法testUpdateDocument
//更新文档信息
@Test
void testUpdateDocument() throws IOException {
    UpdateRequest updateRequest = new UpdateRequest("jin_index", "1");
    updateRequest.timeout("1s");
    User user = new User("Jin进", 18);
    updateRequest.doc(JSON.toJSONString(user),XContentType.JSON);
    UpdateResponse updateResponse = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
    System.out.println(updateResponse.status());
}
2、输出结果

1641795006000

1641795056861

八、删除文档信息
1、删除文档信息:编写删除文档信息的方法testDeleteDocument
//删除文档信息
@Test
void testDeleteDocument() throws IOException {
    DeleteRequest deleteRequest = new DeleteRequest("jin_index", "1");
    deleteRequest.timeout("1s");
    DeleteResponse deleteResponse = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
    System.out.println(deleteResponse.status());
}
2、输出结果

1641795670319

1641795764540

九、批量添加文档
1、批量添加文档:编写批量添加文档的方法testBulkRequest
//批量添加文档
@Test
void  testBulkRequest() throws IOException {
    BulkRequest bulkRequest = new BulkRequest();
    bulkRequest.timeout("10s");

    ArrayList<User> userList = new ArrayList<>();
    userList.add(new User("Jin1",21));
    userList.add(new User("Jin2",22));
    userList.add(new User("Jin3",23));
    userList.add(new User("Jin4",24));
    userList.add(new User("Jin5",25));
    userList.add(new User("Jin6",26));

    for (int i = 0; i < userList.size(); i++) {
        bulkRequest.add(
            new IndexRequest("jin_index")
            .id(""+(i+1))
            .source(JSON.toJSONString(userList.get(i)),XContentType.JSON));
        BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(bulkResponse.hasFailures());
    }
}
2、输出结果

1641796929970

1641797029879

十、批量删除文档
1、批量删除文档:编写批量删除文档的方法testBulkRequestDeleteRequest
//批量删除文档
@Test
void  testBulkRequestDeleteRequest() throws IOException {
    BulkRequest bulkRequest = new BulkRequest();
    bulkRequest.timeout("10s");

    for (int i = 0; i < 6; i++) {
        bulkRequest.add(
            new DeleteRequest("jin_index")
            .id(""+(i+1)));
        BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(bulkResponse.hasFailures());
    }
}
2、输出结果

1641797399862

十一、查询文档
1、查询文档:编写查询文档的方法testSearch

先添加一条文档数据(“Jin”, 22)

//查询文档
// SearchRequest 搜索请求
// SearchSourceBuilder 条件构造
// HighlightBuilder 高亮
// TermQueryBuilder 精确查询
// MatchAllQueryBuilder
// xxxQueryBuilder ...
@Test
public void testSearch() throws IOException {
    // 1.创建查询请求对象
    SearchRequest searchRequest = new SearchRequest("jin_index");
    // 2.构建搜索条件
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    // (1)查询条件 使用QueryBuilders工具类创建
    // 精确查询
    TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("age", 22);
    // 匹配查询
    //MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
    // 设置高亮
    searchSourceBuilder.highlighter(new HighlightBuilder());
    //分页
    //searchSourceBuilder.from();
    //searchSourceBuilder.size();
    searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
    //条件投入
    searchSourceBuilder.query(termQueryBuilder);
    // 3.添加条件到请求
    searchRequest.source(searchSourceBuilder);
    // 4.客户端查询请求
    SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
    // 5.查看返回结果
    SearchHits hits = searchResponse.getHits();
    System.out.println(JSON.toJSONString(hits));
    System.out.println("===========================");
    for (SearchHit documentFields : hits.getHits()) {
        System.out.println(documentFields.getSourceAsMap());
    }
}
2、输出结果

1641800169556

九、模仿京东

1641886201136

一、创建项目

1641823271365

1、创建项目

1641801955314

2、确保导入的elasticsearch依赖与下载的elasticsearch版本包一致
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.Jin</groupId>
    <artifactId>springboot-elasticsearch-jingdong</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-elasticsearch-jingdong</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
        <elasticsearch-version>7.16.2</elasticsearch-version>
    </properties>
    <dependencies>
        <!-- jsoup解析页面 -->
        <!-- 解析网页 爬视频可 研究tiko -->
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.10.2</version>
        </dependency>
        <!-- fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.70</version>
        </dependency>
        <!-- elasticsearch -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
        <!-- thymeleaf -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!-- web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- devtools -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <!--  -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- test -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
3、编写 application.preperties配置文件
# 更改端口,防止冲突
server.port=9090
# 关闭thymeleaf缓存
spring.thymeleaf.cache=false
4、导入前端文件

链接:https://pan.baidu.com/s/15mqnRdy5OVuBe9-dz4kg5w
提取码:3r7l

1641808386895

5、编写controller测试
package com.jin.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class IndexController {

    @GetMapping({"/","index"})
    public String index(){
        return "index";
    }
}

1641823308375

二、爬取数据

1641824703413

一、测试爬取数据
1、创建utils包,创建HtmlParseUtil.java类
package com.jin.utils;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

public class HtmlParseUtil {
    public static void main(String[] args) throws IOException {
        //1、获得请求(前提需要联网)  https://search.jd.com/Search?keyword=java
        String url="https://search.jd.com/Search?keyword=java";
        //2、解析网页(Jsoup返回的Document就是浏览器Document的对象)
        Document document = Jsoup.parse(new URL(url), 30000);
        Element element = document.getElementById("J_goodsList");
        System.out.println(element.text());     //获取爬取的数据
        System.out.println();
        System.out.println(element.html());     //获取爬取的html
    }
}
2、输出结果

1641824572221

二、简单爬取数据
1、获取标签、图片、价格、标题
package com.jin.utils;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

public class HtmlParseUtil {
    public static void main(String[] args) throws IOException {
        //1、获得请求(前提需要联网)  https://search.jd.com/Search?keyword=java
        String url="https://search.jd.com/Search?keyword=java";
        //2、解析网页(Jsoup返回的Document就是浏览器Document的对象)
        Document document = Jsoup.parse(new URL(url), 30000);
        //3、调用js里面的方法
        Element element = document.getElementById("J_goodsList");
        //        System.out.println(element.text());     //获取爬取的数据
        //        System.out.println();
        //        System.out.println(element.html());     //获取爬取的html
        //4、获取所有的li元素
        Elements elements = element.getElementsByTag("li");
        //5、获取元素里的内容,el为每一个li标签
        for (Element el : elements) {
            String img = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
            String price = el.getElementsByClass("p-price").eq(0).text();
            String title = el.getElementsByClass("p-name").eq(0).text();
            System.out.println("===================================");
            System.out.println(img);
            System.out.println(price);
            System.out.println(title);
        }
    }
}
2、输出结果

1641826535878

三、打包成工具类
1、编写pojo类
package com.jin.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Content {
    private String img;
    private String price;
    private String title;
}
2、编写utils的工具类HtmlParseUtil.java
package com.jin.utils;

import com.jin.pojo.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

@Component
public class HtmlParseUtil {
//    测试输出
//    public static void main(String[] args) throws IOException {
//        HtmlParseUtil htmlParseUtil = new HtmlParseUtil();
//        List<Content> list = htmlParseUtil.parseJD("vue");
//        list.forEach(System.out::println);
//    }

    public List<Content> parseJD(String keyword) throws IOException {
        //1、获得请求(前提需要联网)  https://search.jd.com/Search?keyword=java
        String url = "https://search.jd.com/Search?keyword="+keyword;
        //2、解析网页(Jsoup返回的Document就是浏览器Document的对象)
        Document document = Jsoup.parse(new URL(url), 30000);
        //3、调用js里面的方法
        Element element = document.getElementById("J_goodsList");
        //4、获取所有的li元素
        Elements elements = element.getElementsByTag("li");
        //5、封装list
        ArrayList<Content> goodsList = new ArrayList<>();
        //6、获取元素里的内容,el为每一个li标签
        for (Element el : elements) {
            String img = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
            String price = el.getElementsByClass("p-price").eq(0).text();
            String title = el.getElementsByClass("p-name").eq(0).text();
            Content content = new Content();
            content.setImg(img);
            content.setPrice(price);
            content.setTitle(title);
            goodsList.add(content);
        }
        return goodsList;
    }
}
3、输出结果

1641864186820

四、业务编写过程
1、(9100)创建jin_goods索引

1641865758397

1641865949215

1641865970059

2、创建config包,编写ElasticSearchConfig.java
package com.jin.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticSearchConfig {
    @Bean
    public RestHighLevelClient restHighLevelClient() {
        RestHighLevelClient client = new RestHighLevelClient(
            RestClient.builder(
                new HttpHost("127.0.0.1", 9200, "http")));
        return client;
    }
}
3、创建service包,编写ContentService.java
package com.jin.service;

import com.alibaba.fastjson.JSON;
import com.jin.pojo.Content;
import com.jin.utils.HtmlParseUtil;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

//编写业务类
@Service
public class ContentService {
    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient restHighLevelClient;

    //1、解析数据放入ElasticSearch中
    public Boolean parseContent(String keyword) throws IOException {
        List<Content> contents = new HtmlParseUtil().parseJD(keyword);
        //把查询到的数据放入ElasticSearch中
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("2m");
        for (int i = 0; i < contents.size(); i++) {
            bulkRequest.add(
                new IndexRequest("jin_goods")
                .source(JSON.toJSONString(contents.get(i)), XContentType.JSON)
            );
        }
        BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        return !bulkResponse.hasFailures();
    }

    //2、获取这些数据实现搜索功能
    public List<Map<String,Object>> searchPage(String keyword,int pageNo,int pageSize) throws IOException {
        if(pageNo<=1){
            pageNo=1;
        }
        //条件搜索
        SearchRequest searchRequest = new SearchRequest("jin_goods");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //分页
        searchSourceBuilder.from();
        searchSourceBuilder.size(pageSize);
        //精准匹配
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", keyword);
        searchSourceBuilder.query(termQueryBuilder);
        searchSourceBuilder.timeout(new TimeValue(60,TimeUnit.SECONDS));
        //执行搜索
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        //解析结果
        ArrayList<Map<String, Object>> list = new ArrayList<>();
        SearchHits searchHits = searchResponse.getHits();
        for (SearchHit searchHit : searchHits) {
            list.add(searchHit.getSourceAsMap());
        }
        return list;
    }
}
4、编写ContentController.java
package com.jin.controller;

import com.jin.service.ContentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@RestController
public class ContentController {
    @Autowired
    @Qualifier("contentService")
    private ContentService contentService;

    @RequestMapping(value = "/parseContent/{keyword}",method = {RequestMethod.GET,RequestMethod.POST})
    public Boolean parseContent(@PathVariable("keyword") String keyword) throws IOException {
        return contentService.parseContent(keyword);
    }

    @RequestMapping(value = "/searchPage/{keyword}/{pageNo}/{pageSize}",method = {RequestMethod.GET,RequestMethod.POST})
    public List<Map<String,Object>> searchPage(@PathVariable("keyword") String keyword,
                                               @PathVariable("pageNo") int pageNo,
                                               @PathVariable("pageSize") int pageSize) throws IOException {
        return contentService.searchPage(keyword,pageNo,pageSize);
    }
}
5、输出结果

1641868100060

1641866081845

1641868319998

五、将前后端交互
1、配置环境
在Node.js的目录下cmd命令通过镜像下载vue和axios:
npm install vue
npm install axios

1641869033149

下载的vue和axios保存在node_modules中

1641869146598

将vue.min.js和axios.min.js放在js文件夹里面

1641869278320

1641869309908

2、index.html代码
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

    <head>
        <meta charset="utf-8"/>
        <title>Jin-Java-ES仿京东实战</title>
        <link rel="stylesheet" th:href="@{/css/style.css}"/>
    </head>

    <body class="pg">
        <div class="page" id="app">
            <div id="mallPage" class=" mallist tmall- page-not-market ">

                <!-- 头部搜索 -->
                <div id="header" class=" header-list-app">
                    <div class="headerLayout">
                        <div class="headerCon ">
                            <!-- Logo-->
                            <h1 id="mallLogo">
                                <img th:src="@{/images/jdlogo.png}" alt="">
                            </h1>

                            <div class="header-extra">

                                <!--搜索-->
                                <div id="mallSearch" class="mall-search">
                                    <form name="searchTop" class="mallSearch-form clearfix">
                                        <fieldset>
                                            <legend>天猫搜索</legend>
                                            <div class="mallSearch-input clearfix">
                                                <div class="s-combobox" id="s-combobox-685">
                                                    <div class="s-combobox-input-wrap">
                                                        <input v-model="keyword" type="text" autocomplete="off" value="dd" id="mq"
                                                               class="s-combobox-input" aria-haspopup="true">
                                                    </div>
                                                </div>
                                                <button type="submit" @click.prevent="searchKey" id="searchbtn">搜索</button>
                                            </div>
                                        </fieldset>
                                    </form>
                                    <ul class="relKeyTop">
                                        <li><a>JinJava</a></li>
                                        <li><a>Jin前端</a></li>
                                        <li><a>JinLinux</a></li>
                                        <li><a>Jin大数据</a></li>
                                        <li><a>Jin聊理财</a></li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 商品详情页面 -->
                <div id="content">
                    <div class="main">
                        <!-- 品牌分类 -->
                        <form class="navAttrsForm">
                            <div class="attrs j_NavAttrs" style="display:block">
                                <div class="brandAttr j_nav_brand">
                                    <div class="j_Brand attr">
                                        <div class="attrKey">
                                            品牌
                                        </div>
                                        <div class="attrValues">
                                            <ul class="av-collapse row-2">
                                                <li><a href="#"> Jin </a></li>
                                                <li><a href="#"> Java </a></li>
                                            </ul>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </form>

                        <!-- 排序规则 -->
                        <div class="filter clearfix">
                            <a class="fSort fSort-cur">综合<i class="f-ico-arrow-d"></i></a>
                            <a class="fSort">人气<i class="f-ico-arrow-d"></i></a>
                            <a class="fSort">新品<i class="f-ico-arrow-d"></i></a>
                            <a class="fSort">销量<i class="f-ico-arrow-d"></i></a>
                            <a class="fSort">价格<i class="f-ico-triangle-mt"></i><i class="f-ico-triangle-mb"></i></a>
                        </div>

                        <!-- 商品详情 -->
                        <div class="view grid-nosku">

                            <div class="product" v-for="result in result">
                                <div class="product-iWrap">
                                    <!--商品封面-->
                                    <div class="productImg-wrap">
                                        <a class="productImg">
                                            <img :src="result.img">
                                        </a>
                                    </div>
                                    <!--价格-->
                                    <p class="productPrice">
                                        <em> {{result.price}} </em>
                                    </p>
                                    <!--标题-->
                                    <p class="productTitle">
                                        <a> {{result.title}} </a>
                                    </p>
                                    <!-- 店铺名 -->
                                    <div class="productShop">
                                        <span>店铺: JinJava </span>
                                    </div>
                                    <!-- 成交信息 -->
                                    <p class="productStatus">
                                        <span>月成交<em>999笔</em></span>
                                        <span>评价 <a>3</a></span>
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 前端使用Vue,实现前后端分离 -->
        <script th:src="@{/js/vue.min.js}"></script>
        <script th:src="@{/js/axios.min.js}"></script>
        <script>
            new Vue({
                el: '#app',
                data: {
                    keyword: '',    //搜索的关键字
                    result: []      //搜索的结果
                },
                methods: {
                    searchKey(){
                        var keyword = this.keyword;
                        console.log(keyword);
                        //对接后端的接口
                        axios.get('searchPage/'+keyword+"/1/10").then(response=>{
                            console.log(response);
                            this.result = response.data;    //绑定数据
                        })
                    }
                }
            })
        </script>

    </body>
</html>
3、输出结果

1641871628653

1641871679315

六、将关键字高亮
1、service包中的ContentService.java增添方法searchPageHighlightBuilder
package com.jin.service;

import com.alibaba.fastjson.JSON;
import com.jin.pojo.Content;
import com.jin.utils.HtmlParseUtil;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

//编写业务类
@Service
public class ContentService {
    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient restHighLevelClient;

    //1、解析数据放入ElasticSearch中
    public Boolean parseContent(String keyword) throws IOException {
        List<Content> contents = new HtmlParseUtil().parseJD(keyword);
        //把查询到的数据放入ElasticSearch中
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("2m");
        for (int i = 0; i < contents.size(); i++) {
            bulkRequest.add(
                new IndexRequest("jin_goods")
                .source(JSON.toJSONString(contents.get(i)), XContentType.JSON)
            );
        }
        BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        return !bulkResponse.hasFailures();
    }

    //2、获取这些数据实现搜索功能
    public List<Map<String,Object>> searchPage(String keyword,int pageNo,int pageSize) throws IOException {
        if(pageNo<=1){
            pageNo=1;
        }
        //条件搜索
        SearchRequest searchRequest = new SearchRequest("jin_goods");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //分页
        searchSourceBuilder.from();
        searchSourceBuilder.size(pageSize);
        //精准匹配
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", keyword);
        searchSourceBuilder.query(termQueryBuilder);
        searchSourceBuilder.timeout(new TimeValue(60,TimeUnit.SECONDS));
        //执行搜索
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        //解析结果
        ArrayList<Map<String, Object>> list = new ArrayList<>();
        SearchHits searchHits = searchResponse.getHits();
        for (SearchHit searchHit : searchHits) {
            list.add(searchHit.getSourceAsMap());
        }
        return list;
    }

    //3、获取这些数据实现搜索并进行高亮功能
    public List<Map<String,Object>> searchPageHighlightBuilder(String keyword,int pageNo,int pageSize) throws IOException {
        if(pageNo<=1){
            pageNo=1;
        }
        //条件搜索
        SearchRequest searchRequest = new SearchRequest("jin_goods");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //分页
        searchSourceBuilder.from();
        searchSourceBuilder.size(pageSize);
        //精准匹配
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", keyword);
        searchSourceBuilder.query(termQueryBuilder);
        searchSourceBuilder.timeout(new TimeValue(60,TimeUnit.SECONDS));
        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.requireFieldMatch(false);  //关闭多个高亮显示
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        searchSourceBuilder.highlighter(highlightBuilder);
        //执行搜索
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        //解析结果
        ArrayList<Map<String, Object>> list = new ArrayList<>();
        SearchHits searchHits = searchResponse.getHits();
        for (SearchHit searchHit : searchHits) {
            //解析高亮的字段
            Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
            HighlightField title = highlightFields.get("title");
            Map<String, Object> sourceAsMap = searchHit.getSourceAsMap();
            if(title!=null){
                Text[] fragments = title.fragments();
                String n_title="";
                for (Text fragment : fragments) {
                    n_title += fragment;
                }
                sourceAsMap.put("title",n_title);
            }
            list.add(sourceAsMap);
        }
        return list;
    }
}
2、controller包中的ContentController.java增添方法
package com.jin.controller;

import com.jin.service.ContentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@RestController
public class ContentController {
    @Autowired
    @Qualifier("contentService")
    private ContentService contentService;

    @RequestMapping(value = "/parseContent/{keyword}",method = {RequestMethod.GET,RequestMethod.POST})
    public Boolean parseContent(@PathVariable("keyword") String keyword) throws IOException {
        return contentService.parseContent(keyword);
    }

    @RequestMapping(value = "/searchPage/{keyword}/{pageNo}/{pageSize}",method = {RequestMethod.GET,RequestMethod.POST})
    public List<Map<String,Object>> searchPage(@PathVariable("keyword") String keyword,
                                               @PathVariable("pageNo") int pageNo,
                                               @PathVariable("pageSize") int pageSize) throws IOException {
        return contentService.searchPage(keyword,pageNo,pageSize);
    }

    @RequestMapping(value = "/searchPageHighlightBuilder/{keyword}/{pageNo}/{pageSize}",method = {RequestMethod.GET,RequestMethod.POST})
    public List<Map<String,Object>> searchPageHighlightBuilder(@PathVariable("keyword") String keyword,
                                                               @PathVariable("pageNo") int pageNo,
                                                               @PathVariable("pageSize") int pageSize) throws IOException {
        return contentService.searchPageHighlightBuilder(keyword,pageNo,pageSize);
    }
}
3、修改前端index.html

1641885352756

1641885369274

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

    <head>
        <meta charset="utf-8"/>
        <title>Jin-Java-ES仿京东实战</title>
        <link rel="stylesheet" th:href="@{/css/style.css}"/>
    </head>

    <body class="pg">
        <div class="page" id="app">
            <div id="mallPage" class=" mallist tmall- page-not-market ">

                <!-- 头部搜索 -->
                <div id="header" class=" header-list-app">
                    <div class="headerLayout">
                        <div class="headerCon ">
                            <!-- Logo-->
                            <h1 id="mallLogo">
                                <img th:src="@{/images/jdlogo.png}" alt="">
                            </h1>

                            <div class="header-extra">

                                <!--搜索-->
                                <div id="mallSearch" class="mall-search">
                                    <form name="searchTop" class="mallSearch-form clearfix">
                                        <fieldset>
                                            <legend>天猫搜索</legend>
                                            <div class="mallSearch-input clearfix">
                                                <div class="s-combobox" id="s-combobox-685">
                                                    <div class="s-combobox-input-wrap">
                                                        <input v-model="keyword" type="text" autocomplete="off" value="dd" id="mq"
                                                               class="s-combobox-input" aria-haspopup="true">
                                                    </div>
                                                </div>
                                                <button type="submit" @click.prevent="searchKey" id="searchbtn">搜索</button>
                                            </div>
                                        </fieldset>
                                    </form>
                                    <ul class="relKeyTop">
                                        <li><a>JinJava</a></li>
                                        <li><a>Jin前端</a></li>
                                        <li><a>JinLinux</a></li>
                                        <li><a>Jin大数据</a></li>
                                        <li><a>Jin聊理财</a></li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 商品详情页面 -->
                <div id="content">
                    <div class="main">
                        <!-- 品牌分类 -->
                        <form class="navAttrsForm">
                            <div class="attrs j_NavAttrs" style="display:block">
                                <div class="brandAttr j_nav_brand">
                                    <div class="j_Brand attr">
                                        <div class="attrKey">
                                            品牌
                                        </div>
                                        <div class="attrValues">
                                            <ul class="av-collapse row-2">
                                                <li><a href="#"> Jin </a></li>
                                                <li><a href="#"> Java </a></li>
                                            </ul>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </form>

                        <!-- 排序规则 -->
                        <div class="filter clearfix">
                            <a class="fSort fSort-cur">综合<i class="f-ico-arrow-d"></i></a>
                            <a class="fSort">人气<i class="f-ico-arrow-d"></i></a>
                            <a class="fSort">新品<i class="f-ico-arrow-d"></i></a>
                            <a class="fSort">销量<i class="f-ico-arrow-d"></i></a>
                            <a class="fSort">价格<i class="f-ico-triangle-mt"></i><i class="f-ico-triangle-mb"></i></a>
                        </div>

                        <!-- 商品详情 -->
                        <div class="view grid-nosku">

                            <div class="product" v-for="result in result">
                                <div class="product-iWrap">
                                    <!--商品封面-->
                                    <div class="productImg-wrap">
                                        <a class="productImg">
                                            <img :src="result.img">
                                        </a>
                                    </div>
                                    <!--价格-->
                                    <p class="productPrice">
                                        <em> {{result.price}} </em>
                                    </p>
                                    <!--标题-->
                                    <p class="productTitle">
                                        <a v-html="result.title"></a>
                                    </p>
                                    <!-- 店铺名 -->
                                    <div class="productShop">
                                        <span>店铺: JinJava </span>
                                    </div>
                                    <!-- 成交信息 -->
                                    <p class="productStatus">
                                        <span>月成交<em>999笔</em></span>
                                        <span>评价 <a>3</a></span>
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 前端使用Vue,实现前后端分离 -->
        <script th:src="@{/js/vue.min.js}"></script>
        <script th:src="@{/js/axios.min.js}"></script>
        <script>
            new Vue({
                el: '#app',
                data: {
                    keyword: '',    //搜索的关键字
                    result: []      //搜索的结果
                },
                methods: {
                    searchKey(){
                        var keyword = this.keyword;
                        console.log(keyword);
                        //对接后端的接口
                        // axios.get('searchPage/'+keyword+"/1/10").then(response=>{
                        //     console.log(response);
                        //     this.result = response.data;    //绑定数据
                        // })
                        axios.get('searchPageHighlightBuilder/'+keyword+"/1/10").then(response=>{
                            console.log(response);
                            this.result = response.data;    //绑定数据
                        })
                    }
                }
            })
        </script>

    </body>
</html>
4、输出结果

1641885814450

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jin-进

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值