ElasticSearch7.6.1学习笔记-狂神

2023-02-12,,,

ElasticSearch:7.6.1

https://gitee.com/yujie.louis/elastic-search 笔记,代码,安装包等

什么是ElasticSearch?

Elasticsearch是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。Elasticsearch是用Java语言开发的,并作为Apache许可条款下的开放源码发布,是一种流行的企业级搜索引擎。Elasticsearch用于云计算中,能够达到实时搜索,稳定,可靠,快速,安装使用方便。官方客户端在Java、.NET(C#)、PHP、Python、Apache Groovy、Ruby和许多其他语言中都是可用的。根据DB-Engines的排名显示,Elasticsearch是最受欢迎的企业搜索引擎,其次是Apache Solr,也是基于Lucene。

ElasticSearch能干什么:搜索

先聊一个人Doug Cutting

Doug Cutting 是一位美国工程师,迷上了搜错引擎。他做了一个用于文本搜索的函数库,命名为Lucene. Lucene 是用java写的,目标是为各种中小型应用软件加入全文搜索功能。Lucene是一套信息检索工具包,并不包含搜索引擎系统,它包含了索引结构、读写索引工具、相关性工具、排序等功能。因此在使用Lucenen时仍需关注搜索引擎系统,例如数据获取、解析、分词等方面的东西。

该项目早期被发布在Doug Cutting的个人网站,后来成为了Apache软件基金会jakarta项目的一个子项目。后来在Lucene的基础上开发了一款可以代替当时的主流搜索的开源搜索引擎,命名为Nutch.

Nutch 是一个建立在Lucene核心之上的网页搜索应用程序,它在Lucene的基础上加了爬虫和一些网页相关的功能,目的就是从一个简单的站内检索推广到全球网络上的搜索上。

随着时间的推移,作为互联网搜索引擎,都面临对象“体积”不断增大的问题需要存储大量的网页,并不断优化自己的搜索算法,提升搜索效率。

在2004年,Doug Cutting实现了分布式文件存储系统,并将它命名为NDFS(Nutch Distributed File System)。后来他加入了雅虎,将NDFS和MapReduce进行了改造,并重新命名为Hadoop(NDFS也改名为HDFS,Hadoop Distributed File System). 这就是大名鼎鼎的大数据框架系统--Hadoop的由来,而Doug Cutting则被人称为Hadoop之父。

ElasticSearch概述

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

谁在使用

维基百科,类似百度百科,全文检索,高亮,搜索推荐
国外新闻网站,类似搜狐新闻,用户行为日志(点击,浏览,收藏,评论)+社交网络数据,数据分析。。。
Stack Overflow国外的程序异常讨论论坛
GitHub(开源代码管理),搜索上千亿行代码
电商网站,检索商品
日志数据分析,logstash采集日志,ES进行复杂的数据分析,ELK技术(elasticsearch+logstash+kibana)
商品价格监控网站
商业智能系统
站内搜索

ES和solr的差别

ElasticSearch简介

ElasticSearch是一个实施分布式搜索分析引擎。它让你以前所未有的速度处理大数据成为可能。它用于全文搜索、结构化搜索、分析以及将这三者混合使用:

维基百科使用es提供全文搜索并高亮关键字,以及输入实施搜索和搜索纠错等搜索建议功能;英国公报使用es结合用户日志和社交网络数据提供给他们的编辑以实施的反馈,以便了解龚总对新发表的文章的回应。。。

es是一个基于Apache Lucene(TM)的开源搜索引擎。无论在开源还是专有领域,Lucene可以被认为是迄今为止最先进、性能最好、功能最全的搜索引擎库。想要使用它,必须使用java来作为开发语言并将其直接继承到你的应用中。

solr简介

Solr是Apache下的一个顶级开源项目,采用java开发,是基于Lucene的全文搜索服务器。Solr提供了比Lucene更为丰富的查询语言,同时实现了可配置、可扩展、并对索引、搜索性能进行了优化。可以独立运行,是一个独立的企业及搜索应用服务器,它对外提供类似于web-service的API接口。用户可以通过http请求,像搜索引擎服务器提交一定格式的文件,生成索引;也可以通过提出查找请求,并得到返回结果。

两者比较

当单纯的对已有数据进行搜索时,Solr更快
实时建立索引是,Solr会产生io阻塞,查询性能较差,ElasticSearch具有明显的优势
随着数据量的增加,Solr的搜索效率会变得更低,而Elasticsearch却没有明显的变化

总结

    es基本是开箱即用,非常简单。而solr会有点复杂。
    Solr利用Zookeeper进行分布式管理,而elasticsearch自身带有分布式协调管理功能
    solr支持更多格式的数据,比如json xml csv。而es只支持json文件格式
    solr官方提供的功能更多,而elasticsearch更注重核心功能,高级功能由第三方插件提供
    solr查询快,但更新索引时慢,用于电商等查询多的应用
    es建立索引宽,即实时性查询快,用于facebook新浪等搜索
    solr较成熟,有一个更大,更成熟的用户、开发和贡献者社区,而elasticsearch相对开发维护者较少,更新太快,学习使用成本较高

安装ElasticSearch之前必须保证JDK1.8+安装完毕,并正确的配置好JDK环境变量,否则启动ElasticSearch失败。

运行bat文件:在浏览器输入:127.0.0.1:9200

第二部配置es的配置yml文件:开启跨域

#配置开启跨域支持
http.cors.enabled: true
http.cors.allow-origin: "*"

下载可视化工具:elasticsearch-head-master

启动可视化header:他是前端项目

npm install || cnpm install

npm run start

访问:http://localhost:9100/

把索引当做数据:

了解ELK

ELK是ElasticSearch 、 Logstash、Kibana三大开源框架首字母大写简称。市面上也称为Elastic Stack。Lostash是ELK的中央数据流,用于从不同目标(文件/数据存储/MQ)收集不同格式数据,经过过滤后支持输出到不同目的地。Kibana可以将elastic的数据通过友好的页面展示出来,提供实时分析的功能

市面上很多开发只要提到ELK能够一直说出它是一个日志分析架构技术栈总称,但实际上ELK不仅仅适用于日志分析,它还可以支持其他任何数据分析和手机的场景,日志分析和收集知识更具有代表性。并非唯一性。

安装Kibana

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

Kibana

配置汉化:i18n.locale: "zh-CN"

核心:索引、字段类型(mapping)、文档(document)

ElasticSearch是面向文档型的数据库,一条数据在这里就是一个文档。比如:

{
"name" : "John",
"sex" : "Male",
"age" : 25,
"birthDate": "1990/05/01",
"about" : "I love to go rock climbing",
"interests": [ "sports", "music" ]
}

es是面向文档的,一切都是json,和关系型数据库对比

relationDB es
数据库 索引
types(慢慢会被弃用)
documents
字段 fields

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

物理设计:

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

逻辑设计:

一个索引类型,包含多个文档,当我们索引一篇文档时,可以通过这样的顺序找到他: 索引-》类型-》文档id(该id实际是个字符串),通过这个组合我们就能索引到某个具体的文档。

文档

es是面向文档的,意味着索引和搜索数据的最小单位是文档,es中,文档有几个重要的属性:

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

尽管我们可以随意的添加或忽略某个字段,但是,每个字段的类型非常重要。因为es会保存字段和类型之间的映射以及其他的设置。这种映射具体到每个映射的每种类型,这也是为什么在es中,类型有时候也称为映射类型。

类型

类型是文档的逻辑容器,就像关系型数据库一样,表格是行的容器。类型中对于字段的定义称为映射,比如name映射为string类型.我们说文档是无模式的,他们不需要拥有映射中所定义的所有字段,当新增加一个字段时,es会自动的将新字段加入映射,但是这个字段不确定他是什么类型,所以最安全的方式是提前定义好所需要的映射。

索引

索引是映射类型的容器,es的索引是一个非常大的集合。索引寻出了映射类型的字段和其他设置。然后他们被存储到了各个分片上。

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

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

倒排索引

elasticsearch使用的是一种称为倒排索引 |的结构,采用Lucene倒排索作为底层。这种结构适用于快速的全文搜索,一个索引由文

档中所有不重复的列表构成,对于每一个词,都有一个包含它的文档列表。 例如,现在有两个文档,每个文档包含如下内容:

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

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

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

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

elasticsearch的索引和Lucene的索引对比

在elasticsearch中,索引(库)这个词被频繁使用,这就是术语的使用。在elasticsearch中 ,索引被分为多个分片,每份分片是-个Lucene的索引。所以一个elasticsearch索引是由多 个Lucene索引组成的。别问为什么,谁让elasticsearch使用Lucene作为底层呢!如无特指,说起索引都是指elasticsearch的索引。

接下来的一切操作都在kibana中Dev Tools下的Console里完成。基础操作!

ik分词器

什么是IK分词器 ?

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

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

IK提供了两个分词算法: ik_ smart和ik_ max_ word ,其中ik_ smart为最少切分, ik_ max_ _word为最细粒度划分!一会我们测试!

什么是IK分词器:

把一句话分词

如果使用中文:推荐IK分词器

两个分词算法:ik_smart(最少切分),ik_max_word(最细粒度划分)

3、命令模式的使用

3.1 Rest风格说明

一种软件架构风格,而不是标准。更易于实现缓存等机制

ik_smart(最少切分):拆分为不重复的词

GET _analyze
{
"analyzer": "ik_smart", //ik_smart(最少切分
"text": "中国人郭童"
} GET _analyze
{
"analyzer": "ik_max_word", //ik_max_word(最细粒度划分)
"text": "中国人郭童"
}

{

"tokens" : [

{

"token" : "中国人",

"start_offset" : 0,

"end_offset" : 3,

"type" : "CN_WORD",

"position" : 0

},

{

"token" : "中国",

"start_offset" : 0,

"end_offset" : 2,

"type" : "CN_WORD",

"position" : 1

},

{

"token" : "国人",

"start_offset" : 1,

"end_offset" : 3,

"type" : "CN_WORD",

"position" : 2

},

{

"token" : "郭",

"start_offset" : 3,

"end_offset" : 4,

"type" : "CN_CHAR",

"position" : 3

},

{

"token" : "童",

"start_offset" : 4,

"end_offset" : 5,

"type" : "CN_CHAR",

"position" : 4

}

]

}

如何把自定义的词加入ik分词器的字典中:

重启再看:

RestFul

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 查询所有的数据

PUT命令

# 创建索引
PUT /text1/type1/1
{
"name":"郭童",
"age":23
}
# PUT是插入命令,/索引名/类型/文档ID
#{请求体}

在header可视化界面查看执行结果:http://localhost:9100/

索引就是类似看做是数据库,put建立的请求实体就是创建的表及表初始数据

创建索引规则类型:

# 创建索引
PUT /text2
{
"mappings": {
"properties": {
"name":{
"type": "text"
},"age":{
"type": "integer"
},"birthday":{
"type": "date"
}
}
}
}

获得规则

get test2

默认自动分配字段类型:_doc

#查看默认信息
PUT /text1/_doc/1
{
"name":"郭童",
"age":23,
"birth":"2020-11-02"
}

获取默认信息:get _cat /

修改{PUT覆盖||update}

POST /text1/_doc/1/_update
{
"doc":{
"name":"郭童123"
}
}

删除(Delete)

#删除
DELETE text2
DELETE /text1/_doc/1

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

基本操作

#添加数据
PUT /text1/_doc/3
{
"name":"狂神123",
"age":123
}
#获取指定数据
GET /text1/_doc/2 #修改 其他操作会全部覆盖,未涉及置空
PUT /text1/_doc/3
{
"name":"狂神",
"age":123
}
#查询简单
GET /text1/_doc/3 #推荐修改 POST 配套:_update :只修改选择的部分,不会置空
POST /text1/_doc/3/_update
{
"name":"狂神说Java",
"age":123
}

搜索

1.通过ID查询 :GET /text1/_doc/2

2.简单的条件查询:

#插入一条数据:注意这里的type不要用默认的_doc,否则搜不出来

PUT /guotong/user/3
{
"name":"狂神",
"age":123
} #等值匹配简写: GET /guotong/user/_search?q=age:123

复杂查询,排序,分页,高亮,模糊

查询出多条结果《Score》就是匹配度,匹配度更高则权重更高!

#原始查询的语法 GET  、 _search  、  query  、match
GET /guotong/user/_search
{
"query": {
"match": {
"name": "郭童"
}
}
}

查询指定记录字段:_source 查询指定字段(过滤全部字段)
GET /guotong/user/_search
{
"query": {
"match": {
"name": "Python"
}
},
"_source": ["name"]
}
**查询排序:sort **
GET /guotong/user/_search
{
"query": {
"match": {
"name": "Python"
}
},
"sort":{
"age":{
"order":"desc"(降序) || "asc"(升序)
}
} }
查询分页:from(第几个数据开始)||size(返回数据数量)
GET /guotong/user/_search
{
"query": {
"match": {
"name": "Python"
}
},
"sort":{
"age":{
"order":"asc"
}
},"from": 0,"size": 1 }
Boolean值多条件精确查询 -must等价于and
	GET /guotong/user/_search
{
"query": {
"bool": {
"must":[
{
"match": {
"name": "Python"
}
},{
"match": {
"age": 23
}
}
]
}
}
}
=======================or====================should
GET /guotong/user/_search
{
"query": {
"bool": {
"should":[
。。。。。。。。。
]
}
}
}
======================(must_not)不等于==============================
GET /guotong/user/_search
{
"query": {
"bool": {
"must_not":[
。。。。。。
]
}
}
}

===========================过滤条件(filter)===============================
GET /guotong/user/_search
{
"query": {
"bool": {
"must":[
{
"match": {
"name": "Python"
}
}
],
"filter": { #过滤
"range": {
"age": {
"gte": 123, #大于等于
"lte": 320 #小于
}
}
}
}
}
}

匹配多个条件
#使用空格隔开
GET /guotong/user/_search
{
"query": {
"match": {
"name": "Python java"
}
}
}

精确自定义查询(倒排索引指定的词条进行精确查找)term

两个类型:
text 可以被分词器解析。
keyword 不会被分词器解析
GET /guotong/_search
{
"query": {
"term": {
"age":123
}
}
}
==========================多条件=============================
GET /guotong/_search
{
"query": {
"bool": {
"should": [
{
"term": {
"age": {
"value": "123"
}
}
},
{
"term": {
"age": {
"value": "23"
}
}
}
]
}
}
}
高亮查询highlight
GET /guotong/user/_search
{
"query": {
"match": {
"name": "郭童"
}
},"highlight": {
"fields": {
"name":{}
}
}
}
+++++++++++++++++++++++++++++++++==自定义高亮++++++++++++++++++++++
GET /guotong/user/_search
{
"query": {
"match": {
"name": "郭童"
}
},"highlight": {
"pre_tags": "<p class='key' style='color:red'>",
"post_tags": "</p>",
"fields": {
"name":{}
}
}
}

Springboot集成

<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.15.1</version>
</dependency>
Maven准备
<?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.2.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.gton</groupId>
<artifactId>elastic</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>elastic</name>
<description>Demo project for Spring Boot ElasticSearch</description>
<properties>
<java.version>1.8</java.version>
<!--elasticsearch自定义版本依赖和本地一致-->
<elasticsearch.version>7.6.1</elasticsearch.version>
</properties>
<dependencies>
<!--elasticsearch-->
<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>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>
</plugin>
</plugins>
</build> </project>
构建ElasticSearch请求连接执行对象
@Configuration
public class ElasticsearchConfig { //ELK
@Bean
public RestHighLevelClient restHighLevelClient() {
return new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 9200, "http"),
new HttpHost("localhost", 9201, "http")));
}
}
测试索引的创建
package com.gton.elastic;

import java.io.IOException;

/**
* Description: ElasticSearch JavaSpringBoot API 测试
*/
@SpringBootTest
class ElasticApplicationTests {
@Autowired
@Qualifier("restHighLevelClient")
private RestHighLevelClient elasticClient; //创建索引
@Test
void createIndexByElasticSearch() throws IOException {
//1.创建索引的请求
CreateIndexRequest indexRequest = new CreateIndexRequest("springboot_index");
//2.执行索引的请求
CreateIndexResponse createIndexResponse = elasticClient.indices().
create(indexRequest, RequestOptions.DEFAULT);
//3.获取索引创建请求的响应
System.out.println(createIndexResponse); //4.获取索引请求
GetIndexRequest getIndexRequest = new GetIndexRequest("springboot_index");
//5.执行获取索引请求:判断是否存在
boolean exists = elasticClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
System.out.println(exists);
elasticClient.close();
} }

文档操作
/**
* Description: ElasticSearch JavaSpringBoot API 测试
*/
@SpringBootTest
class ElasticApplicationTests {
@Autowired
@Qualifier("restHighLevelClient")
private RestHighLevelClient elasticClient; //jackson
private ObjectMapper mapper = new ObjectMapper(); //创建索引
@Test
void createIndexByElasticSearch() throws IOException {
//1.创建索引的请求
CreateIndexRequest indexRequest = new CreateIndexRequest("springboot_index");
//2.执行索引的请求
CreateIndexResponse createIndexResponse = elasticClient.indices().
create(indexRequest, RequestOptions.DEFAULT);
//3.获取索引创建请求的响应
System.out.println(createIndexResponse); //4.获取索引(好比数据库)请求
GetIndexRequest getIndexRequest = new GetIndexRequest("springboot_index");
//5.执行获取索引请求:判断是否存在
boolean exists = elasticClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
System.out.println(exists); //6.删除索引请求
DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("springboot_index");
//7.执行索引删除
AcknowledgedResponse delete = elasticClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
System.out.println(delete.isAcknowledged()); elasticClient.close();
} //测试文档操作
@SneakyThrows
@Test
void documentCreateByElasticSearch() throws JsonProcessingException {
//1.创建文档存储对象
User user = new User("郭童", 23); //2.创建请求
IndexRequest indexRequest = new IndexRequest("springboot_index"); //3.设置规则
indexRequest.id("1");
indexRequest.timeout(TimeValue.timeValueSeconds(1));
indexRequest.timeout("1s"); //4.将我们的数据放入请求中,使用json格式
indexRequest.source(mapper.writeValueAsString(user), XContentType.JSON); //5.客户端发送请求
IndexResponse response = elasticClient.index(indexRequest, RequestOptions.DEFAULT);
System.out.println(response.status());
System.out.println(response.toString()); //6.获取文档是否存在请求
GetRequest getRequest = new GetRequest("springboot_index", "1");
//6.1不回去返回的上下文了
getRequest.fetchSourceContext(new FetchSourceContext(false));
getRequest.storedFields("_none_");
//6.2判断文档是否存在
boolean exists = elasticClient.exists(getRequest, RequestOptions.DEFAULT);
if (exists) {
//7.获取文档信息
GetResponse documentFields = elasticClient.get(getRequest, RequestOptions.DEFAULT);
System.out.println(documentFields.getSourceAsString());
System.out.println(documentFields);
}
//8.更新文档信息请求
UpdateRequest updateRequest = new UpdateRequest("springboot_index", "1");
indexRequest.timeout("1s");
//8.1更新内容
User user1 = new User("狂神", 18);
//8.2json数据封装进去
updateRequest.doc(mapper.writeValueAsString(user1), XContentType.JSON);
//8.3执行更新操作
UpdateResponse updateResponse = elasticClient.update(updateRequest, RequestOptions.DEFAULT);
System.out.println(updateResponse.status()); //9.删除请求
DeleteRequest deleteRequest = new DeleteRequest("springboot_index", "1");
deleteRequest.timeout("1s");
//9.1执行
DeleteResponse deleteResp = elasticClient.delete(deleteRequest, RequestOptions.DEFAULT);
System.out.println(deleteResp); //10.批量插入
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.timeout("10s"); //10.1构造用户数据,批处理
for (int i = 2; i < 10; i++) {
bulkRequest.add(new IndexRequest("springboot_index").
id(String.valueOf(i)).
source(mapper.writeValueAsString(new User("gtooo" + i, i * i)),
XContentType.JSON));
}
//批量执行
BulkResponse bulkItemResponses = elasticClient.bulk(bulkRequest, RequestOptions.DEFAULT);
//是否失败
System.out.println(bulkItemResponses.hasFailures()); elasticClient.close(); } //查询
@Test
public void selectByElasticSearch() throws IOException {
System.out.println("---");
//搜索请求
SearchRequest searchRequest = new SearchRequest("springboot_index");
//条件构建搜索资源条件器
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//构建查询构建器
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("age", "23");
//装入搜索资源条件器
sourceBuilder.query(termQueryBuilder); //设置时间
sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
//分页
sourceBuilder.from(0);
sourceBuilder.size(10);
//高亮
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.field("username");
sourceBuilder.highlighter(highlightBuilder);
//插入请求体
searchRequest.source(sourceBuilder);
//执行查询
SearchResponse search = elasticClient.search(searchRequest, RequestOptions.DEFAULT);
//返回结果
SearchHits hits = search.getHits();
hits.forEach(System.out::println);
} }

ElasticSearch7.6.1学习笔记-狂神的相关教程结束。

《ElasticSearch7.6.1学习笔记-狂神.doc》

下载本文的Word格式文档,以方便收藏与打印。