SpringCloud-day5-Elasticsearch

本文详细介绍了如何在Spring Cloud中使用Elasticsearch进行分布式搜索。内容涵盖Elasticsearch的正向索引和倒排索引概念,ik分词器的使用,以及通过RestClient进行索引库和文档的各种操作,包括创建、查询、删除和修改。

分布式搜索

1. elasticsearch

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

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

  • elasticsearch是核心,负责存储、计算、搜索、分析数据
  • kibana负责数据可视化
  • Logstash、Beats负责数据抓取
1.1 正向索引和倒排索引

正向索引:基于文档id创建索引。查询词条时必须先找到文档,然后判断是否包含词条

倒排索引:对文档内容分词,对词条创建索引,并记录词条所在文档的信息。查询时先根据词条查询到文档id,然后获取到文档

elasticsearch采用倒排索引:

  • 文档(document):每条数据就是一个文档
  • 词条(term):文档按照语义分成的词语,中文按照语义分,英文按照空格分

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-JOr3Cy50-1659015467832)(C:/Users/丁凯旋/AppData/Roaming/Typora/typora-user-images/image-20220727105512061.png)]

elasticsearch是面向文档存储的,可以是数据库中的一条商品数据,一个订单信息。

文档数据会被序列化为json格式后存储在elasticsearch中

索引(index):相同类型的文档的集合

映射(mapping):索引中文档的字段约束信息,类似表的结构约束

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4J5F6C86-1659015467834)(C:/Users/丁凯旋/AppData/Roaming/Typora/typora-user-images/image-20220727113637546.png)]

架构:

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

使用docker安装elasticsearch,并启动

docker pull elasticsearch:7.12.1

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 "cluster.name=es-docker-cluster":设置集群名称
  • -e "http.host=0.0.0.0":监听的地址,可以外网访问
  • -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:端口映射配置

安装kibana并运行

docker pull kibana:7.12.1

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:端口映射配置
1.2 ik分词器

es在创建倒排索引时需要对文档分词,在搜索时,需要对用户输入内容分词。但默认的分词规则对中文处理并不友好。所以处理中文分词,一般会使用ik分词器

IK分词器包含两种模式:

GET /_analyze
{
  "analyzer": "ik_smart",
  "text": "今天的天气真不错"
}
  • ik_smart:最少切分,粗粒度切分

    响应
    {
      "tokens" : [
        {
          "token" : "今天",
          "start_offset" : 0,
          "end_offset" : 2,
          "type" : "CN_WORD",
          "position" : 0
        },
        {
          "token" : "的",
          "start_offset" : 2,
          "end_offset" : 3,
          "type" : "CN_CHAR",
          "position" : 1
        },
        {
          "token" : "天气",
          "start_offset" : 3,
          "end_offset" : 5,
          "type" : "CN_WORD",
          "position" : 2
        },
        {
          "token" : "真不错",
          "start_offset" : 5,
          "end_offset" : 8,
          "type" : "CN_WORD",
          "position" : 3
        }
      ]
    }
    
  • ik_max_word:最细切分,细粒度切分

    {
      "tokens" : [
        {
          "token" : "今天",
          "start_offset" : 0,
          "end_offset" : 2,
          "type" : "CN_WORD",
          "position" : 0
        },
        {
          "token" : "的",
          "start_offset" : 2,
          "end_offset" : 3,
          "type" : "CN_CHAR",
          "position" : 1
        },
        {
          "token" : "天气",
          "start_offset" : 3,
          "end_offset" : 5,
          "type" : "CN_WORD",
          "position" : 2
        },
        {
          "token" : "真不错",
          "start_offset" : 5,
          "end_offset" : 8,
          "type" : "CN_WORD",
          "position" : 3
        },
        {
          "token" : "真不",
          "start_offset" : 5,
          "end_offset" : 7,
          "type" : "CN_WORD",
          "position" : 4
        },
        {
          "token" : "不错",
          "start_offset" : 6,
          "end_offset" : 8,
          "type" : "CN_WORD",
          "position" : 5
        }
      ]
    }
    

ik分词器-扩展词库

要扩展ik分词器的词库,只需要修改ik分词器目录中config目录中的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>
</properties>

然后在名为ext.dic的文件中,添加想要拓展的词语即可:

白嫖
一键三连

要禁用某些敏感词条,只需要修改ik分词器目录中config目录中的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>

分词器的作用是什么?

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

2. 索引库操作

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

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

ES中通过Restful请求操作索引库、文档。请求内容用DSL语句来表示。

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

例如:创建一个名为myindex的索引库

PUT /myindex
{
  "mappings": {
    "properties": {
      "info":{
        "type": "text",
        "analyzer": "ik_smart"
      },
      "email":{
        "type": "keyword",
        "index": false
      },
      "name":{
        "type": "object",
        "properties": {
          "firstName":{
            "type":"keyword"
          },
          "lastName":{
            "type":"keyword"
          }
        }
      }
    }
  }
}

查看索引库:GET /索引库名

例如:GET /myindex

删除索引库:DELETE /索引库名

例如:DELETE /myindex

修改索引库:索引库和mapping一旦创建无法修改,但是可以添加新的字段,语法如下

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

3. 文档操作

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

例如

POST /myindex/_doc/1
{
  "info":"测试文档1",
  "email":"123@qq.com",
  "name":{
    "firstName":"三",
    "lastName":"张"
  }
}
3.2 查询文档:

GET /索引库名/_doc/文档id

3.3 删除文档:

DELETE /索引库名/_doc/文档id

3.4 修改文档:
  • 方式一:全量修改,会删除旧文档,添加新文档。既能修改,又能新增。id存在时修改,id不存在新增

    PUT /索引库名/_doc/文档id
    {
        "字段1":"值1",
        "字段2":"值2",
        // ...
    }
    
  • 方式二:增量修改,修改指定字段值

    POST /索引库名/_update/文档id
    {
        "doc":{
            "字段名":"值"
        }
    }
    

4. RestClient操作索引库

4.1 初始化JavaRestClient
  1. 引入es的RestHighLevelClient依赖

    <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>elasticsearch-rest-high-level-client</artifactId>
    </dependency>
    
  2. 初始化RestHighLevelClient

    RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(HttpHost.create("http://xxx.xxx.xxx.xx:9200")));
    
4.2 创建索引库
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" +
        "      },\n" +
        "      \"starName\":{\n" +
        "        \"type\": \"keyword\"\n" +
        "      },\n" +
        "      \"business\":{\n" +
        "        \"type\": \"keyword\",\n" +
        "        \"copy_to\": \"all\"\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" +
        "}";

@Test
public void testCreateHotelIndex() throws IOException {
    //1. 创建Request对象
    CreateIndexRequest request = new CreateIndexRequest("hotel");
    //2. 请求参数,MAPPING_TEMPLATE是静态常量字符串,内容是创建索引库的DSL语句
    request.source(MAPPING_TEMPLATE, XContentType.JSON);
    //3. 发起请求,indices返回的对象中包含索引库操作的所有方法
    client.indices().create(request, RequestOptions.DEFAULT);
}
4.3 删除索引库
@Test
public void testDeleteHotelIndex() throws IOException {
    //1. 创建Request对象
    DeleteIndexRequest request = new DeleteIndexRequest("hotel");
    //2. 发起请求删除索引库
    client.indices().delete(request, RequestOptions.DEFAULT);
}
4.4 判断索引库是否存在
@Test
public void testExistHotelIndex() throws IOException {
    GetIndexRequest request = new GetIndexRequest("hotel");
    boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
    System.out.println(exists ? "索引库已经存在" : "索引库不存在");
}
4.5 索引库操作的基本步骤:
  1. 初始化RestHighLevelClient
  2. 创建xxxIndexRequest。XXX是Create、Get、Delete
  3. 准备DSL(Create时需要)
  4. 发送请求。调用RestHighLevelClient.indices().xxx()方法,xxx是create、exists、delete

5. RestClient操作文档

初始化RestHighLevelClient

RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(HttpHost.create("http://xxx.xxx.xxx.xx:9200")));
5.1 新增文档
@Test
public void testAddDocument() throws IOException{
    //根据id查询酒店数据
    Hotel hotel = hotelService.getById(61083L);
    //转换为文档类型
    HotelDoc hotelDoc = new HotelDoc(hotel);

    //1. 准备Request对象
    IndexRequest request = new IndexRequest("hotel").id(hotel.getId().toString());
    //2. 准备json文档,使用JSON.toJSONString()方法将查询出的对象转换为json字符串
    request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
    //3. 发送请求
    client.index(request, RequestOptions.DEFAULT);
}
5.2 查询文档

根据id查询到的文档数据是json,需要反序列化为java对象

@Test
public void testGetDocument() throws IOException{
    //1. 创建request对象
    GetRequest request = new GetRequest("hotel", "61083");
    //2. 发送请求,得到响应
    GetResponse response = client.get(request, RequestOptions.DEFAULT);
    //3. 解析响应结果
    String json = response.getSourceAsString();
    HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
    System.out.println("hotelDoc = " + hotelDoc);
}
5.3 删除文档

根据id删除文档

@Test
public void testDeleteDocument() throws IOException {
    DeleteRequest request = new DeleteRequest("hotel", "61083");
    client.delete(request, RequestOptions.DEFAULT);
}
5.4 修改文档

修改文档有两种方式:

  • 全量更新。再次写入id一样的文档,就会删除旧文档,添加新文档

  • 局部更新。只更新部分字段。

    @Test
    public void testUpdateDocumentById() throws IOException {
        //1. 创建request对象
        UpdateRequest request = new UpdateRequest("hotel", "61083");
        //2. 准备请求参数
        request.doc(
            "price", "721",
            "starName", "四钻"
        );	//可变参数,第一个为key,第二个为value,如果修改多个就接着往下写
        //3. 发送请求
        client.update(request, RequestOptions.DEFAULT);
    }
    
5.5 批量导入文档

批量查询酒店数据,然后批量导入索引库中

@Test
public void testBulkRequest() throws IOException {
    //批量查询酒店数据
    List<Hotel> hotels = hotelService.list();

    //1. 创建request
    BulkRequest request = new BulkRequest();
    //2. 准备参数,添加多个新增的request
    for (Hotel hotel : hotels) {
        //转换为文档类型
        HotelDoc hotelDoc = new HotelDoc(hotel);
        //创建新增文档的request对象
        request.add(new IndexRequest("hotel")
                    .id(hotelDoc.getId().toString())
                    .source(JSON.toJSONString(hotelDoc), XContentType.JSON));
    }
    //3. 发送请求
    client.bulk(request, RequestOptions.DEFAULT);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值