锐单电子商城 , 一站式电子元器件采购平台!
  • 电话:400-990-0325

Spring5-Cloud2索引库文档es操作与RestClient操作

时间:2023-02-14 05:30:00 61082连接器

一、索引库操作

elasticsearch底层是基于lucene来实现的。Lucene是一个Java语言搜索引擎类库是Apache公司顶级项目,由DougCutting于1999年研发。官网地址:https://lucene.apache.org/ 。

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

MySQL Elasticsearch 说明
Table Index 索引(index),是文档的集合,类似于数据库的表(table)
Row Document 文档(Document),它是一个数据,类似于数据库中的行(Row),文档都是JSON格式
Column Field 字段(Field),就是JSON文档中的字段类似于数据库中的列(Column)
Schema Mapping Mapping(映射)是索引中文档的约束,例如字段类型约束。类似数据库的表结构(Schema)
SQL DSL DSL是elasticsearch提供的JSON风格请求句用于操作elasticsearch,实现CRUD增查改删
  • Mysql:

  • Elasticsearch:

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

  • 使用安全要求高的写作操作mysql擅长事务类型操作,能保证数据的安全性和一致性
  • 搜索需求对查询性能要求高,使用elasticsearch实现,擅长大量数据的搜索、分析和计算
  • 以某种方式实现数据同步,确保一致性

mapping映射属性

索引库类似于数据库表,mapping映射类似于表的结构。我们必须朝向es在存储数据时,必须首先创建库和表。

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

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

1.创建索引库和映射

PUT /索引库名称 { 
           "mappings": { 
             "properties": { 
               "字段名":{ 
                 "type": "text",         "analyzer": "ik_smart"       },       "字段名2":{ 
                 "type": "keyword",         "index": "false"       },       "字段名3":{ 
                 "properties": { 
                   "子字段": { 
                     "type": "keyword"           }         }       },       // ...略     }   } } 

示例:

{     "age": 21,    "weight": 52.1,
    "isMarried": false,
    "info": "my fisrt data",
    "email": "xxxxx@xxx.com",
    "score": [99, 99.5, 100],
    "name": {
        "firstName": "大",
        "lastName": "锤"
    }
}
PUT /test
{
  "mappings": {
    "properties": {
      "age":{
        "type": "integer"
      },
      "weight":{
        "type": "float"
      }, 
      "isMarried":{
        "type": "boolean"
      },      
      "info":{
        "type": "text",
        "analyzer": "ik_smart"
      },
      "email": {
        "type": "keyword",
        "index": "false"
      },
      "score": {
        "type": "float"
      },
      "name":{
        "properties": {
          "firstName": {
            "type": "keyword"
          },
          "lastName": {
            "type": "keyword"
          }
        }
      }
    }
  }
}

在这里插入图片描述

1.2查询索引库

GET /索引库名

1.3修改索引库

因此索引库一旦创建,无法修改mapping。允许添加新的字段到mapping中,因为不会对倒排索引产生影响。

PUT /索引库名/_mapping
{ 
        
  "properties": { 
        
    "新字段名":{ 
        
      "type": "integer"
    }
  }
}
DELETE /索引库名  删除索引库

二、文档操作

2.1新增文档

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

2.2查改删

GET /{ 
        索引库名称}/_doc/{ 
        id}    查询文档
DELETE /{ 
        索引库名}/_doc/id值  删除文档
PUT /{ 
        索引库名}/_doc/文档id       全量修改
{ 
        
    "字段1": "值1",
    "字段2": "值2",
    // ... 略
}
POST /{ 
        索引库名}/_update/文档id      增量修改是只修改指定id匹配的文档中的部分字段。
{ 
        
    "doc": { 
        
         "字段名": "新的值",
    }
}

数据修改会导致查询到的 “_version” : 值递增

三、RestAPI索引库操作

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

我们学习的是Java HighLevel Rest Client客户端API

导入Demo工程

数据库结构如下:

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

初始化RestClient

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

分为三步:

1)引入es的RestHighLevelClient依赖:

<dependency>
    <groupId>org.elasticsearch.clientgroupId>
    <artifactId>elasticsearch-rest-high-level-clientartifactId>
dependency>

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

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

3)初始化RestHighLevelClient:

初始化的代码如下:

RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
        HttpHost.create("http://192.168.1.11: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.1.11:9200")
                //集群可以写多个
        ));
    }

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

3.1创建索引库代码解读

代码分为三步:

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

示例

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

3.2删除索引库

与创建索引库相比:请求方式从PUT变为DELTE

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

@Test
void testDeleteHotelIndex() throws IOException { 
        
    // 1.创建Request对象
    DeleteIndexRequest request = new DeleteIndexRequest("hotel");
    // 2.发送请求
    client.indices().delete(request, RequestOptions.DEFAULT);
}

3.3判断索引库是否存在

  • 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 ? "索引库已经存在!" : "索引库不存在!");
}

四、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.1.11:9200")
        ));
    }

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

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

新增文档的DSL语句如下:

POST /{ 
        索引库名}/_doc/1
{ 
        
    "name": "Jack",
    "age": 元器件数据手册IC替代型号,打造电子元器件IC百科大全!
          

相关文章