elasticsearch搜索引擎

在这里插入图片描述
elasticsearch底层是基于lucene来实现的。
Lucene是一个Java语言的搜索引擎类库,是Apache公司的顶级项目,由DougCutting于1999年研发

正向索引

需求:比如查询数据库中title中包含手机
select * from tb_goods where title like "%手机%"

如果是基于title做模糊查询,只能是逐行扫描数据,流程如下:
1)用户搜索数据,条件是title符合"%手机%"
2)逐行获取数据,比如id为1的数据
3)判断数据中的title是否符合用户搜索条件
4)如果符合则放入结果集,不符合则丢弃。回到步骤1

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

倒排索引

倒排索引中有两个非常重要的概念:
文档(Document):用来搜索的数据,其中的每一条数据就是一个文档。例如一个网页、一个商品信息
词条(Term):对文档数据或用户搜索数据,利用某种算法分词,得到的具备含义的词语就是词条。例如:我是中国人,就可以分为:我、是、中国人、中国、国人这样的几个词条
在这里插入图片描述
倒排索引的搜索流程如下(以搜索"华为手机"为例):
1)用户输入条件"华为手机"进行搜索。
2)对用户输入内容分词,得到词条:华为手机
3)拿着词条在倒排索引中查找,可以得到包含词条的文档id:1、2、3。
4)拿着文档id到正向索引中查找具体文档。
在这里插入图片描述

mysql与elasticsearch比较

MySQLElasticsearch说明
TableIndex索引(index),就是文档的集合,类似数据库的表(table)
RowDocument文档(Document),就是一条条的数据,类似数据库中的行(Row),文档都是JSON格式
ColumnField字段(Field),就是JSON文档中的字段,类似数据库中的列(Column)
SchemaMappingMapping(映射)是索引中文档的约束,例如字段类型约束。类似数据库的表结构(Schema)
SQLDSLDSL是elasticsearch提供的JSON风格的请求语句,用来操作elasticsearch,实现CRUD

Mysql:擅长事务类型操作,可以确保数据的安全和一致性
Elasticsearch:擅长海量数据的搜索、分析、计算

往往是两者结合使用:
对安全性要求较高的写操作,使用mysql实现
对查询性能要求较高的搜索需求,使用elasticsearch实现
两者再基于某种方式,实现数据的同步,保证一致性
在这里插入图片描述

安装elasticsearch

部署单点es

1,创建网络
还需要部署kibana容器,因此需要让es和kibana容器互联。这里先创建一个网络
docker network create es-net

2,上传es.tar至虚拟机

3,加载tar文件成镜像文件
# 导入数据
docker load -i es.tar

4,创建并启动es容器
docker run -d \
	--name es \
    -e "ES_JAVA_OPTS=-Xms512m -Xmx512m" \
    -e "discovery.type=single-node" \
    -v es-data:/usr/share/elasticsearch/data \
    -v es-plugins:/usr/share/elasticsearch/plugins \
    --privileged \
    --network es-net \
    -p 9200:9200 \
    -p 9300:9300 \
elasticsearch:7.12.1
命令解析:
`-e "ES_JAVA_OPTS=-Xms512m -Xmx512m"`:内存大小
`-e "discovery.type=single-node"`:非集群模式
`-v es-data:/usr/share/elasticsearch/data`:挂载逻辑卷,绑定es的数据目录
`-v es-logs:/usr/share/elasticsearch/logs`:挂载逻辑卷,绑定es的日志目录
`-v es-plugins:/usr/share/elasticsearch/plugins`:挂载逻辑卷,绑定es的插件目录
`--privileged`:授予逻辑卷访问权
`--network es-net` :加入一个名为es-net的网络中
`-p 9200:9200`:端口映射配置

5,在浏览器中输入:http://192.168.150.101:9200 即可看到elasticsearch的响应结果
{
  "name" : "3983790045db",
  "cluster_name" : "docker-cluster",
  "cluster_uuid" : "19AVstGMTzqejqsSHgfzJg",
  "version" : {
    "number" : "7.12.1",
    "build_flavor" : "default",
    "build_type" : "docker",
    "build_hash" : "3186837139b9c6b6d23c3200870651f10d3343b7",
    "build_date" : "2021-04-20T20:56:39.040728659Z",
    "build_snapshot" : false,
    "lucene_version" : "8.8.0",
    "minimum_wire_compatibility_version" : "6.8.0",
    "minimum_index_compatibility_version" : "6.0.0-beta1"
  },
  "tagline" : "You Know, for Search"
}

部署kibana

kibana提供一个elasticsearch的可视化界面

1,创建网络(因为部署es时已经创建所以第一步不需要操作)
还需要部署kibana容器,因此需要让es和kibana容器互联。这里先创建一个网络
docker network create es-net

2,上传kibana.tar至虚拟机

3,加载tar文件成镜像文件
# 导入数据
docker load -i es.tar

4,创建并启动kibana容器
docker run -d \
--name kibana \
-e ELASTICSEARCH_HOSTS=http://es:9200 \
--network=es-net \
-p 5601:5601  \
kibana:7.12.1
命令解析:
`--network es-net` :加入一个名为es-net的网络中,与elasticsearch在同一个网络中
`-e ELASTICSEARCH_HOSTS=http://es:9200"`:设置elasticsearch的地址,因为kibana已经与elasticsearch在一个网络,因此可以用容器名直接访问elasticsearch
`-p 5601:5601`:端口映射配置

5,kibana启动一般比较慢,需要多等待一会,可以通过命令查看运行日志
docker logs -f kibana
如果出现http server running at http://0.0.0.0:5601说明运行成功

6,在浏览器输入地址访问:http://192.168.150.101:5601

7,kibana中提供了一个DevTools界面
这个界面中可以编写DSL来操作elasticsearch。并且对DSL语句有自动补全功能

安装IK分词器

因为默认的分词器对中文不友好

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

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

离线安装ik插件

1,查看数据卷目录
安装插件需要知道elasticsearch的plugins目录位置,而我们用了数据卷挂载,因此需要查看elasticsearch的数据卷目录
docker volume inspect es-plugins
查询结果:
[
    {
        "CreatedAt": "2022-10-23T19:25:10-07:00",
        "Driver": "local",
        "Labels": null,
        "Mountpoint": "/var/lib/docker/volumes/es-plugins/_data",
        "Name": "es-plugins",
        "Options": null,
        "Scope": "local"
    }
]
2,本地解压分词器安装包重命名为ik

3,上传到es容器的插件数据卷中
/var/lib/docker/volumes/es-plugins/_data

4重启容器
docker restart es

5,查看es日志
docker logs -f es

6,DevTools界面测试
# 测试分词器
POST /_analyze
{
  "text": "学习java太棒了",
  "analyzer": "ik_smart"
}
分词结果:
{
  "tokens" : [
    {
      "token" : "学习",
      "start_offset" : 0,
      "end_offset" : 2,
      "type" : "CN_WORD",
      "position" : 0
    },
    {
      "token" : "java",
      "start_offset" : 2,
      "end_offset" : 6,
      "type" : "ENGLISH",
      "position" : 1
    },
    {
      "token" : "太棒了",
      "start_offset" : 6,
      "end_offset" : 9,
      "type" : "CN_WORD",
      "position" : 2
    }
  ]
}

IK分词器包含两种模式:
ik_smart:最少切分
ik_max_word:最细切分

扩展词、停用词词典

1,打开IK分词器config目录
/var/lib/docker/volumes/es-plugins/_data/ik/config

2,在IKAnalyzer.cfg.xml配置文件内容添加
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
        <comment>IK Analyzer 扩展配置</comment>
        <!--用户可以在这里配置自己的扩展字典 *** 添加扩展词典-->
        <entry key="ext_dict">ext.dic</entry>
		<!--用户可以在这里配置自己的扩展停止词字典-->
		<entry key="ext_stopwords">stopword.dic</entry>
</properties>

3,新建一个 ext.dic 添加自己需要的新词比如:奥利给
	修改stopword.dic,添加新的敏感词

4,重启elasticsearch 
docker restart es
docker restart kibana
# 查看 日志,直到日志中已经成功加载ext.dic、stopword.dic配置文件
docker logs -f elasticsearch

5,DevTools界面测试
# 测试分词器
POST /_analyze
{
  "text": "学习java太棒了,奥利给",
  "analyzer": "ik_smart"
}
# 结果集
{
  "tokens" : [
    {
      "token" : "学习",
      "start_offset" : 0,
      "end_offset" : 2,
      "type" : "CN_WORD",
      "position" : 0
    },
    {
      "token" : "java",
      "start_offset" : 2,
      "end_offset" : 6,
      "type" : "ENGLISH",
      "position" : 1
    },
    {
      "token" : "太棒了",
      "start_offset" : 6,
      "end_offset" : 9,
      "type" : "CN_WORD",
      "position" : 2
    },
    {
      "token" : "奥利给",
      "start_offset" : 10,
      "end_offset" : 13,
      "type" : "CN_WORD",
      "position" : 3
    }
  ]
}

索引库操作

索引库就类似数据库表,mapping映射类似数据库的表结构(Schema)
我们要向es中存储数据,必须先创建“库”和“表”

mapping映射属性

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

{
    "age": 21,  //age:类型为 integer;参与搜索,因此需要index为true;无需分词器
    "weight": 52.1, //weight:类型为float;参与搜索,因此需要index为true;无需分词器
    "isMarried": false,  //isMarried:类型为boolean;参与搜索,因此需要index为true;无需分词器
    "info": "程序员Java", //info:类型为字符串,需要分词,因此是text;参与搜索,因此需要index为true;分词器可以用ik_smart
    "email": "zy@ben.cn",  //email:类型为字符串,但是不需要分词,因此是keyword;不参与搜索,因此需要index为false;无需分词器
    "score": [99.1, 99.5, 98.9], //score:虽然是数组,但是我们只看元素的类型,类型为float;参与搜索,因此需要index为true;无需分词器
    "name": {
        "firstName": "云",//name.firstName;类型为字符串,但是不需要分词,因此是keyword;参与搜索,因此需要index为true;无需分词器
        "lastName": "赵" //ame.lastName;类型为字符串,但是不需要分词,因此是keyword;参与搜索,因此需要index为true;无需分词器
    }
}

创建索引库和映射 相当于数据库里创建表

# 创建索引库 相当于数据库里创建表
语法:
PUT /索引库名
例如:
PUT /user_table
{
  "mappings": {
    "properties": {
      "info": {
        "type": "text",
         "analyzer": "ik_smart"
      },
       "email": {
        "type": "keyword",
        "index": false
       },
       "name": {
           "type": "object",
           "properties": {
             "firstName": {
                 "type": "keyword"
             },
          "lastName": {
             "type": "keyword"
          }
        }
      }
    }
  }
}

结果集
{
  "acknowledged" : true,
  "shards_acknowledged" : true,
  "index" : "user_table"
}

查询索引库、修改索引库、删除索引库

# 查询索引库
GET /索引库名
GET /user_table

# 修改索引库
倒排索引结构虽然不复杂,但是一旦数据结构改变(比如改变了分词器),就需要重新创建倒排索引,这简直是灾难。因此索引库一旦创建,无法修改mapping。
虽然无法修改mapping中已有的字段,但是却允许添加新的字段到mapping中,因为不会对倒排索引产生影响。
语法说明:
PUT /索引库名/_mapping
{
  "properties": {
    "新字段名":{
      "type": "integer"
    }
  }
}
# 修改索引库,添加新字段
PUT /user_table/_mapping
{
  "properties": {
    "age": {
      "type": "integer"
    }
  }
}

# 删除索引库
DELETE /索引库名
DELETE /user_table

文档操作:新增文档、查询文档、删除文档

文档操作相当于数据库里每一行数据

1,新增文档
POST /索引库名/_doc/文档id
{
    "字段1": "值1",
    "字段2": "值2",
    "字段3": {
        "子属性1": "值3",
        "子属性2": "值4"
    },
    // ...
}
例子:
# 插入文档
POST /user_table/_doc/1
{
  "age": 18,
  "email": "abc@qq.com",
  "info": "java讲师",
  "name": {
    "firstName": "赵",
    "lastName": "云"
  }
}

2,查询文档
GET /{索引库名称}/_doc/{id}
# 查询文档
GET /user_table/_doc/1

3,删除文档
DELETE /{索引库名}/_doc/id值
# 删除文档
DELETE /user_table/_doc/1

修改文档

修改有两种方式:
全量修改:直接覆盖原来的文档
增量修改:修改文档中的部分字段

# 全量修改文档
# 当id存在时是修改操作;当id不存在时,是新增操作
PUT /{索引库名}/_doc/文档id
{
    "字段1": "值1",
    "字段2": "值2",
    // ... 略
}
示例:
PUT /user_table/_doc/1
{
  "age": 18,
  "email": "zy@qq.com",
  "info": "java讲师",
  "name": {
    "firstName": "赵",
    "lastName": "云"
  }
}
# 增量修改
增量修改是只修改指定id匹配的文档中的部分字段
POST /{索引库名}/_update/文档id
{
    "doc": {
         "字段名": "新的值",
    }
}
# 增量修改,修改指定字段值
示例:
POST /user_table/_update/1
{
  "doc": {
    "email": "zhaoyun@qq.com"
  }
}

RestAPI

ES官方提供了各种不同语言的客户端,用来操作ES。这些客户端的本质就是组装DSL语句,通过http请求发送给ES。

数据结构如下:

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;

酒店数据的索引库结构

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:地理坐标,里面包含精度、纬度;类型是geo_point
all:一个组合字段,其目的是将多字段的值 利用copy_to合并,提供给用户搜索

操作索引库 初始化RestClient

在elasticsearch提供的API中,与elasticsearch一切交互都封装在一个名为RestHighLevelClient的类中,必须先完成这个对象的初始化,建立与elasticsearch的连接。
1)引入es的RestHighLevelClient依赖:

<!--引入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>
    <!--覆盖父工程spring-boot-starter-parent中定义的elasticsearch.version-->
    <elasticsearch.version>7.12.1</elasticsearch.version>
</properties>

3)初始化RestHighLevelClient:

public class HotelIndexTest {
    //RestHighLevelClient初始化去操作es
    private RestHighLevelClient client;

    @BeforeEach
    void setUp(){
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://192.168.98.129:9200")
        ));
    }
    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }

    @Test
    void testInit(){
        //org.elasticsearch.client.RestHighLevelClient@7922d892
        System.out.println(client);
    }
}

RestClient 创建索引库 操作索引库

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

public class HotelIndexTest {
    //RestHighLevelClient初始化去操作es
    private RestHighLevelClient client;

    @BeforeEach
    void setUp(){
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://192.168.98.129:9200")
        ));
    }

    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }

    @Test
    void testInit(){
        //org.elasticsearch.client.RestHighLevelClient@7922d892
        System.out.println(client);
    }

    @Test
    void createHotelIndex() throws IOException {
        //1,创建request对象 hotel指索引库名称
        CreateIndexRequest request = new CreateIndexRequest("hotel");
        //2,准备请求的参数 DSL语句
        //MAPPPING_TEMPLATE是静态常量字符串,内容是创建索引库的DSL语句
        request.source(MAPPPING_TEMPLATE,XContentType.JSON);
        //3,发送请求
        //indices()返回的是索引库操作的所有方法
        client.indices().create(request,RequestOptions.DEFAULT);
    }
}

静态字符串常量MAPPING_TEMPLATE

public class HotelConstants {
    public static final String MAPPPING_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" +
            "}";
}

RestClient 删除索引库、判断索引库是否存在

JavaRestClient操作elasticsearch的流程基本类似。核心是client.indices()方法来获取索引库的操作对象。
索引库操作的基本步骤:
初始化RestHighLevelClient
创建XxxIndexRequest。XXX是Create、Get、Delete
准备DSL( Create时需要,其它是无参)
发送请求。调用RestHighLevelClient#indices().xxx()方法,xxx是create、exists、delete

public class HotelIndexTest {
    //RestHighLevelClient初始化去操作es
    private RestHighLevelClient client;

    @BeforeEach
    void setUp(){
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://192.168.98.129:9200")
        ));
    }

    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }
	
	//删除索引库
    @Test
    void deleteHotelIndex() throws IOException {
        //1,创建request对象 hotel指索引库名称
        DeleteIndexRequest request = new DeleteIndexRequest("hotel");
        //3,发送请求
        //indices()返回的是索引库操作的所有方法
        client.indices().delete(request,RequestOptions.DEFAULT);
    }
	
	//判断索引库是否存在
    @Test
    void existHotelIndex() throws IOException {
        //1,创建request对象 hotel指索引库名称
        GetIndexRequest request = new GetIndexRequest("hotel");
        //3,发送请求
        //indices()返回的是索引库操作的所有方法
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);
    }
}

RestClient操作文档

新增文档

需求:将mysql数据查出来,插入es文档
数据库查询后的结果是一个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
因此,我们需要定义一个新的类型,与索引库结构吻合

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();
    }
}

代码整体步骤如下:
1)根据id查询酒店数据Hotel
2)将Hotel封装为HotelDoc
3)将HotelDoc序列化为JSON
4)创建IndexRequest,指定索引库名和id
5)准备请求参数,也就是JSON文档
6)发送请求

import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
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;


@SpringBootTest
public class HotelDocumentTest {

    @Autowired
    private IHotelService iHotelService;

    //RestHighLevelClient初始化去操作es
    private RestHighLevelClient client;

    @BeforeEach
    void setUp(){
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://192.168.98.129:9200")
        ));
    }

    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }

    @Test
    void testAddDocument() throws IOException {

        //根据id查询酒店数据
        //这块是mybatis plus的查询
        Hotel hotel = iHotelService.getById(61083L);
        //将数据库类型转换为索引库文档类型
        HotelDoc hotelDoc = new HotelDoc(hotel);
        //1,创建request对象 hotel指索引库名称
        IndexRequest request = new IndexRequest("hotel").id(hotel.getId().toString());
        //2,准备Json文档
        //JSON.toJSONString将对象转换成json类型字符串
        request.source(JSON.toJSONString(hotelDoc),XContentType.JSON);
        //3,发送请求
        //indices()返回的是索引库操作的所有方法
        client.index(request,RequestOptions.DEFAULT);
    }
}

查询文档

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

import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpHost;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
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;


@SpringBootTest
public class HotelDocumentTest {

    @BeforeEach
    void setUp(){
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://192.168.98.129:9200")
        ));
    }

    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }

    @Test
    void testGetDocument() throws IOException {

        //1,创建request对象 hotel指索引库名称
        GetRequest request = new GetRequest("hotel","61083");
        //2,发送请求,得到相应
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        //3,解析响应结果
        String json = response.getSourceAsString();
        //将json字符串反序列化为HotelDoc对象
        HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
        System.out.println(hotelDoc);
    }
}

更新文档

全量修改:本质是先根据id删除,再新增

在RestClient的API中,全量修改与新增的API完全一致,判断依据是ID:
如果新增时,ID已经存在,则修改
如果新增时,ID不存在,则新增

增量修改:修改文档中的指定字段值

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

@SpringBootTest
public class HotelDocumentTest {

    //RestHighLevelClient初始化去操作es
    private RestHighLevelClient client;

    @BeforeEach
    void setUp(){
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://192.168.98.129:9200")
        ));
    }

    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }
    
    @Test
    void testUpdateDocument() throws IOException {

        //1,创建request对象 hotel指索引库名称
        UpdateRequest request = new UpdateRequest("hotel","61083");
        //2,准备请求参数
        request.doc(
                "city","西安",
                "starName","四钻"
        );
        //3,发送请求
        client.update(request,RequestOptions.DEFAULT);
    }
}

删除文档

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

@SpringBootTest
public class HotelDocumentTest {

    //RestHighLevelClient初始化去操作es
    private RestHighLevelClient client;

    @BeforeEach
    void setUp(){
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://192.168.98.129:9200")
        ));
    }

    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }
    
    @Test
    void testDeleteDocument() throws IOException {

        //1,创建request对象 hotel指索引库名称
        DeleteRequest request = new DeleteRequest("hotel","61083");
        //2,发送请求
        client.delete(request,RequestOptions.DEFAULT);
    }
}

批量导入文档

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

@SpringBootTest
public class HotelDocumentTest {

    @Autowired
    private IHotelService iHotelService;

    //RestHighLevelClient初始化去操作es
    private RestHighLevelClient client;

    @BeforeEach
    void setUp(){
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://192.168.98.129:9200")
        ));
    }

    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }
    
    @Test
    void testBulkDocument() throws IOException {

        //1,批处理查询酒店数据
        //利用mybatis-plus查询酒店数据
        List<Hotel> hotels = iHotelService.list();
        //2,创建request
        BulkRequest request = new BulkRequest();
        //3,准备参数,添加多个新增的request
        for (Hotel hotel : hotels) {
        	//将查询到的酒店数据(Hotel)转换为文档类型数据(HotelDoc)
            HotelDoc hotelDoc = new HotelDoc(hotel);
            //4,创建新增文档的request对象
            //利用JavaRestClient中的BulkRequest批处理,实现批量新增文档
            //批量处理BulkRequest,其本质就是将多个普通的CRUD请求组合在一起发送
            request.add(new IndexRequest("hotel")
                    .id(hotel.getId().toString())
                    .source(JSON.toJSONString(hotelDoc),XContentType.JSON));
        }
        client.bulk(request,RequestOptions.DEFAULT);
    }
}

DSL查询文档

Elasticsearch提供了基于JSON的DSL(Domain Specific Language)来定义查询。常见的查询类型包括:

查询所有:查询出所有数据,一般测试用。例如:match_all
全文检索(full text)查询:利用分词器对用户输入内容分词,然后去倒排索引库中匹配。例如:
match_query
multi_match_query
精确查询:根据精确词条值查找数据,一般是查找keyword、数值、日期、boolean等类型字段。例如:
ids
range
term
地理(geo)查询:根据经纬度查询。例如:
geo_distance
geo_bounding_box
复合(compound)查询:复合查询可以将上述各种查询条件组合起来,合并查询条件。例如:
bool
function_score
查询的语法基本一致

GET /indexName/_search
{
  "query": {
    "查询类型": {
      "查询条件": "条件值"
    }
  }
}

以查询所有为例
# 查询所有
GET /hotel/_search
{
  "query": {
    "match_all": {}
  }
}

全文检索查询

match查询:单字段查询
multi_match查询:多字段查询,任意一个字段符合条件就算符合查询条件

match查询语法如下:

GET /indexName/_search
{
  "query": {
    "match": {
      "FIELD": "TEXT"
    }
  }
}

# match查询
GET /hotel/_search
{
  "query": {
    "match": {
      "all": "如家外滩"
    }
  }
}

mulit_match语法如下:

GET /indexName/_search
{
  "query": {
    "multi_match": {
      "query": "TEXT",
      "fields": ["FIELD1", " FIELD12"]
    }
  }
}

# multi_match查询
GET /hotel/_search
{
  "query": {
    "multi_match": {
      "query": "如家外滩",
      "fields": ["brand","business","name"]
    }
  }
}

将brand、name、business值都利用copy_to复制到了all字段中。因此你根据三个字段搜索,和根据all字段搜索效果当然一样了。
但是,搜索字段越多,对查询性能影响越大,因此建议采用copy_to,然后单字段查询的方式。

精准查询

精确查询一般是查找keyword、数值、日期、boolean等类型字段。所以不会对搜索条件分词。常见的有:

term:根据词条精确值查询

查询时,用户输入的内容跟自动值完全匹配时才认为符合条件。如果用户输入的内容过多,反而搜索不到数据

// term查询
GET /indexName/_search
{
  "query": {
    "term": {
      "FIELD": {
        "value": "VALUE"
      }
    }
  }
}

# term查询 精确匹配
GET /hotel/_search
{
  "query": {
    "term": {
      "city": {
        "value": "上海"
      }
    }
  }
}

range:根据值的范围查询

范围查询,一般应用在对数值类型做范围过滤的时候。比如做价格范围过滤

// range查询
GET /indexName/_search
{
  "query": {
    "range": {
      "FIELD": {
        "gte": 10, // 这里的gte代表大于等于,gt则代表大于
        "lte": 20 // lte代表小于等于,lt则代表小于
      }
    }
  }
}

# range查询 范围匹配
GET /hotel/_search
{
  "query": {
    "range": {
      "price": {
        "gte": 100,
        "lte": 400
      }
    }
  }
}

地理坐标查询

矩形范围查询

// geo_bounding_box查询
GET /indexName/_search
{
  "query": {
    "geo_bounding_box": {
      "FIELD": {
        "top_left": { // 左上点
          "lat": 31.1,
          "lon": 121.5
        },
        "bottom_right": { // 右下点
          "lat": 30.9,
          "lon": 121.7
        }
      }
    }
  }
}

距离查询(geo_distance)

附近查询,也叫做距离查询(geo_distance):查询到指定中心点小于某个距离值的所有文档;在地图上找一个点作为圆心,以指定距离为半径,画一个圆,落在圆内的坐标都算符合条件

语法说明:
// geo_distance 查询
GET /indexName/_search
{
  "query": {
    "geo_distance": {
      "distance": "15km", // 半径
      "FIELD": "31.21,121.5" // 圆心
    }
  }
}

示例:
# distance查询
GET /hotel/_search
{
  "query": {
    "geo_distance": {
      "distance": "15km",
      "location": "31.21, 121.5"
    }
  }
}

复合查询

复合(compound)查询:复合查询可以将其它简单查询组合起来,实现更复杂的搜索逻辑。常见的有两种:
fuction score:算分函数查询,可以控制文档相关性算分,控制文档排名
bool query:布尔查询,利用逻辑关系组合多个其它的查询,实现复杂搜索

相关性算分

elasticsearch会根据词条和文档的相关度做打分,算法由两种:
TF-IDF算法
BM25算法,elasticsearch5.1版本后采用的算法

function score 查询

你搜索的结果中,并不是相关度越高排名越靠前,而是谁掏的钱多排名就越靠前
要想认为控制相关性算分,就需要利用elasticsearch中的function score 查询了
在这里插入图片描述
unction score 查询中包含四部分内容:
原始查询条件:query部分,基于这个条件搜索文档,并且基于BM25算法给文档打分,原始算分(query score)
过滤条件:filter部分,符合该条件的文档才会重新算分
算分函数:符合filter条件的文档要根据这个函数做运算,得到的函数算分(function score),有四种函数
weight:函数结果是常量
field_value_factor:以文档中的某个字段值作为函数结果
random_score:以随机数作为函数结果
script_score:自定义算分函数算法
运算模式:算分函数的结果、原始查询的相关性算分,两者之间的运算方式,包括:
multiply:相乘
replace:用function score替换query score
其它,例如:sum、avg、max、min

function score query定义的三要素是什么?
过滤条件:哪些文档要加分
算分函数:如何计算function score
加权方式:function score 与 query score如何运算

DSL语句如下
GET /hotel/_search
{
  "query": {
    "function_score": {
      "query": {  .... }, // 原始查询,可以是任意条件
      "functions": [ // 算分函数
        {
          "filter": { // 满足的条件,品牌必须是如家
            "term": {
              "brand": "如家"
            }
          },
          "weight": 2 // 算分权重为2
        }
      ],
      "boost_mode": "sum" // 加权模式,求和
    }
  }
}

# 给如家的查询结果加10分
# function_score查询
GET /hotel/_search
{
  "query": {
    "function_score": {
      "query": {"match": {
        "all": "外滩"
      }},
      "functions": [
        {
          "filter": {
            "term": {
              "brand": "如家"
            }
          },
          "weight": 10
        }
      ],
      "boost_mode": "sum"
    }
  }
}

布尔查询

布尔查询是一个或多个查询子句的组合,每一个子句就是一个子查询。子查询的组合方式有:
must:必须匹配每个子查询,类似“与”
should:选择性匹配子查询,类似“或”
must_not:必须不匹配,不参与算分,类似“非”
filter:必须匹配,不参与算分

搜索时,参与打分的字段越多,查询的性能也越差。因此这种多条件查询时,建议这样做:
搜索框的关键字搜索,是全文检索查询,使用must查询,参与算分
其它过滤条件,采用filter查询。不参与算分

需求:搜索名字包含“如家”,价格不高于400,在坐标31.21,121.5周围10km范围内的酒店
- 名称搜索,属于全文检索查询,应该参与算分。放到must中
- 价格不高于400,用range查询,属于过滤条件,不参与算分。放到must_not中
- 周围10km范围内,用geo_distance查询,属于过滤条件,不参与算分。放到filter中
# 布尔查询
GET /hotel/_search
{
  "query": {
    "bool": {
      "must": [
        {"match": {
          "name": "如家"
        }}
      ],
      "must_not": [
        {"range": {
          "price": {
            "gt": 400
          }
        }}
      ],
      "filter": [
        {"geo_distance": {
          "distance": "10km",
          "location": {
            "lat": 31.21,
            "lon": 121.5
          }
        }}
      ]
    }
  }
}

排序

elasticsearch默认是根据相关度算分(_score)来排序,但是也支持自定义方式对搜索结果排序。可以排序字段类型有:keyword类型、数值类型、地理坐标类型、日期类型等。
排序默认不会对查询结果进行打分

标题普通字段排序

keyword、数值、日期类型排序的语法基本一致。

GET /indexName/_search
{
  "query": {
    "match_all": {}
  },
  "sort": [
    {
      "FIELD": "desc"  // 排序字段、排序方式ASC、DESC
    }
  ]
}

# sort排序
# 先按评分降序,再按价格升序排序
GET /hotel/_search
{
  "query": {"match_all": {}},
  "sort": [
    {
      "score": "desc"
    },
    {
      "price": "asc"
    }
  ]
}

地理坐标排序

GET /indexName/_search
{
  "query": {
    "match_all": {}
  },
  "sort": [
    {
      "_geo_distance" : {
          "FIELD" : "纬度,经度", // 文档中geo_point类型的字段名、目标坐标点
          "order" : "asc", // 排序方式
          "unit" : "km" // 排序的距离单位
      }
    }
  ]
}

# 找到12,31周围的酒店,距离升序排序
GET /hotel/_search
{
  "query": {"match_all": {}},
  "sort": [
    {
      "_geo_distance": {
        "location": {
          "lat": 31,
          "lon": 121
        },
        "order": "asc",
        "unit": "km"
      }
    }
  ]
}

分页

elasticsearch 默认情况下只返回top10的数据。而如果要查询更多数据就需要修改分页参数了。elasticsearch中通过修改from、size参数来控制要返回的分页结果:
from:从第几个文档开始
size:总共查询几个文档
类似于mysql中的limit ?, ?

基本的分页

分页的基本语法如下:
GET /hotel/_search
{
  "query": {
    "match_all": {}
  },
  "from": 0, // 分页开始的位置,默认为0
  "size": 10, // 期望获取的文档总数
  "sort": [
    {"price": "asc"}
  ]
}

# 分页查询
GET /hotel/_search
{
  "query": {"match_all": {}},
  "sort": [
    {
      "price": "asc"
    }
  ],
  "from": 0,
  "size": 20
}

深度分页问题

查询第990~第1000条数据,elasticsearch内部分页时,必须先查询 0~1000条,然后截取其中的990 ~ 1000的这10条
elasticsearch一定是集群,例如我集群有5个节点,我要查询TOP1000的数据,并不是每个节点查询200条就可以了。
因为节点A的TOP200,在另一个节点可能排到10000名以外了。
因此要想获取整个集群的TOP1000,必须先查询出每个节点的TOP1000,汇总结果后,重新排名,重新截取TOP1000。
针对深度分页,ES提供了两种解决方案
search after:分页时需要排序,原理是从上一次的排序值开始,查询下一页数据。官方推荐使用的方式。
scroll:原理将排序后的文档id形成快照,保存在内存。官方已经不推荐使用。

分页查询的常见实现方案以及优缺点:

  • from + size
    优点:支持随机翻页
    缺点:深度分页问题,默认查询上限(from + size)是10000
    场景:百度、京东、谷歌、淘宝这样的随机翻页搜索

  • after search
    优点:没有查询上限(单次查询的size不超过10000)
    缺点:只能向后逐页查询,不支持随机翻页
    场景:没有随机翻页需求的搜索,例如手机向下滚动翻页

  • scroll
    优点:没有查询上限(单次查询的size不超过10000)
    缺点:会有额外内存消耗,并且搜索结果是非实时的
    场景:海量数据的获取和迁移。从ES7.1开始不推荐,建议用 after search方案。

高亮

高亮的语法
GET /hotel/_search
{
  "query": {
    "match": {
      "FIELD": "TEXT" // 查询条件,高亮一定要使用全文检索查询
    }
  },
  "highlight": {
    "fields": { // 指定要高亮的字段
      "FIELD": {
        "pre_tags": "<em>",  // 用来标记高亮字段的前置标签
        "post_tags": "</em>" // 用来标记高亮字段的后置标签
      }
    }
  }
}

- 高亮是对关键字高亮,因此**搜索条件必须带有关键字**,而不能是范围这样的查询。
- 默认情况下,**高亮的字段,必须与搜索指定的字段一致**,否则无法高亮
- 如果要对非搜索字段高亮,则需要添加一个属性:required_field_match=false

# 示例
# 高亮查询,默认情况下,es搜索字段必须与高亮字段一致
# require_field_match指查询字段是否与高亮字段匹配
GET /hotel/_search
{
  "query": {"match": {
    "all": "如家"
  }},
  "highlight": {
    "fields": {"name": {"require_field_match": "false"}}
  }
}

在这里插入图片描述

RestClient查询文档

第一步,创建SearchRequest对象,指定索引库名
第二步,利用request.source()构建DSL,DSL中可以包含查询、分页、排序、高亮等
query():代表查询条件,利用QueryBuilders.matchAllQuery()构建一个match_all查询的DSL
第三步,利用client.search()发送请求,得到响应

elasticsearch返回的结果是一个JSON字符串,结构包含:
- `hits`:命中的结果
  - `total`:总条数,其中的value是具体的总条数值
  - `max_score`:所有结果中得分最高的文档的相关性算分
  - `hits`:搜索结果的文档数组,其中的每个文档都是一个json对象
    - `_source`:文档中的原始数据,也是json对象

因此,我们解析响应结果,就是逐层解析JSON字符串,流程如下:

- `SearchHits`:通过response.getHits()获取,就是JSON中的最外层的hits,代表命中的结果
  - `SearchHits#getTotalHits().value`:获取总条数信息
  - `SearchHits#getHits()`:获取SearchHit数组,也就是文档数组
    - `SearchHit#getSourceAsString()`:获取文档结果中的_source,也就是原始的json文档数据
@SpringBootTest
public class HotelSearchTest {

    //RestHighLevelClient初始化去操作es
    private RestHighLevelClient client;

    @BeforeEach
    void setUp(){
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://192.168.98.129:9200")
        ));
    }

    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }

	@Test
	void testMatchAll() throws IOException {
	    // 1.准备Request
	    SearchRequest request = new SearchRequest("hotel");
	    // 2.准备DSL
	    request.source()
	        .query(QueryBuilders.matchAllQuery());
	    // 3.发送请求
	    SearchResponse response = client.search(request, RequestOptions.DEFAULT);
	
	    // 4.解析响应
	    handleResponse(response);
	}
	
	private void handleResponse(SearchResponse response) {
	    // 4.解析响应
	    SearchHits searchHits = response.getHits();
	    // 4.1.获取总条数
	    long total = searchHits.getTotalHits().value;
	    System.out.println("共搜索到" + total + "条数据");
	    // 4.2.文档数组
	    SearchHit[] hits = searchHits.getHits();
	    // 4.3.遍历
	    for (SearchHit hit : hits) {
	        // 获取文档source
	        String json = hit.getSourceAsString();
	        // 反序列化
	        HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
	        System.out.println("hotelDoc = " + hotelDoc);
	    }
	}
}

match查询

全文检索的match和multi_match查询与match_all的API基本一致。差别是查询条件,也就是query的部分。
在这里插入图片描述

@SpringBootTest
public class HotelSearchTest {

    //RestHighLevelClient初始化去操作es
    private RestHighLevelClient client;

    @BeforeEach
    void setUp(){
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://192.168.98.129:9200")
        ));
    }

    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }

    @Test
    void testMatch() throws IOException {

        //1,准备request
        SearchRequest request = new SearchRequest("hotel");
        //2,准备dsl
        request.source().query(QueryBuilders.matchQuery("all","如家"));
        //3,发送请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        //4,解析相应
        SearchHits searchHits = response.getHits();
        //4.1,获取总条数
        long value = searchHits.getTotalHits().value;
        System.out.println(value);
        //4.2文档数组
        SearchHit[] hits = searchHits.getHits();
        //4.3遍历
        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            //反序列化
            HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
            System.out.println(hotelDoc);
        }
    }

精确查询term,range

精确查询主要是两者:
term:词条精确匹配
range:范围查询
与之前的查询相比,差异同样在查询条件,其它都一样。
查询条件构造的API如下:
在这里插入图片描述

布尔查询

布尔查询是用must、must_not、filter等方式组合其它查询,代码示例如下:
在这里插入图片描述
可以看到,API与其它查询的差别同样是在查询条件的构建,QueryBuilders,结果解析等其他代码完全不变。

@SpringBootTest
public class HotelSearchTest {

    //RestHighLevelClient初始化去操作es
    private RestHighLevelClient client;

    @BeforeEach
    void setUp(){
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://192.168.98.129:9200")
        ));
    }

    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }

    @Test
    void testBool() throws IOException {

        //1,准备request
        SearchRequest request = new SearchRequest("hotel");
        //2,准备dsl
        //2.1,准备boolQuery
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //2.2添加term
        boolQuery.must(QueryBuilders.termQuery("name","上海"));
        //2.3添加range
        boolQuery.filter(QueryBuilders.rangeQuery("price").lte(250));

        request.source().query(boolQuery);
        //3,发送请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        //4,解析相应
        SearchHits searchHits = response.getHits();
        //4.1,获取总条数
        long value = searchHits.getTotalHits().value;
        System.out.println(value);
        //4.2文档数组
        SearchHit[] hits = searchHits.getHits();
        //4.3遍历
        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            //反序列化
            HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
            System.out.println(hotelDoc);
        }
    }
}

排序、分页

搜索结果的排序和分页是与query同级的参数,因此同样是使用request.source()来设置。
对应的API如下:
在这里插入图片描述
完整代码示例:

@SpringBootTest
public class HotelSearchTest {

    //RestHighLevelClient初始化去操作es
    private RestHighLevelClient client;

    @BeforeEach
    void setUp(){
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://192.168.98.129:9200")
        ));
    }

    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }

    @Test
    void testPageAndSort() throws IOException {

        int page = 1;
        int size = 5;

        //1,准备request
        SearchRequest request = new SearchRequest("hotel");
        //2,准备dsl
        //2.1query
        request.source().query(QueryBuilders.matchAllQuery());
        //2.2排序 sort
        request.source().sort("price",SortOrder.ASC);
        //2.3分页 from,size
        request.source().from((page-1)*size).size(size);
        //3,发送请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        //4,解析相应
        SearchHits searchHits = response.getHits();
        //4.1,获取总条数
        long value = searchHits.getTotalHits().value;
        System.out.println(value);
        //4.2文档数组
        SearchHit[] hits = searchHits.getHits();
        //4.3遍历
        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            //反序列化
            HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
            System.out.println(hotelDoc);
        }
    }
   
}

高亮

高亮请求的构建API
在这里插入图片描述
高亮结果解析
第一步:从结果中获取source。hit.getSourceAsString(),这部分是非高亮结果,json字符串。还需要反序列为HotelDoc对象
第二步:获取高亮结果。hit.getHighlightFields(),返回值是一个Map,key是高亮字段名称,值是HighlightField对象,代表高亮值
第三步:从map中根据高亮字段名称,获取高亮字段值对象HighlightField
第四步:从HighlightField中获取Fragments,并且转为字符串。这部分就是真正的高亮字符串了
第五步:用高亮的结果替换HotelDoc中的非高亮结果
在这里插入图片描述
完整代码如下:

@SpringBootTest
public class HotelSearchTest {

    @Autowired
    private IHotelService iHotelService;

    //RestHighLevelClient初始化去操作es
    private RestHighLevelClient client;

    @BeforeEach
    void setUp(){
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://192.168.98.129:9200")
        ));
    }

    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }

    @Test
    void testHighlight() throws IOException {

        //1,准备request
        SearchRequest request = new SearchRequest("hotel");
        //2,准备dsl
        //2.1 query
        request.source().query(QueryBuilders.matchQuery("all","如家"));
        //2.2高亮
        request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));
        //3,发送请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        
        //4,解析相应
        SearchHits searchHits = response.getHits();
        //4.1,获取总条数
        long value = searchHits.getTotalHits().value;
        System.out.println(value);
        //4.2文档数组
        SearchHit[] hits = searchHits.getHits();
        //4.3遍历
        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            //反序列化
            HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);

            //获得高亮结果
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();

            //highlightFields非空判断
            if(!org.springframework.util.CollectionUtils.isEmpty(highlightFields)){
                //根据字段名称获取高亮结果
                HighlightField highlightField = highlightFields.get("name");
                if(highlightField != null){
                    //获取高亮值
                    String name = highlightField.getFragments()[0].toString();
                    //覆盖非高亮结果
                    hotelDoc.setName(name);
                }
            }
            System.out.println("hotelDoc = " + hotelDoc);
        }
    }
}

酒店搜索和分页

我们这个请求的信息如下:
请求方式:POST
请求路径:/hotel/list
请求参数:JSON对象,包含4个字段:
key:搜索关键字
page:页码
size:每页大小
sortBy:排序,目前暂不实现
返回值:分页查询,需要返回分页结果PageResult,包含两个属性:
total:总条数
List<HotelDoc>:当前页的数据

因此,我们实现业务的流程如下:
步骤一:定义实体类,接收请求参数的JSON对象
步骤二:编写controller,接收页面的请求
步骤三:编写业务实现,利用RestHighLevelClient实现搜索、分页

1,定义实体类

前端请求的json结构如下

{
    "key": "搜索关键字",
    "page": 1,
    "size": 3,
    "sortBy": "default"
}

我们在cn.ben.hotel.pojo包下定义一个实体类

import lombok.Data;

@Data
public class RequestParams {
    private String key;
    private Integer page;
    private Integer size;
    private String sortBy;
}

2,返回值

分页查询,需要返回分页结果PageResult,包含两个属性:
total:总条数
List<HotelDoc>:当前页的数据
因此,我们在cn.ben.hotel.pojo中定义返回结果:

import lombok.Data;
import java.util.List;

@Data
public class PageResult {
    private Long total;
    private List<HotelDoc> hotels;

    public PageResult() {
    }

    public PageResult(Long total, List<HotelDoc> hotels) {
        this.total = total;
        this.hotels = hotels;
    }
}

3,定义controller

定义一个HotelController,声明查询接口,满足下列要求:

请求方式:Post
请求路径:/hotel/list
请求参数:对象,类型为RequestParam
返回值:PageResult,包含两个属性
Long total:总条数
List<HotelDoc> hotels:酒店数据
因此,我们在cn.ben.hotel.web中定义HotelController

@RestController
@RequestMapping("/hotel")
public class HotelController {

    @Autowired
    private IHotelService hotelService;
	// 搜索酒店数据
    @PostMapping("/list")
    public PageResult search(@RequestBody RequestParams params){
        return hotelService.search(params);
    }
}

4,实现搜索业务

我们在controller调用了IHotelService,并没有实现该方法,因此下面我们就在IHotelService中定义方法,并且去实现业务逻辑。
1)在cn.ben.hotel.service中的IHotelService接口中定义一个方法:

/**
 * 根据关键字搜索酒店信息
 * @param params 请求参数对象,包含用户输入的关键字 
 * @return 酒店文档列表
 */
PageResult search(RequestParams params);

2)实现搜索业务,肯定离不开RestHighLevelClient,我们需要把它注册到Spring中作为一个Bean。在cn.ben.hotel中的HotelDemoApplication中声明这个Bean:

@Bean
public RestHighLevelClient client(){
    return  new RestHighLevelClient(RestClient.builder(
        HttpHost.create("http://192.168.150.101:9200")
    ));
}

3)在cn.ben.hotel.service.impl中的HotelService中实现search方法:

@Override
public PageResult search(RequestParams params) {
    try {
        // 1.准备Request
        SearchRequest request = new SearchRequest("hotel");
        // 2.准备DSL
        // 2.1.query
        String key = params.getKey();
        if (key == null || "".equals(key)) {
            boolQuery.must(QueryBuilders.matchAllQuery());
        } else {
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        }

		 //设置查询条件
         request.source().query(boolQuery);

        // 2.2.分页
        int page = params.getPage();
        int size = params.getSize();
        request.source().from((page - 1) * size).size(size);

        // 3.发送请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        // 4.解析响应
        return handleResponse(response);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

// 结果解析
private PageResult handleResponse(SearchResponse response) {
    // 4.解析响应
    SearchHits searchHits = response.getHits();
    // 4.1.获取总条数
    long total = searchHits.getTotalHits().value;
    // 4.2.文档数组
    SearchHit[] hits = searchHits.getHits();
    // 4.3.遍历
    List<HotelDoc> hotels = new ArrayList<>();
    for (SearchHit hit : hits) {
        // 获取文档source
        String json = hit.getSourceAsString();
        // 反序列化
        HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
		// 放入集合
        hotels.add(hotelDoc);
    }
    // 4.4.封装返回
    return new PageResult(total, hotels);
}

酒店结果过滤

包含的过滤条件有:
brand:品牌值
city:城市
minPrice~maxPrice:价格范围
starName:星级

我们需要做两件事情:
修改请求参数的对象RequestParams,接收上述参数
修改业务逻辑,在搜索条件之外,添加一些过滤条件

修改实体类

实体类RequestParams

@Data
public class RequestParams {
    private String key;
    private Integer page;
    private Integer size;
    private String sortBy;
    // 下面是新增的过滤条件参数
    private String city;
    private String brand;
    private String starName;
    private Integer minPrice;
    private Integer maxPrice;
}

修改搜索业务

在HotelService的search方法中,只有一个地方需要修改:requet.source().query( … )其中的查询条件。
在之前的业务中,只有match查询,根据关键字搜索,现在要添加条件过滤,包括:
品牌过滤:是keyword类型,用term查询
星级过滤:是keyword类型,用term查询
价格过滤:是数值类型,用range查询
城市过滤:是keyword类型,用term查询
多个查询条件组合,肯定是boolean查询来组合:

关键字搜索放到must中,参与算分
其它过滤条件放到filter中,不参与算分
因为条件构建的逻辑比较复杂,这里先封装为一个函数:

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public PageResult search(RequestParams requestParams) {
        try {
            // 1.准备Request
            SearchRequest request = new SearchRequest("hotel");
            //2,准备DSL
            //2.1,构建boolQuery
            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
            // 2.准备请求参数
            // 2.1.query
            String key = requestParams.getKey();
            if (key == null || "".equals(key)) {
                boolQuery.must(QueryBuilders.matchAllQuery());
            } else {
                boolQuery.must(QueryBuilders.matchQuery("all", key));
            }
             // 1.3.城市
            String city = requestParams.getCity();
            if (StringUtils.isNotBlank(city)) {
                boolQuery.filter(QueryBuilders.termQuery("city",requestParams.getCity()));
            }
            // 1.2.品牌
            String brand = requestParams.getBrand();
            if (StringUtils.isNotBlank(brand)) {
                boolQuery.filter(QueryBuilders.termQuery("brand",requestParams.getBrand()));
            }
            // 1.4.星级
            String starName = requestParams.getStarName();
            if (StringUtils.isNotBlank(starName)) {
                boolQuery.filter(QueryBuilders.termQuery("starName",requestParams.getStarName()));
            }
            // 1.5.价格范围
            Integer minPrice = requestParams.getMinPrice();
            Integer maxPrice = requestParams.getMaxPrice();
            if (minPrice!=null && maxPrice!=null){
                boolQuery.filter(
                        QueryBuilders.rangeQuery("price")
                        .lte(requestParams.getMaxPrice())
                        .gte(requestParams.getMinPrice()));
            }
            
            // 7.放入source
    		request.source().query(boolQuery);
    		
            // 2.2.分页
            int page = requestParams.getPage();
            int size = requestParams.getSize();
            request.source().from((page - 1) * size).size(size);

            // 3.发送请求
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            // 4.解析响应
            return handleResponse(response);
        } catch (IOException e) {
            throw new RuntimeException("搜索数据失败", e);
        }
    }

    // 结果解析
    private PageResult handleResponse(SearchResponse response) {
        // 4.解析响应
        SearchHits searchHits = response.getHits();
        // 4.1.获取总条数
        long total = searchHits.getTotalHits().value;
        // 4.2.文档数组
        SearchHit[] hits = searchHits.getHits();
        // 4.3.遍历
        List<HotelDoc> hotels = new ArrayList<>();
        for (SearchHit hit : hits) {
            // 获取文档source
            String json = hit.getSourceAsString();
            // 反序列化
            HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
            // 放入集合
            hotels.add(hotelDoc);
        }
        // 4.4.封装返回
        return new PageResult(total, hotels);
    }

}

附近的酒店

需求分析

在酒店列表页的右侧,有一个小地图,点击地图的定位按钮,地图会找到你所在的位置;并且,在前端会发起查询请求,将你的坐标发送到服务端:
在这里插入图片描述
基于这个location坐标,然后按照距离对周围酒店排序。实现思路如下:
修改RequestParams参数,接收location字段
修改search方法业务逻辑,如果location有值,添加根据geo_distance排序的功能

修改实体类

修改在cn.ben.hotel.pojo包下的实体类RequestParams:

package cn.itcast.hotel.pojo;

import lombok.Data;

@Data
public class RequestParams {
    private String key;
    private Integer page;
    private Integer size;
    private String sortBy;
    private String city;
    private String brand;
    private String starName;
    private Integer minPrice;
    private Integer maxPrice;
    // 我当前的地理坐标
    private String location;
}

距离排序API

地理坐标排序只学过DSL语法,如下:

GET /indexName/_search
{
  "query": {
    "match_all": {}
  },
  "sort": [
    {
      "price": "asc"  
    },
    {
      "_geo_distance" : {
          "FIELD" : "纬度,经度",
          "order" : "asc",
          "unit" : "km"
      }
    }
  ]
}

添加距离排序

1,在cn.ben.hotel.service.implHotelServicesearch方法中,添加一个排序功能:
2,我们在结果解析阶段,除了解析source部分以外,还要得到sort部分,也就是排序的距离,然后放到响应结果中。
我们要做两件事:
修改HotelDoc,添加排序距离字段,用于页面显示

@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;
    private Object distance;
}

修改HotelService类中的handleResponse方法,添加对sort值的获取

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public PageResult search(RequestParams requestParams) {
        try {
            // 1.准备Request
            SearchRequest request = new SearchRequest("hotel");
            //2,准备DSL
            //2.1,构建boolQuery
            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
            // 2.准备请求参数
            // 2.1.query
            String key = requestParams.getKey();
            if (key == null || "".equals(key)) {
                boolQuery.must(QueryBuilders.matchAllQuery());
            } else {
                boolQuery.must(QueryBuilders.matchQuery("all", key));
            }
            // 1.3.城市
            String city = requestParams.getCity();
            if (StringUtils.isNotBlank(city)) {
                boolQuery.filter(QueryBuilders.termQuery("city",requestParams.getCity()));
            }
            // 1.2.品牌
            String brand = requestParams.getBrand();
            if (StringUtils.isNotBlank(brand)) {
                boolQuery.filter(QueryBuilders.termQuery("brand",requestParams.getBrand()));
            }
            // 1.4.星级
            String starName = requestParams.getStarName();
            if (StringUtils.isNotBlank(starName)) {
                boolQuery.filter(QueryBuilders.termQuery("starName",requestParams.getStarName()));
            }
            // 1.5.价格范围
            Integer minPrice = requestParams.getMinPrice();
            Integer maxPrice = requestParams.getMaxPrice();
            if (minPrice!=null && maxPrice!=null){
                boolQuery.filter(
                        QueryBuilders.rangeQuery("price")
                        .lte(requestParams.getMaxPrice())
                        .gte(requestParams.getMinPrice()));
            }

			//放入source
    		request.source().query(boolQuery);

            // 2.2.分页
            int page = requestParams.getPage();
            int size = requestParams.getSize();
            request.source().from((page - 1) * size).size(size);

            //2.3 地理坐标排序
            String location = requestParams.getLocation();
            if (StringUtils.isNotBlank(location)) {
                request.source().sort(SortBuilders
                        .geoDistanceSort("location", new GeoPoint(location))
                        .order(SortOrder.ASC).unit(DistanceUnit.KILOMETERS));
            }

            // 3.发送请求
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            // 4.解析响应
            return handleResponse(response);
        } catch (IOException e) {
            throw new RuntimeException("搜索数据失败", e);
        }
    }

    // 结果解析
    private PageResult handleResponse(SearchResponse response) {
        // 4.解析响应
        SearchHits searchHits = response.getHits();
        // 4.1.获取总条数
        long total = searchHits.getTotalHits().value;
        // 4.2.文档数组
        SearchHit[] hits = searchHits.getHits();
        // 4.3.遍历
        List<HotelDoc> hotels = new ArrayList<>();
        for (SearchHit hit : hits) {
            // 获取文档source
            String json = hit.getSourceAsString();
            // 反序列化
            HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
            //获取地理坐标排序值
            Object[] sortValues = hit.getSortValues();
            if(sortValues.length>0){
                Object sortValue = sortValues[0];
                hotelDoc.setDistance(sortValue);
            }
            // 放入集合
            hotels.add(hotelDoc);
        }
        // 4.4.封装返回
        return new PageResult(total, hotels);
    }
}

酒店竞价排名

需求:让指定的酒店在搜索结果中排名置顶

function_score查询可以影响算分,算分高了,自然排名也就高了。而function_score包含3个要素:

过滤条件:哪些文档要加分
算分函数:如何计算function score
加权方式:function score 与 query score如何运算

这里的需求是:让指定酒店排名靠前。因此我们需要给这些酒店添加一个标记,这样在过滤条件中就可以根据这个标记来判断,是否要提高算分

比如,我们给酒店添加一个字段:isAD,Boolean类型:
true:是广告
false:不是广告

这样function_score包含3个要素就很好确定了:
过滤条件:判断isAD 是否为true
算分函数:我们可以用最简单暴力的weight,固定加权值
加权方式:可以用默认的相乘,大大提高算分

因此,业务的实现步骤包括:

  1. 给HotelDoc类添加isAD字段,Boolean类型
@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;
    private Object distance;
    private Boolean isAD;
}
  1. 挑选几个你喜欢的酒店,给它的文档数据添加isAD字段,值为true
POST /hotel/_update/1902197537
{
    "doc": {
        "isAD": true
    }
}
POST /hotel/_update/2056126831
{
    "doc": {
        "isAD": true
    }
}
POST /hotel/_update/1989806195
{
    "doc": {
        "isAD": true
    }
}
POST /hotel/_update/2056105938
{
    "doc": {
        "isAD": true
    }
}
  1. 修改search方法,添加function score功能,给isAD值为true的酒店增加权重
import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
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.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public PageResult search(RequestParams requestParams) {
        try {
            // 1.准备Request
            SearchRequest request = new SearchRequest("hotel");
            //2,准备DSL
            //2.1,准备Boolean查询
            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
            // 2.准备请求参数
            // 2.1.关键字搜索,match查询,放到must中
            String key = requestParams.getKey();
            if (key == null || "".equals(key)) {
                boolQuery.must(QueryBuilders.matchAllQuery());
            } else {
                boolQuery.must(QueryBuilders.matchQuery("all", key));
            }
            // 1.3.城市
            String city = requestParams.getCity();
            if (StringUtils.isNotBlank(city)) {
                boolQuery.filter(QueryBuilders.termQuery("city",city));
            }
            // 1.2.品牌
            String brand = requestParams.getBrand();
            if (StringUtils.isNotBlank(brand)) {
                boolQuery.filter(QueryBuilders.termQuery("brand",brand));
            }
            // 1.4.星级
            String starName = requestParams.getStarName();
            if (StringUtils.isNotBlank(starName)) {
                boolQuery.filter(QueryBuilders.termQuery("starName",starName));
            }
            // 1.5.价格范围
            Integer minPrice = requestParams.getMinPrice();
            Integer maxPrice = requestParams.getMaxPrice();
            if (minPrice!=null && maxPrice!=null){
                boolQuery.filter(
                        QueryBuilders.rangeQuery("price")
                        .lte(maxPrice)
                        .gte(minPrice));
            }

            //算分控制
            //给isAD=true的酒店加分
            FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(
                            //原始查询 相关性算分的查询
                            boolQuery,
                    // function score的数组
                    new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                                    //其中的一个function score元素
                           new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                   //过滤条件
                                   QueryBuilders.termQuery("isAD",true),
                                   //算分函数 原始分*10
                                   ScoreFunctionBuilders.weightFactorFunction(10)
                           )
                    });
            // 3.设置查询条件
            request.source().query(functionScoreQuery);

            // 2.2.分页
            int page = requestParams.getPage();
            int size = requestParams.getSize();
            request.source().from((page - 1) * size).size(size);

            //2.3 地理坐标排序
            String location = requestParams.getLocation();
            if (StringUtils.isNotBlank(location)) {
                request.source().sort(SortBuilders
                        .geoDistanceSort("location", new GeoPoint(location))
                        .order(SortOrder.ASC).unit(DistanceUnit.KILOMETERS));
            }

            // 3.发送请求
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            // 4.解析响应
            return handleResponse(response);
        } catch (IOException e) {
            throw new RuntimeException("搜索数据失败", e);
        }
    }

    // 结果解析
    private PageResult handleResponse(SearchResponse response) {
        // 4.解析响应
        SearchHits searchHits = response.getHits();
        // 4.1.获取总条数
        long total = searchHits.getTotalHits().value;
        // 4.2.文档数组
        SearchHit[] hits = searchHits.getHits();
        // 4.3.遍历
        List<HotelDoc> hotels = new ArrayList<>();
        for (SearchHit hit : hits) {
            // 获取文档source
            String json = hit.getSourceAsString();
            // 反序列化,非高亮的
            HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);

            // 4.6.处理高亮结果
            // 1)获取高亮map
            Map<String, HighlightField> map = hit.getHighlightFields();
            if (map != null && !map.isEmpty()) {
                // 2)根据字段名,获取高亮结果
                HighlightField highlightField = map.get("name");
                if (highlightField != null) {
                    // 3)获取高亮结果字符串数组中的第1个元素
                    String hName = highlightField.getFragments()[0].toString();
                    // 4)把高亮结果放到HotelDoc中
                    hotelDoc.setName(hName);
                }
            }

            //获取地理坐标排序值
            Object[] sortValues = hit.getSortValues();
            if(sortValues.length>0){
                Object sortValue = sortValues[0];
                hotelDoc.setDistance(sortValue);
            }
            // 放入集合
            hotels.add(hotelDoc);
        }
        // 4.4.封装返回
        return new PageResult(total, hotels);
    }
}

数据聚合

聚合(aggregations可以让我们极其方便的实现对数据的统计、分析、运算。

聚合的种类

桶(Bucket)聚合:用来对文档做分组
TermAggregation:按照文档字段值分组,例如按照品牌值分组、按照国家分组
Date Histogram:按照日期阶梯分组,例如一周为一组,或者一月为一组

度量(Metric)聚合:用以计算一些值,比如:最大值、最小值、平均值等
Avg:求平均值
Max:求最大值
Min:求最小值
Stats:同时求max、min、avg、sum等
管道(pipeline)聚合:其它聚合的结果为基础做聚合

Bucket聚合语法

GET /hotel/_search
{
  "size": 0,  // 设置size为0,结果中不包含文档,只包含聚合结果
  "aggs": { // 定义聚合
    "brandAgg": { //给聚合起个名字
      "terms": { // 聚合的类型,按照品牌值聚合,所以选择term
        "field": "brand", // 参与聚合的字段
        "size": 20 // 希望获取的聚合结果数量
      }
    }
  }
}

# 聚合功能
GET /hotel/_search
{
  "size": 0,
  "aggs": {
    "brandAgg": {
      "terms": {
        "field": "brand",
        "size": 10
      }
    }
  }
}

默认情况下,Bucket聚合会统计Bucket内的文档数量,记为_count,并且按照_count降序排序。
我们可以指定order属性,自定义聚合的排序方式
# 聚合功能,自定义排序规则
GET /hotel/_search
{
  "size": 0,
  "aggs": {
    "brandAgg": {
      "terms": {
        "field": "brand",
        "size": 10,
        "order": {
          "_count": "asc" // 按照_count升序排列
        }
      }
    }
  }
}

默认情况下,Bucket聚合是对索引库的所有文档做聚合,但真实场景下,用户会输入搜索条件,因此聚合必须是对搜索结果聚合。那么聚合必须添加限定条件。
我们可以限定要聚合的文档范围,只要添加query条件即可:
# 聚合功能,限定聚合范围
GET /hotel/_search
{
  "query": {
    "range": {
      "price": {
        "lte": 200 // 只对200元以下的文档聚合
      }
    }
  }, 
  "size": 0,
  "aggs": {
    "brandAgg": {
      "terms": {
        "field": "brand",
        "size": 10
      }
    }
  }
}

Metric聚合语法

我们对酒店按照品牌分组,形成了一个个桶。现在我们需要对桶内的酒店做运算,获取每个品牌的用户评分的min、max、avg等值。
这就要用到Metric聚合了,例如stat聚合:就可以获取min、max、avg等结果。

GET /hotel/_search
{
  "size": 0, 
  "aggs": {
    "brandAgg": { 
      "terms": { 
        "field": "brand", 
        "size": 20   //size:指定聚合结果数量
      },
      "aggs": { // 是brands聚合的子聚合,也就是分组后对每组分别计算
        "score_stats": { // 聚合名称
          "stats": { // 聚合类型,这里stats可以计算min、max、avg等
            "field": "score" // 聚合字段,这里是score
          }
        }
      }
    }
  }
}


# 嵌套聚合metric
GET /hotel/_search
{
  "size": 0,
  "aggs": {
    "brandAgg": {
      "terms": {
        "field": "brand",
        "size": 10,
        "order": { //order:指定聚合结果排序方式
          "scoreAgg.avg": "desc"
        }
      },
      "aggs": {
        "scoreAgg": {
          "stats": {
            "field": "score"  //field:指定聚合字段
          }
        }
      }
    }
  }
}

RestAPI实现聚合

聚合条件与query条件同级别,因此需要使用request.source()来指定聚合条件。
聚合条件的语法:
在这里插入图片描述
聚合的结果也与查询结果不同,API也比较特殊。不过同样是JSON逐层解析:
在这里插入图片描述

@SpringBootTest
public class HotelSearchTest {

    //RestHighLevelClient初始化去操作es
    private RestHighLevelClient client;

    @BeforeEach
    void setUp(){
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://192.168.98.129:9200")
        ));
    }

    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }

    @Test
    void testAggregation() throws IOException {
        //1,准备request
        SearchRequest request = new SearchRequest("hotel");
        //2,准备DSL
        request.source().size(0); //不需要显示别的搜索结果
        request.source().aggregation(AggregationBuilders
            .terms("brandAgg")
            .field("brand")
            .size(10)
        );
        //3,发起请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        //4,解析结果
        Aggregations aggregations = response.getAggregations();
        //根据聚合名称获取聚合结果
        Terms brandTerms = aggregations.get("brandAgg");
        //获取buckets
        List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            //获取key
            String key = bucket.getKeyAsString();
            System.out.println(key);
        }
    }

}

搜索页面的品牌、城市等信息不应该是在页面写死,而是通过聚合索引库中的酒店数据得来的

cn.ben.hotel.web包的HotelController中添加一个方法,遵循下面的要求:
请求方式:POST
请求路径:/hotel/filters
请求参数:RequestParams,与搜索文档的参数一致
返回值类型:Map<String, List<String>>

@RestController
@RequestMapping("/hotel")
public class HotelController {

    @Autowired
    IHotelService iHotelService;

    @PostMapping("/list")
    public PageResult search(@RequestBody RequestParams requestParams){
        //alt+enter
        return iHotelService.search(requestParams);
    }

    @PostMapping("/filters")
    public Map<String, List<String>> getFilters(@RequestBody RequestParams requestParams){
        //alt+enter
        return iHotelService.filters(requestParams);
    }
}

cn.ben.hotel.service.IHotelService接口中定义新方法:

Map<String, List<String>> filters(RequestParams params);

cn.ben.hotel.service.impl.HotelService中实现该方法:

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public PageResult search(RequestParams requestParams) {
        try {
            // 1.准备Request
            SearchRequest request = new SearchRequest("hotel");
            //2,准备DSL
            buildBasicQuery(requestParams, request);

            // 2.2.分页
            int page = requestParams.getPage();
            int size = requestParams.getSize();
            request.source().from((page - 1) * size).size(size);

            //2.3 地理坐标排序
            String location = requestParams.getLocation();
            if (StringUtils.isNotBlank(location)) {
                request.source().sort(SortBuilders
                        .geoDistanceSort("location", new GeoPoint(location))
                        .order(SortOrder.ASC).unit(DistanceUnit.KILOMETERS));
            }

            // 3.发送请求
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            // 4.解析响应
            return handleResponse(response);
        } catch (IOException e) {
            throw new RuntimeException("搜索数据失败", e);
        }
    }

	//构建基本查询条件
    private void buildBasicQuery(RequestParams requestParams, SearchRequest request) {
        //2.1,准备Boolean查询
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 2.准备请求参数
        // 2.1.关键字搜索,match查询,放到must中
        String key = requestParams.getKey();
        if (key == null || "".equals(key)) {
            boolQuery.must(QueryBuilders.matchAllQuery());
        } else {
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        }
        // 1.3.城市
        String city = requestParams.getCity();
        if (StringUtils.isNotBlank(city)) {
            boolQuery.filter(QueryBuilders.termQuery("city",city));
        }
        // 1.2.品牌
        String brand = requestParams.getBrand();
        if (StringUtils.isNotBlank(brand)) {
            boolQuery.filter(QueryBuilders.termQuery("brand",brand));
        }
        // 1.4.星级
        String starName = requestParams.getStarName();
        if (StringUtils.isNotBlank(starName)) {
            boolQuery.filter(QueryBuilders.termQuery("starName",starName));
        }
        // 1.5.价格范围
        Integer minPrice = requestParams.getMinPrice();
        Integer maxPrice = requestParams.getMaxPrice();
        if (minPrice!=null && maxPrice!=null){
            boolQuery.filter(
                    QueryBuilders.rangeQuery("price")
                    .lte(maxPrice)
                    .gte(minPrice));
        }

        //算分控制
        //给isAD=true的酒店加分
        FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(
                        //原始查询 相关性算分的查询
                        boolQuery,
                // function score的数组
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                                //其中的一个function score元素
                       new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                               //过滤条件
                               QueryBuilders.termQuery("isAD",true),
                               //算分函数 原始分*10
                               ScoreFunctionBuilders.weightFactorFunction(10)
                       )
                });
        // 3.设置查询条件
        request.source().query(functionScoreQuery);
    }


    // 结果解析
    private PageResult handleResponse(SearchResponse response) {
        // 4.解析响应
        SearchHits searchHits = response.getHits();
        // 4.1.获取总条数
        long total = searchHits.getTotalHits().value;
        // 4.2.文档数组
        SearchHit[] hits = searchHits.getHits();
        // 4.3.遍历
        List<HotelDoc> hotels = new ArrayList<>();
        for (SearchHit hit : hits) {
            // 获取文档source
            String json = hit.getSourceAsString();
            // 反序列化,非高亮的
            HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);

            // 4.6.处理高亮结果
            // 1)获取高亮map
            Map<String, HighlightField> map = hit.getHighlightFields();
            if (map != null && !map.isEmpty()) {
                // 2)根据字段名,获取高亮结果
                HighlightField highlightField = map.get("name");
                if (highlightField != null) {
                    // 3)获取高亮结果字符串数组中的第1个元素
                    String hName = highlightField.getFragments()[0].toString();
                    // 4)把高亮结果放到HotelDoc中
                    hotelDoc.setName(hName);
                }
            }

            //获取地理坐标排序值
            Object[] sortValues = hit.getSortValues();
            if(sortValues.length>0){
                Object sortValue = sortValues[0];
                hotelDoc.setDistance(sortValue);
            }
            // 放入集合
            hotels.add(hotelDoc);
        }
        // 4.4.封装返回
        return new PageResult(total, hotels);
    }

	//聚合查询
    @Override
    public Map<String, List<String>> filters(RequestParams requestParams) {
        //1,准备request
        SearchRequest request = new SearchRequest("hotel");
        //2,准备DSL
        //2.1,准备query
        buildBasicQuery(requestParams, request);

        //2.2设置size
        request.source().size(0);
        //2.2 聚合
        buildAggregation(request);
        //3,发起请求
        SearchResponse response = null;
        try {
            response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //4,解析结果
        Map<String, List<String>> result = new HashMap<>();
        Aggregations aggregations = response.getAggregations();
        //根据品牌名称,获取品牌结果
        List<String> brandList = getAggByName(aggregations,"brandAgg");
        //放入map
        result.put("品牌",brandList);

        //根据品牌名称,获取品牌结果
        List<String> cityList = getAggByName(aggregations,"cityAgg");
        //放入map
        result.put("城市",cityList);

        //根据品牌名称,获取品牌结果
        List<String> starNameList = getAggByName(aggregations,"starNameAgg");
        //放入map
        result.put("星级",starNameList);

        return result;
    }

	//聚合结果解析
    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        //根据聚合名称获取聚合结果
        Terms brandTerms = aggregations.get(aggName);
        //获取buckets
        List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();

        List<String> brandList =  new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            //获取key
            String key = bucket.getKeyAsString();
            brandList.add(key);
        }
        return brandList;
    }

	//聚合查询
    private void buildAggregation(SearchRequest request) {
        request.source().aggregation(AggregationBuilders
                .terms("brandAgg")
                .field("brand")
                .size(100)
        );
        request.source().aggregation(AggregationBuilders
                .terms("cityAgg")
                .field("city")
                .size(100)
        );
        request.source().aggregation(AggregationBuilders
                .terms("starNameAgg")
                .field("starName")
                .size(100)
        );
    }

}

自动补全

当用户在搜索框输入字符时,我们应该提示出与该字符有关的搜索项,如图:
在这里插入图片描述
这种根据用户输入的字母,提示完整词条的功能,就是自动补全了。
因为需要根据拼音字母来推断,因此要用到拼音分词功能。

拼音分词器

要实现根据字母做补全,就必须对文档按照拼音分词
拼音分词器安装方式与IK分词器一样,分三步:
①解压
解压拼音分词器本地文件(elasticsearch-analysis-pinyin-7.12.1.zip),重命文件名为py
②上传到虚拟机中,elasticsearch的plugin目录

/var/lib/docker/volumes/es-plugins/_data

③重启elasticsearch

docker restart es

④测试

POST /_analyze
{
  "text": "如家酒店还不错",
  "analyzer": "pinyin"
}

自定义分词器

默认的拼音分词器会将每个汉字单独分为拼音,而我们希望的是每个词条形成一组拼音,需要对拼音分词器做个性化定制,形成自定义分词器。

elasticsearch中分词器(analyzer)的组成包含三部分:
character filters:在tokenizer之前对文本进行处理。例如删除字符、替换字符
tokenizer:将文本按照一定的规则切割成词条(term)。例如keyword,就是不分词;还有ik_smart
tokenizer filter:将tokenizer输出的词条做进一步处理。例如大小写转换、同义词处理、拼音处理等
文档分词时会依次由这三部分来处理文档:
在这里插入图片描述声明自定义分词器的语法如下:

PUT /test
{
  "settings": {
    "analysis": {
      "analyzer": { // 自定义分词器
        "my_analyzer": {  // 分词器名称
          "tokenizer": "ik_max_word",
          "filter": "py"
        }
      },
      "filter": { // 自定义tokenizer filter
        "py": { // 过滤器名称
          "type": "pinyin", // 过滤器类型,这里是pinyin
		  "keep_full_pinyin": false,
          "keep_joined_full_pinyin": true,
          "keep_original": true,
          "limit_first_letter_length": 16,
          "remove_duplicated_term": true,
          "none_chinese_pinyin_tokenize": false
        }
      }
    }
  },
  "mappings": {
    "properties": {
      "name": {
        "type": "text",
        "analyzer": "my_analyzer",
        "search_analyzer": "ik_smart" //为了避免搜索到同音字,搜索时不要使用拼音分词器
      }
    }
  }
}

自动补全查询

elasticsearch提供了Completion Suggester查询来实现自动补全功能。这个查询会匹配以用户输入内容开头的词条并返回。为了提高补全查询的效率,对于文档中字段的类型有一些约束:
参与补全查询的字段必须是completion类型。
字段的内容一般是用来补全的多个词条形成的数组。

比如,一个这样的索引库:

// 创建索引库
PUT test
{
  "mappings": {
    "properties": {
      "title":{
        "type": "completion"
      }
    }
  }
}

然后插入下面的数据:

// 示例数据
POST test/_doc
{
  "title": ["Sony", "WH-1000XM3"]
}
POST test/_doc
{
  "title": ["SK-II", "PITERA"]
}
POST test/_doc
{
  "title": ["Nintendo", "switch"]
}

查询的DSL语句如下:

// 自动补全查询
GET /test/_search
{
  "suggest": {
    "title_suggest": {
      "text": "s", // 关键字
      "completion": {
        "field": "title", // 补全查询的字段
        "skip_duplicates": true, // 跳过重复的
        "size": 10 // 获取前10条结果
      }
    }
  }
}

实现酒店搜索框自动补全

现在,我们的hotel索引库还没有设置拼音分词器,需要修改索引库中的配置。但是我们知道索引库是无法修改的,只能删除然后重新创建。
另外,我们需要添加一个字段,用来做自动补全,将brand、suggestion、city等都放进去,作为自动补全的提示。
因此,总结一下,我们需要做的事情包括:

1,修改酒店映射结构

// 酒店数据索引库
PUT /hotel
{
  "settings": {
    "analysis": {
      "analyzer": {
        "text_anlyzer": {
          "tokenizer": "ik_max_word",
          "filter": "py"
        },
        "completion_analyzer": {
          "tokenizer": "keyword",
          "filter": "py"
        }
      },
      "filter": {
        "py": {
          "type": "pinyin",
          "keep_full_pinyin": false,
          "keep_joined_full_pinyin": true,
          "keep_original": true,
          "limit_first_letter_length": 16,
          "remove_duplicated_term": true,
          "none_chinese_pinyin_tokenize": false
        }
      }
    }
  },
  "mappings": {
    "properties": {
      "id":{
        "type": "keyword"
      },
      "name":{
        "type": "text",
        "analyzer": "text_anlyzer",
        "search_analyzer": "ik_smart",
        "copy_to": "all"
      },
      "address":{
        "type": "keyword",
        "index": false
      },
      "price":{
        "type": "integer"
      },
      "score":{
        "type": "integer"
      },
      "brand":{
        "type": "keyword",
        "copy_to": "all"
      },
      "city":{
        "type": "keyword"
      },
      "starName":{
        "type": "keyword"
      },
      "business":{
        "type": "keyword",
        "copy_to": "all"
      },
      "location":{
        "type": "geo_point"
      },
      "pic":{
        "type": "keyword",
        "index": false
      },
      "all":{
        "type": "text",
        "analyzer": "text_anlyzer",
        "search_analyzer": "ik_smart"
      },
      "suggestion":{
          "type": "completion",
          "analyzer": "completion_analyzer"
      }
    }
  }
}

2,修改HotelDoc实体

HotelDoc中要添加一个字段,用来做自动补全,内容可以是酒店品牌、城市、商圈等信息。按照自动补全字段的要求,最好是这些字段的数组。
因此我们在HotelDoc中添加一个suggestion字段,类型为List<String>,然后将brand、city、business等信息放到里面。

@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;
    private Object distance;
    private Boolean isAD;
    private List<String> suggestion;

    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();
        // 组装suggestion
        if(this.business.contains("/")){
            // business有多个值,需要切割
            String[] arr = this.business.split("/");
            // 添加元素
            this.suggestion = new ArrayList<>();
            this.suggestion.add(this.brand);
            Collections.addAll(this.suggestion, arr);
        }else {
            this.suggestion = Arrays.asList(this.brand, this.business);
        }
    }
}

3,重新导入

重新执行之前编写的导入数据功能,可以看到新的酒店数据中包含了suggestion:

"suggest" : {
    "mysuggestions" : [
      {
        "text" : "hm",
        "offset" : 0,
        "length" : 2,
        "options" : [
          {
            "text" : "华美达",
            "_index" : "hotel",
            "_type" : "_doc",
            "_id" : "47066",
            "_score" : 1.0,
            "_source" : {
              "address" : "施新路958号",
              "brand" : "华美达",
              "business" : "浦东机场核心区",
              "city" : "上海",
              "id" : 47066,
              "location" : "31.147989, 121.759199",
              "name" : "上海浦东东站华美达酒店",
              "pic" : "https://m.tuniucdn.com/fb3/s1/2n9c/2pNujAVaQbXACzkHp8bQMm6zqwhp_w200_h200_c1_t0.jpg",
              "price" : 408,
              "score" : 46,
              "starName" : "四钻",
              "suggestion" : [
                "华美达",
                "浦东机场核心区"
              ]
            }
          }
        ]
      }
    ]
  }

4,自动补全查询的JavaAPI

自动补全查询的DSL,和对应的JavaAPI
在这里插入图片描述
而自动补全的结果也比较特殊,解析的代码如下
在这里插入图片描述

@SpringBootTest
public class HotelSearchTest {

    //RestHighLevelClient初始化去操作es
    private RestHighLevelClient client;

    @BeforeEach
    void setUp(){
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://192.168.98.129:9200")
        ));
    }

    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }
	
	@Test
    void testSuggest() throws IOException {
        //1,准备request
        SearchRequest request = new SearchRequest("hotel");
        //2,准备DSL
        request.source()
                .suggest(new SuggestBuilder().addSuggestion(
                        "suggestions",
                        SuggestBuilders.completionSuggestion("suggestion")
                            .prefix("h")//自动补全h开头的
                            .skipDuplicates(true)
                            .size(10)
                ));
        //3,发起请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        //4,解析结果
        Suggest suggest = response.getSuggest();
        //4.1,根据补全查询名称,获取补全结果
        CompletionSuggestion suggestion = suggest.getSuggestion("suggestions");
        //4.2,获取options
        List<CompletionSuggestion.Entry.Option> options = suggestion.getOptions();
        //4.3,遍历
        for (CompletionSuggestion.Entry.Option option : options) {
            String text = option.getText().toString();
            System.out.println(text);
        }
    }
}

实现搜索框自动补全

查看前端页面,可以发现当我们在输入框键入时,前端会发起ajax请求:
在这里插入图片描述
返回值是补全词条的集合,类型为List<String>
1)在cn.ben.hotel.web包下的HotelController中添加新接口,接收新的请求:

@GetMapping("suggestion")
public List<String> getSuggestions(@RequestParam("key") String prefix) {
    return hotelService.getSuggestions(prefix);
}

2)在cn.ben.hotel.service包下的IhotelService中添加方法:

List<String> getSuggestions(String prefix);

3)在cn.ben.hotel.service.impl.HotelService中实现该方法:

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    
	@Override
    public List<String> getSuggestions(String prefix) {
        //1,准备request
        SearchRequest request = new SearchRequest("hotel");
        //2,准备DSL
        request.source()
                .suggest(new SuggestBuilder().addSuggestion(
                        "suggestions",
                        SuggestBuilders.completionSuggestion("suggestion")
                                .prefix(prefix)//自动补全页面传的字母,比如h开头的
                                .skipDuplicates(true)
                                .size(10)
                ));
        //3,发起请求
        SearchResponse response = null;
        try {
            response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //4,解析结果
        Suggest suggest = response.getSuggest();
        //4.1,根据补全查询名称,获取补全结果
        CompletionSuggestion suggestion = suggest.getSuggestion("suggestions");
        //4.2,获取options
        List<CompletionSuggestion.Entry.Option> options = suggestion.getOptions();
        //4.3,遍历
        ArrayList list = new ArrayList();
        for (CompletionSuggestion.Entry.Option option : options) {
            String text = option.getText().toString();
            list.add(text);
        }
        return list;
    }
}

数据同步

elasticsearch中的酒店数据来自于mysql数据库,因此mysql数据发生改变时,elasticsearch也必须跟着改变,这个就是elasticsearch与mysql之间的数据同步

同步调用

方案一:同步调用
优点:实现简单,粗暴
缺点:业务耦合度高
在这里插入图片描述hotel-demo对外提供接口,用来修改elasticsearch中的数据
酒店管理服务在完成数据库操作后,直接调用hotel-demo提供的接口

异步通知

方案二:异步通知
优点:低耦合,实现难度一般
缺点:依赖mq的可靠性
在这里插入图片描述
hotel-admin对mysql数据库数据完成增、删、改后,发送MQ消息
hotel-demo监听MQ,接收到消息后完成elasticsearch数据修改

1,导入hotel-admin项目:
2,声明交换机、队列

在这里插入图片描述
2.1,引入依赖
在hotel-admin、hotel-demo中引入rabbitmq的依赖:

<!--amqp-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

2.2,声明队列交换机名称
在hotel-admin和hotel-demo中的cn.ben.hotel.constatnts包下新建一个类MqConstants

package cn.ben.hotel.constatnts;

    public class MqConstants {
    /**
     * 交换机
     */
    public final static String HOTEL_EXCHANGE = "hotel.topic";
    /**
     * 监听新增和修改的队列
     */
    public final static String HOTEL_INSERT_QUEUE = "hotel.insert.queue";
    /**
     * 监听删除的队列
     */
    public final static String HOTEL_DELETE_QUEUE = "hotel.delete.queue";
    /**
     * 新增或修改的RoutingKey
     */
    public final static String HOTEL_INSERT_KEY = "hotel.insert";
    /**
     * 删除的RoutingKey
     */
    public final static String HOTEL_DELETE_KEY = "hotel.delete";
}
3,声明队列交换机

在hotel-demo中,定义配置类,声明队列、交换机:

import cn.itcast.hotel.constants.MqConstants;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MqConfig {
    @Bean
    public TopicExchange topicExchange(){
        return new TopicExchange(MqConstants.HOTEL_EXCHANGE, true, false);
    }

    @Bean
    public Queue insertQueue(){
        return new Queue(MqConstants.HOTEL_INSERT_QUEUE, true);
    }

    @Bean
    public Queue deleteQueue(){
        return new Queue(MqConstants.HOTEL_DELETE_QUEUE, true);
    }

    @Bean
    public Binding insertQueueBinding(){
        return BindingBuilder.bind(insertQueue()).to(topicExchange()).with(MqConstants.HOTEL_INSERT_KEY);
    }

    @Bean
    public Binding deleteQueueBinding(){
        return BindingBuilder.bind(deleteQueue()).to(topicExchange()).with(MqConstants.HOTEL_DELETE_KEY);
    }
}
4,发送MQ消息

在hotel-admin中的增、删、改业务中分别发送MQ消息:

@RestController
@RequestMapping("hotel")
public class HotelController {

    @Autowired
    private IHotelService hotelService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostMapping
    public void saveHotel(@RequestBody Hotel hotel){
        hotelService.save(hotel);

        rabbitTemplate.convertAndSend(MQConstants.HOTEL_EXCHANGE,MQConstants.HOTEL_INSERT_KEY
                ,hotel.getId());
    }

    @PutMapping()
    public void updateById(@RequestBody Hotel hotel){
        if (hotel.getId() == null) {
            throw new InvalidParameterException("id不能为空");
        }
        hotelService.updateById(hotel);

        rabbitTemplate.convertAndSend(MQConstants.HOTEL_EXCHANGE,MQConstants.HOTEL_INSERT_KEY
                ,hotel.getId());
    }

    @DeleteMapping("/{id}")
    public void deleteById(@PathVariable("id") Long id) {
        hotelService.removeById(id);

        rabbitTemplate.convertAndSend(MQConstants.HOTEL_EXCHANGE,MQConstants.HOTEL_DELETE_KEY
                ,id);
    }
}
2.5,接收MQ消息

hotel-demo接收到MQ消息要做的事情包括:
新增消息:根据传递的hotel的id查询hotel信息,然后新增一条数据到索引库
删除消息:根据传递的hotel的id删除索引库中的一条数据
1)首先在hotel-demo的cn.ben.hotel.service包下的IHotelService中新增新增、删除业务

void deleteById(Long id);

void insertById(Long id);

2)给hotel-demo中的cn.ben.hotel.service.impl包下的HotelService中实现业务:

@Override
public void deleteById(Long id) {
    try {
        // 1.准备Request
        DeleteRequest request = new DeleteRequest("hotel", id.toString());
        // 2.发送请求
        client.delete(request, RequestOptions.DEFAULT);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

@Override
public void insertById(Long id) {
    try {
        // 0.根据id查询酒店数据
        Hotel hotel = getById(id);
        // 转换为文档类型
        HotelDoc hotelDoc = new HotelDoc(hotel);

        // 1.准备Request对象
        IndexRequest request = new IndexRequest("hotel").id(hotel.getId().toString());
        // 2.准备Json文档
        request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
        // 3.发送请求
        client.index(request, RequestOptions.DEFAULT);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

3)编写监听器
在hotel-demo中的cn.ben.hotel.mq包新增一个类:

@Component
public class HotelListener {

    @Autowired
    private IHotelService hotelService;

    /**
     * 监听酒店新增或修改的业务
     * @param id 酒店id
     */
    @RabbitListener(queues = MqConstants.HOTEL_INSERT_QUEUE)
    public void listenHotelInsertOrUpdate(Long id){
        hotelService.insertById(id);
    }

    /**
     * 监听酒店删除的业务
     * @param id 酒店id
     */
    @RabbitListener(queues = MqConstants.HOTEL_DELETE_QUEUE)
    public void listenHotelDelete(Long id){
        hotelService.deleteById(id);
    }
}

监听binlog

方案三:监听binlog
优点:完全解除服务间耦合
缺点:开启binlog增加数据库负担、实现复杂度高
在这里插入图片描述给mysql开启binlog功能
mysql完成增、删、改操作都会记录在binlog中
hotel-demo基于canal监听binlog变化,实时更新elasticsearch中的内容

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值