当前位置: 代码网 > it编程>数据库>Nosql > 【微服务】分布式搜索引擎elasticsearch(1)

【微服务】分布式搜索引擎elasticsearch(1)

2024年08月02日 Nosql 我要评论
了解ES,倒排索引,文档和字段,索引和映射,索引库操作,文档操作,RestAPI,RestClient操作文档

1.elasticsearch

1.1.了解es

1.1.1.elasticsearch的作用

elasticsearch是一款非常强大的开源搜索引擎,具备非常多强大功能,可以帮助我们从海量数据中快速找到需要的内容

例如:

  • 在github搜索代码

  • 在电商网站搜索商品

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-da0xv131-1674697171603)(assets/image-20210720193633483.png)]

  • 在百度搜索答案

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-jgjndase-1674697171603)(assets/image-20210720193641907.png)]

1.1.2.elk技术栈

elasticsearch结合kibana、logstash、beats,也就是elastic stack(elk)。被广泛应用在日志数据分析、实时监控等领域:

在这里插入图片描述

而elasticsearch是elastic stack的核心,负责存储、搜索、分析数据。

在这里插入图片描述

1.1.3.elasticsearch和lucene

elasticsearch底层是基于lucene来实现的。

lucene是一个java语言的搜索引擎类库,是apache公司的顶级项目,由dougcutting于1999年研发。官网地址:https://lucene.apache.org/ 。

在这里插入图片描述

elasticsearch的发展历史:

  • 2004年shay banon基于lucene开发了compass
  • 2010年shay banon 重写了compass,取名为elasticsearch。

在这里插入图片描述

1.1.4.为什么不是其他搜索技术?

目前比较知名的搜索引擎技术排名:

在这里插入图片描述

虽然在早期,apache solr是最主要的搜索引擎技术,但随着发展elasticsearch已经渐渐超越了solr,独占鳌头:

在这里插入图片描述

1.1.5.总结

什么是elasticsearch?

  • 一个开源的分布式搜索引擎,可以用来实现搜索、日志统计、分析、系统监控等功能

什么是elastic stack(elk)?

  • 是以elasticsearch为核心的技术栈,包括beats、logstash、kibana、elasticsearch

什么是lucene?

  • 是apache的开源搜索引擎类库,提供了搜索引擎的核心api

1.2.倒排索引

倒排索引的概念是基于mysql这样的正向索引而言的。

1.2.1.正向索引

那么什么是正向索引呢?例如给下表(tb_goods)中的id创建索引:

在这里插入图片描述

如果是根据id查询,那么直接走索引,查询速度非常快。

但如果是基于title做模糊查询,只能是逐行扫描数据,流程如下:

1)用户搜索数据,条件是title符合"%手机%"

2)逐行获取数据,比如id为1的数据

3)判断数据中的title是否符合用户搜索条件

4)如果符合则放入结果集,不符合则丢弃。回到步骤1

逐行扫描,也就是全表扫描,随着数据量增加,其查询效率也会越来越低。当数据量达到数百万时,就是一场灾难。

1.2.2.倒排索引

倒排索引中有两个非常重要的概念:

  • 文档(document):用来搜索的数据,其中的每一条数据就是一个文档。例如一个网页、一个商品信息
  • 词条(term):对文档数据或用户搜索数据,利用某种算法分词,得到的具备含义的词语就是词条。例如:我是中国人,就可以分为:我、是、中国人、中国、国人这样的几个词条

创建倒排索引是对正向索引的一种特殊处理,流程如下:

  • 将每一个文档的数据利用算法分词,得到一个个词条
  • 创建表,每行数据包括词条、词条所在文档id、位置等信息
  • 因为词条唯一性,可以给词条创建索引,例如hash表结构索引

如图:

在这里插入图片描述

倒排索引的搜索流程如下(以搜索"华为手机"为例):

1)用户输入条件"华为手机"进行搜索。

2)对用户输入内容分词,得到词条:华为手机

3)拿着词条在倒排索引中查找,可以得到包含词条的文档id:1、2、3。

4)拿着文档id到正向索引中查找具体文档。

如图:

在这里插入图片描述

虽然要先查询倒排索引,再查询倒排索引,但是无论是词条、还是文档id都建立了索引,查询速度非常快!无需全表扫描。

1.2.3.正向和倒排

那么为什么一个叫做正向索引,一个叫做倒排索引呢?

  • 正向索引是最传统的,根据id索引的方式。但根据词条查询时,必须先逐条获取每个文档,然后判断文档中是否包含所需要的词条,是根据文档找词条的过程

  • 倒排索引则相反,是先找到用户要搜索的词条,根据词条得到保护词条的文档的id,然后根据id获取文档。是根据词条找文档的过程

是不是恰好反过来了?

那么两者方式的优缺点是什么呢?

正向索引

  • 优点:
    • 可以给多个字段创建索引
    • 根据索引字段搜索、排序速度非常快
  • 缺点:
    • 根据非索引字段,或者索引字段中的部分词条查找时,只能全表扫描。

倒排索引

  • 优点:
    • 根据词条搜索、模糊搜索时,速度非常快
  • 缺点:
    • 只能给词条创建索引,而不是字段
    • 无法根据字段做排序

1.3.es的一些概念

elasticsearch中有很多独有的概念,与mysql中略有差别,但也有相似之处。

1.3.1.文档和字段

elasticsearch是面向**文档(document)**存储的,可以是数据库中的一条商品数据,一个订单信息。文档数据会被序列化为json格式后存储在elasticsearch中:

在这里插入图片描述

而json文档中往往包含很多的字段(field),类似于数据库中的列。

1.3.2.索引和映射

索引(index),就是相同类型的文档的集合。

例如:

  • 所有用户文档,就可以组织在一起,称为用户的索引;
  • 所有商品的文档,可以组织在一起,称为商品的索引;
  • 所有订单的文档,可以组织在一起,称为订单的索引;

在这里插入图片描述

因此,我们可以把索引当做是数据库中的表。

数据库的表会有约束信息,用来定义表的结构、字段的名称、类型等信息。因此,索引库中就有映射(mapping),是索引中文档的字段约束信息,类似表的结构约束。

1.3.3.mysql与elasticsearch

我们统一的把mysql与elasticsearch的概念做一下对比:

mysqlelasticsearch说明
tableindex索引(index),就是文档的集合,类似数据库的表(table)
rowdocument文档(document),就是一条条的数据,类似数据库中的行(row),文档都是json格式
columnfield字段(field),就是json文档中的字段,类似数据库中的列(column)
schemamappingmapping(映射)是索引中文档的约束,例如字段类型约束。类似数据库的表结构(schema)
sqldsldsl是elasticsearch提供的json风格的请求语句,用来操作elasticsearch,实现crud

是不是说,我们学习了elasticsearch就不再需要mysql了呢?

并不是如此,两者各自有自己的擅长支出:

  • mysql:擅长事务类型操作,可以确保数据的安全和一致性

  • elasticsearch:擅长海量数据的搜索、分析、计算

因此在企业中,往往是两者结合使用:

  • 对安全性要求较高的写操作,使用mysql实现
  • 对查询性能要求较高的搜索需求,使用elasticsearch实现
  • 两者再基于某种方式,实现数据的同步,保证一致性

在这里插入图片描述

1.4.安装es、kibana

1.4.1.安装

参考资料:《java—微服务—elasticsearch安装部署》

1.4.2.分词器

参考资料:《java—微服务—elasticsearch安装部署》

1.4.3.总结

分词器的作用是什么?

  • 创建倒排索引时对文档分词
  • 用户搜索时,对输入的内容分词

ik分词器有几种模式?

  • ik_smart:智能切分,粗粒度
  • ik_max_word:最细切分,细粒度

ik分词器如何拓展词条?如何停用词条?

  • 利用config目录的ikanalyzer.cfg.xml文件添加拓展词典和停用词典
  • 在词典中添加拓展词条或者停用词条

2.索引库操作

索引库就类似数据库表,mapping映射就类似表的结构。

我们要向es中存储数据,必须先创建“库”和“表”。

2.1.mapping映射属性

mapping是对索引库中文档的约束,常见的mapping属性包括:

  • type:字段数据类型,常见的简单类型有:
    • 字符串:text(可分词的文本)、keyword(精确值,例如:品牌、国家、ip地址)
    • 数值:long、integer、short、byte、double、float、
    • 布尔:boolean
    • 日期:date
    • 对象:object
  • index:是否创建索引,默认为true
  • analyzer:使用哪种分词器
  • properties:该字段的子字段

例如下面的json文档:

{
    "age": 21,
    "weight": 52.1,
    "ismarried": false,
    "info": "中关村顶级全栈工程师",
    "email": "123@123.com",
    "score": [99.1, 99.5, 98.9],
    "name": {
        "firstname": "云",
        "lastname": "赵"
    }
}

对应的每个字段映射(mapping):

  • age:类型为 integer;参与搜索,因此需要index为true;无需分词器
  • weight:类型为float;参与搜索,因此需要index为true;无需分词器
  • ismarried:类型为boolean;参与搜索,因此需要index为true;无需分词器
  • info:类型为字符串,需要分词,因此是text;参与搜索,因此需要index为true;分词器可以用ik_smart
  • email:类型为字符串,但是不需要分词,因此是keyword;不参与搜索,因此需要index为false;无需分词器
  • score:虽然是数组,但是我们只看元素的类型,类型为float;参与搜索,因此需要index为true;无需分词器
  • name:类型为object,需要定义多个子属性
    • name.firstname;类型为字符串,但是不需要分词,因此是keyword;参与搜索,因此需要index为true;无需分词器
    • name.lastname;类型为字符串,但是不需要分词,因此是keyword;参与搜索,因此需要index为true;无需分词器

2.2.索引库的crud

这里我们统一使用kibana编写dsl的方式来演示。

2.2.1.创建索引库和映射

基本语法:
  • 请求方式:put
  • 请求路径:/索引库名,可以自定义
  • 请求参数:mapping映射

格式:

put /索引库名称
{
  "mappings": {
    "properties": {
      "字段名":{
        "type": "text",
        "analyzer": "ik_smart"
      },
      "字段名2":{
        "type": "keyword",
        "index": "false"
      },
      "字段名3":{
        "properties": {
          "子字段": {
            "type": "keyword"
          }
        }
      },
      // ...略
    }
  }
}
示例:
put /dsc
{
  "mappings": {
    "properties": {
      "info":{
        "type": "text",
        "analyzer": "ik_smart"
      },
      "email":{
        "type": "keyword",
        "index": "falsae"
      },
      "name":{
        "properties": {
          "firstname": {
            "type": "keyword"
          }
        }
      },
      // ... 略
    }
  }
}

2.2.2.查询索引库

基本语法

  • 请求方式:get

  • 请求路径:/索引库名

  • 请求参数:无

格式

get /索引库名

示例

在这里插入图片描述

2.2.3.修改索引库

倒排索引结构虽然不复杂,但是一旦数据结构改变(比如改变了分词器),就需要重新创建倒排索引,这简直是灾难。因此索引库一旦创建,无法修改mapping

虽然无法修改mapping中已有的字段,但是却允许添加新的字段到mapping中,因为不会对倒排索引产生影响。

语法说明

put /索引库名/_mapping
{
  "properties": {
    "新字段名":{
      "type": "integer"
    }
  }
}

示例

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-jlcyqsbv-1674697171606)(assets/image-20210720212357390.png)]

2.2.4.删除索引库

语法:

  • 请求方式:delete

  • 请求路径:/索引库名

  • 请求参数:无

格式:

delete /索引库名

2.2.5.总结

索引库操作有哪些?

  • 创建索引库:put /索引库名
  • 查询索引库:get /索引库名
  • 删除索引库:delete /索引库名
  • 添加字段:put /索引库名/_mapping

3.文档操作

3.1.新增文档

语法:

post /索引库名/_doc/文档id
{
    "字段1": "值1",
    "字段2": "值2",
    "字段3": {
        "子属性1": "值3",
        "子属性2": "值4"
    },
    // ...
}

示例:

post /dsc/_doc/1
{
    "info": "中关村顶级全栈工程师",
    "email": "123@123.cn",
    "name": {
        "firstname": "云",
        "lastname": "赵"
    }
}

响应:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-zpxen5br-1674697171606)(assets/image-20210720212933362.png)]

3.2.查询文档

根据rest风格,新增是post,查询应该是get,不过查询一般都需要条件,这里我们把文档id带上。

语法:

get /{索引库名称}/_doc/{id}

通过kibana查看数据:

get /dsc/_doc/1

查看结果:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-pkojuljk-1674697171606)(assets/image-20210720213345003.png)]

3.3.删除文档

删除使用delete请求,同样,需要根据id进行删除:

语法:

delete /{索引库名}/_doc/id值

示例:

# 根据id删除数据
delete /dsc/_doc/1

结果:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-aok7sj4b-1674697171606)(assets/image-20210720213634918.png)]

3.4.修改文档

修改有两种方式:

  • 全量修改:直接覆盖原来的文档
  • 增量修改:修改文档中的部分字段

3.4.1.全量修改

全量修改是覆盖原来的文档,其本质是:

  • 根据指定的id删除文档
  • 新增一个相同id的文档

注意:如果根据id删除时,id不存在,第二步的新增也会执行,也就从修改变成了新增操作了。

语法:

put /{索引库名}/_doc/文档id
{
    "字段1": "值1",
    "字段2": "值2",
    // ... 略
}

示例:

put /dsc/_doc/1
{
    "info": "硅谷全栈工程师",
    "email": "321@321.cn",
    "name": {
        "firstname": "松",
        "lastname": "武"
    }
}

在这里插入图片描述

3.4.2.增量修改

增量修改是只修改指定id匹配的文档中的部分字段。

语法:

post /{索引库名}/_update/文档id
{
    "doc": {
         "字段名": "新的值",
    }
}

示例:

post /dsc/_update/1
{
  "doc": {
    "email": "141614@3051.cn"
  }
}

在这里插入图片描述

3.5.总结

文档操作有哪些?

  • 创建文档:post /{索引库名}/_doc/文档id { json文档 }
  • 查询文档:get /{索引库名}/_doc/文档id
  • 删除文档:delete /{索引库名}/_doc/文档id
  • 修改文档:
    • 全量修改:put /{索引库名}/_doc/文档id { json文档 }
    • 增量修改:post /{索引库名}/_update/文档id { “doc”: {字段}}

4.restapi

es官方提供了各种不同语言的客户端,用来操作es。这些客户端的本质就是组装dsl语句,通过http请求发送给es。官方文档地址:https://www.elastic.co/guide/en/elasticsearch/client/index.html

其中的java rest client又包括两种:

  • java low level rest client
  • java high level rest client

在这里插入图片描述

我们学习的是java highlevel rest client客户端api

4.0.导入demo工程

4.0.1.导入数据

首先导入数据库数据,数据结构如下:

create table `tb_hotel` (
  `id` bigint(20) not null comment '酒店id',
  `name` varchar(255) not null comment '酒店名称;例:7天酒店',
  `address` varchar(255) not null comment '酒店地址;例:航头路',
  `price` int(10) not null comment '酒店价格;例:329',
  `score` int(2) not null comment '酒店评分;例:45,就是4.5分',
  `brand` varchar(32) not null comment '酒店品牌;例:如家',
  `city` varchar(32) not null comment '所在城市;例:上海',
  `star_name` varchar(16) default null comment '酒店星级,从低到高分别是:1星到5星,1钻到5钻',
  `business` varchar(255) default null comment '商圈;例:虹桥',
  `latitude` varchar(32) not null comment '纬度;例:31.2497',
  `longitude` varchar(32) not null comment '经度;例:120.3925',
  `pic` varchar(255) default null comment '酒店图片;例:/img/1.jpg',
  primary key (`id`)
) engine=innodb default charset=utf8mb4;

4.0.2.导入项目

导入黑马提供的项目,项目结构如图:

在这里插入图片描述

4.0.3.mapping映射分析

创建索引库,最关键的是mapping映射,而mapping映射要考虑的信息包括:

  • 字段名
  • 字段数据类型
  • 是否参与搜索
  • 是否需要分词
  • 如果分词,分词器是什么?

其中:

  • 字段名、字段数据类型,可以参考数据表结构的名称和类型
  • 是否参与搜索要分析业务来判断,例如图片地址,就无需参与搜索
  • 是否分词呢要看内容,内容如果是一个整体就无需分词,反之则要分词
  • 分词器,我们可以统一使用ik_max_word

来看下酒店数据的索引库结构:

put /hotel
{
  "mappings": {
    "properties": {
      "id": {
        "type": "keyword"
      },
      "name":{
        "type": "text",
        "analyzer": "ik_max_word",
        "copy_to": "all"
      },
      "address":{
        "type": "keyword",
        "index": false
      },
      "price":{
        "type": "integer"
      },
      "score":{
        "type": "integer"
      },
      "brand":{
        "type": "keyword",
        "copy_to": "all"
      },
      "city":{
        "type": "keyword",
        "copy_to": "all"
      },
      "starname":{
        "type": "keyword"
      },
      "business":{
        "type": "keyword"
      },
      "location":{
        "type": "geo_point"
      },
      "pic":{
        "type": "keyword",
        "index": false
      },
      "all":{
        "type": "text",
        "analyzer": "ik_max_word"
      }
    }
  }
}

几个特殊字段说明:

  • location:地理坐标,里面包含精度、纬度
  • all:一个组合字段,其目的是将多字段的值 利用copy_to合并,提供给用户搜索

地理坐标说明:

在这里插入图片描述

copy_to说明:

在这里插入图片描述

4.0.4.初始化restclient

在elasticsearch提供的api中,与elasticsearch一切交互都封装在一个名为resthighlevelclient的类中,必须先完成这个对象的初始化,建立与elasticsearch的连接。

分为三步:

1)引入es的resthighlevelclient依赖:

<dependency>
    <groupid>org.elasticsearch.client</groupid>
    <artifactid>elasticsearch-rest-high-level-client</artifactid>
</dependency>

2)因为springboot默认的es版本是7.6.2,所以我们需要覆盖默认的es版本:

<properties>
    <java.version>1.8</java.version>
    <elasticsearch.version>7.12.1</elasticsearch.version>
</properties>

3)初始化resthighlevelclient:

初始化的代码如下:

resthighlevelclient client = new resthighlevelclient(restclient.builder(
        httphost.create("http://192.168.150.101:9200")
));

这里为了单元测试方便,我们创建一个测试类hotelindextest,然后将初始化的代码编写在@beforeeach方法中:

package cn.itcast.hotel;

import org.apache.http.httphost;
import org.elasticsearch.client.resthighlevelclient;
import org.junit.jupiter.api.aftereach;
import org.junit.jupiter.api.beforeeach;
import org.junit.jupiter.api.test;

import java.io.ioexception;

public class hotelindextest {
    private resthighlevelclient client;

    @beforeeach
    void setup() {
        this.client = new resthighlevelclient(restclient.builder(
                httphost.create("http://192.168.150.101:9200")
        ));
    }

    @aftereach
    void teardown() throws ioexception {
        this.client.close();
    }
}

4.1.创建索引库

4.1.1.代码解读

创建索引库的api如下:

在这里插入图片描述

代码分为三步:

  • 1)创建request对象。因为是创建索引库的操作,因此request是createindexrequest。
  • 2)添加请求参数,其实就是dsl的json参数部分。因为json字符串很长,这里是定义了静态字符串常量mapping_template,让代码看起来更加优雅。
  • 3)发送请求,client.indices()方法的返回值是indicesclient类型,封装了所有与索引库操作有关的方法。

4.1.2.完整示例

在hotel-demo的cn.itcast.hotel.constants包下,创建一个类,定义mapping映射的json字符串常量:

package cn.itcast.hotel.constants;

public class hotelconstants {
    public static final string mapping_template = "{\n" +
            "  \"mappings\": {\n" +
            "    \"properties\": {\n" +
            "      \"id\": {\n" +
            "        \"type\": \"keyword\"\n" +
            "      },\n" +
            "      \"name\":{\n" +
            "        \"type\": \"text\",\n" +
            "        \"analyzer\": \"ik_max_word\",\n" +
            "        \"copy_to\": \"all\"\n" +
            "      },\n" +
            "      \"address\":{\n" +
            "        \"type\": \"keyword\",\n" +
            "        \"index\": false\n" +
            "      },\n" +
            "      \"price\":{\n" +
            "        \"type\": \"integer\"\n" +
            "      },\n" +
            "      \"score\":{\n" +
            "        \"type\": \"integer\"\n" +
            "      },\n" +
            "      \"brand\":{\n" +
            "        \"type\": \"keyword\",\n" +
            "        \"copy_to\": \"all\"\n" +
            "      },\n" +
            "      \"city\":{\n" +
            "        \"type\": \"keyword\",\n" +
            "        \"copy_to\": \"all\"\n" +
            "      },\n" +
            "      \"starname\":{\n" +
            "        \"type\": \"keyword\"\n" +
            "      },\n" +
            "      \"business\":{\n" +
            "        \"type\": \"keyword\"\n" +
            "      },\n" +
            "      \"location\":{\n" +
            "        \"type\": \"geo_point\"\n" +
            "      },\n" +
            "      \"pic\":{\n" +
            "        \"type\": \"keyword\",\n" +
            "        \"index\": false\n" +
            "      },\n" +
            "      \"all\":{\n" +
            "        \"type\": \"text\",\n" +
            "        \"analyzer\": \"ik_max_word\"\n" +
            "      }\n" +
            "    }\n" +
            "  }\n" +
            "}";
}

在hotel-demo中的hotelindextest测试类中,编写单元测试,实现创建索引:

@test
void createhotelindex() throws ioexception {
    // 1.创建request对象
    createindexrequest request = new createindexrequest("hotel");
    // 2.准备请求的参数:dsl语句
    request.source(mapping_template, xcontenttype.json);
    // 3.发送请求
    client.indices().create(request, requestoptions.default);
}

4.2.删除索引库

删除索引库的dsl语句非常简单:

delete /hotel

与创建索引库相比:

  • 请求方式从put变为delte
  • 请求路径不变
  • 无请求参数

所以代码的差异,注意体现在request对象上。依然是三步走:

  • 1)创建request对象。这次是deleteindexrequest对象
  • 2)准备参数。这里是无参
  • 3)发送请求。改用delete方法

在hotel-demo中的hotelindextest测试类中,编写单元测试,实现删除索引:

@test
void testdeletehotelindex() throws ioexception {
    // 1.创建request对象
    deleteindexrequest request = new deleteindexrequest("hotel");
    // 2.发送请求
    client.indices().delete(request, requestoptions.default);
}

4.3.判断索引库是否存在

判断索引库是否存在,本质就是查询,对应的dsl是:

get /hotel

因此与删除的java代码流程是类似的。依然是三步走:

  • 1)创建request对象。这次是getindexrequest对象
  • 2)准备参数。这里是无参
  • 3)发送请求。改用exists方法
@test
void testexistshotelindex() throws ioexception {  
    // 1.创建request对象
    getindexrequest request = new getindexrequest("hotel");
    // 2.发送请求
    boolean exists = client.indices().exists(request, requestoptions.default);
    // 3.输出
    system.err.println(exists ? "索引库已经存在!" : "索引库不存在!");
}

4.4.总结

javarestclient操作elasticsearch的流程基本类似。核心是client.indices()方法来获取索引库的操作对象。

索引库操作的基本步骤:

  • 初始化resthighlevelclient
  • 创建xxxindexrequest。xxx是create、get、delete
  • 准备dsl( create时需要,其它是无参)
  • 发送请求。调用resthighlevelclient#indices().xxx()方法,xxx是create、exists、delete

5.restclient操作文档

为了与索引库操作分离,我们再次参加一个测试类,做两件事情:

  • 初始化resthighlevelclient
  • 我们的酒店数据在数据库,需要利用ihotelservice去查询,所以注入这个接口
package cn.itcast.hotel;

import cn.itcast.hotel.pojo.hotel;
import cn.itcast.hotel.service.ihotelservice;
import org.junit.jupiter.api.aftereach;
import org.junit.jupiter.api.beforeeach;
import org.junit.jupiter.api.test;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.boot.test.context.springboottest;

import java.io.ioexception;
import java.util.list;

@springboottest
public class hoteldocumenttest {
    @autowired
    private ihotelservice hotelservice;

    private resthighlevelclient client;

    @beforeeach
    void setup() {
        this.client = new resthighlevelclient(restclient.builder(
                httphost.create("http://192.168.150.101:9200")
        ));
    }

    @aftereach
    void teardown() throws ioexception {
        this.client.close();
    }
}

5.1.新增文档

我们要将数据库的酒店数据查询出来,写入elasticsearch中。

5.1.1.索引库实体类

数据库查询后的结果是一个hotel类型的对象。结构如下:

@data
@tablename("tb_hotel")
public class hotel {
    @tableid(type = idtype.input)
    private long id;
    private string name;
    private string address;
    private integer price;
    private integer score;
    private string brand;
    private string city;
    private string starname;
    private string business;
    private string longitude;
    private string latitude;
    private string pic;
}

与我们的索引库结构存在差异:

  • longitude和latitude需要合并为location

因此,我们需要定义一个新的类型,与索引库结构吻合:

package cn.itcast.hotel.pojo;

import lombok.data;
import lombok.noargsconstructor;

@data
@noargsconstructor
public class hoteldoc {
    private long id;
    private string name;
    private string address;
    private integer price;
    private integer score;
    private string brand;
    private string city;
    private string starname;
    private string business;
    private string location;
    private string pic;

    public hoteldoc(hotel hotel) {
        this.id = hotel.getid();
        this.name = hotel.getname();
        this.address = hotel.getaddress();
        this.price = hotel.getprice();
        this.score = hotel.getscore();
        this.brand = hotel.getbrand();
        this.city = hotel.getcity();
        this.starname = hotel.getstarname();
        this.business = hotel.getbusiness();
        this.location = hotel.getlatitude() + ", " + hotel.getlongitude();
        this.pic = hotel.getpic();
    }
}

5.1.2.语法说明

新增文档的dsl语句如下:

post /{索引库名}/_doc/1
{
    "name": "jack",
    "age": 21
}

对应的java代码如图:

在这里插入图片描述

可以看到与创建索引库类似,同样是三步走:

  • 1)创建request对象
  • 2)准备请求参数,也就是dsl中的json文档
  • 3)发送请求

变化的地方在于,这里直接使用client.xxx()的api,不再需要client.indices()了。

5.1.3.完整代码

我们导入酒店数据,基本流程一致,但是需要考虑几点变化:

  • 酒店数据来自于数据库,我们需要先查询出来,得到hotel对象
  • hotel对象需要转为hoteldoc对象
  • hoteldoc需要序列化为json格式

因此,代码整体步骤如下:

  • 1)根据id查询酒店数据hotel
  • 2)将hotel封装为hoteldoc
  • 3)将hoteldoc序列化为json
  • 4)创建indexrequest,指定索引库名和id
  • 5)准备请求参数,也就是json文档
  • 6)发送请求

在hotel-demo的hoteldocumenttest测试类中,编写单元测试:

@test
void testadddocument() throws ioexception {
    // 1.根据id查询酒店数据
    hotel hotel = hotelservice.getbyid(61083l);
    // 2.转换为文档类型
    hoteldoc hoteldoc = new hoteldoc(hotel);   
    // 3.将hoteldoc转json
    string json = json.tojsonstring(hoteldoc);

    // 1.准备request对象
    indexrequest request = new indexrequest("hotel").id(hoteldoc.getid().tostring());
    // 2.准备json文档
    request.source(json, xcontenttype.json);
    // 3.发送请求
    client.index(request, requestoptions.default);
}

5.2.查询文档

5.2.1.语法说明

查询的dsl语句如下:

get /hotel/_doc/{id}

非常简单,因此代码大概分两步:

  • 准备request对象
  • 发送请求

不过查询的目的是得到结果,解析为hoteldoc,因此难点是结果的解析。完整代码如下:

在这里插入图片描述

可以看到,结果是一个json,其中文档放在一个_source属性中,因此解析就是拿到_source,反序列化为java对象即可。

与之前类似,也是三步走:

  • 1)准备request对象。这次是查询,所以是getrequest
  • 2)发送请求,得到结果。因为是查询,这里调用client.get()方法
  • 3)解析结果,就是对json做反序列化

5.2.2.完整代码

在hotel-demo的hoteldocumenttest测试类中,编写单元测试:

@test
void testgetdocumentbyid() throws ioexception {
    // 1.准备request
    getrequest request = new getrequest("hotel", "61082");
    // 2.发送请求,得到响应
    getresponse response = client.get(request, requestoptions.default);
    // 3.解析响应结果
    string json = response.getsourceasstring();

    hoteldoc hoteldoc = json.parseobject(json, hoteldoc.class);
    system.out.println(hoteldoc);
}

5.3.删除文档

删除的dsl为是这样的:

delete /hotel/_doc/{id}

与查询相比,仅仅是请求方式从delete变成get,可以想象java代码应该依然是三步走:

  • 1)准备request对象,因为是删除,这次是deleterequest对象。要指定索引库名和id
  • 2)准备参数,无参
  • 3)发送请求。因为是删除,所以是client.delete()方法

在hotel-demo的hoteldocumenttest测试类中,编写单元测试:

@test
void testdeletedocument() throws ioexception {
    // 1.准备request
    deleterequest request = new deleterequest("hotel", "61083");
    // 2.发送请求
    client.delete(request, requestoptions.default);
}

5.4.修改文档

5.4.1.语法说明

修改我们讲过两种方式:

  • 全量修改:本质是先根据id删除,再新增
  • 增量修改:修改文档中的指定字段值

在restclient的api中,全量修改与新增的api完全一致,判断依据是id:

  • 如果新增时,id已经存在,则修改
  • 如果新增时,id不存在,则新增

这里不再赘述,我们主要关注增量修改。

代码示例如图:

在这里插入图片描述

与之前类似,也是三步走:

  • 1)准备request对象。这次是修改,所以是updaterequest
  • 2)准备参数。也就是json文档,里面包含要修改的字段
  • 3)更新文档。这里调用client.update()方法

5.4.2.完整代码

在hotel-demo的hoteldocumenttest测试类中,编写单元测试:

@test
void testupdatedocument() throws ioexception {
    // 1.准备request
    updaterequest request = new updaterequest("hotel", "61083");
    // 2.准备请求参数
    request.doc(
        "price", "952",
        "starname", "四钻"
    );
    // 3.发送请求
    client.update(request, requestoptions.default);
}

5.5.批量导入文档

案例需求:利用bulkrequest批量将数据库数据导入到索引库中。

步骤如下:

  • 利用mybatis-plus查询酒店数据

  • 将查询到的酒店数据(hotel)转换为文档类型数据(hoteldoc)

  • 利用javarestclient中的bulkrequest批处理,实现批量新增文档

5.5.1.语法说明

批量处理bulkrequest,其本质就是将多个普通的crud请求组合在一起发送。

其中提供了一个add方法,用来添加其他请求:

在这里插入图片描述

可以看到,能添加的请求包括:

  • indexrequest,也就是新增
  • updaterequest,也就是修改
  • deleterequest,也就是删除

因此bulk中添加了多个indexrequest,就是批量新增功能了。示例:

在这里插入图片描述

其实还是三步走:

  • 1)创建request对象。这里是bulkrequest
  • 2)准备参数。批处理的参数,就是其它request对象,这里就是多个indexrequest
  • 3)发起请求。这里是批处理,调用的方法为client.bulk()方法

我们在导入酒店数据时,将上述代码改造成for循环处理即可。

5.5.2.完整代码

在hotel-demo的hoteldocumenttest测试类中,编写单元测试:

@test
void testbulkrequest() throws ioexception {
    // 批量查询酒店数据
    list<hotel> hotels = hotelservice.list();

    // 1.创建request
    bulkrequest request = new bulkrequest();
    // 2.准备参数,添加多个新增的request
    for (hotel hotel : hotels) {
        // 2.1.转换为文档类型hoteldoc
        hoteldoc hoteldoc = new hoteldoc(hotel);
        // 2.2.创建新增文档的request对象
        request.add(new indexrequest("hotel")
                    .id(hoteldoc.getid().tostring())
                    .source(json.tojsonstring(hoteldoc), xcontenttype.json));
    }
    // 3.发送请求
    client.bulk(request, requestoptions.default);
}

5.6.小结

文档操作的基本步骤:

  • 初始化resthighlevelclient
  • 创建xxxrequest。xxx是index、get、update、delete、bulk
  • 准备参数(index、update、bulk时需要)
  • 发送请求。调用resthighlevelclient#.xxx()方法,xxx是index、get、update、delete、bulk
  • 解析结果(get时需要)

如有不足,请多指教,
未完待续,持续更新!
大家一起进步!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com