Day08_ ElasticSearch基础

本文详细介绍Elasticsearch的安装、核心概念、操作方法及Java API应用,涵盖倒排索引原理、数据类型、索引管理和文档操作,适合初学者快速上手。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1-今日内容

  1. 初识 ElasticSearch

  2. 安装 ElasticSearch

  3. ElasticSearch 核心概念

  4. 操作 ElasticSearch

  5. ElasticSearch JavaAPI

2-初识ElasticSearch

2.1-基于数据库查询的问题

在这里插入图片描述

2.2-倒排索引

倒排索引:将文档进行分词,形成词条和id的对应关系即为反向索引。

以唐诗为例,所处包含“前”的诗句

正向索引:由《静夜思》–>窗前明月光—>“前”字

反向索引:“前”字–>《静夜思》–>窗前明月光

​ 搜索框中输入的汉字 id 通过id找文档的数据

“床前明月光”–> 分词

将一段文本按照一定的规则,拆分为不同的词条(term)

在这里插入图片描述

在这里插入图片描述

倒排索引:将各个文档中的内容,进行分词,形成词条。然后记录词条和数据的唯一标识(id)的对应关系,形成的产物

2.3-ES存储和查询的原理

index(索引):相当于mysql的库

document(文档):相当于mysql的表中的数据(json格式)

数据库查询存在的问题:

  1. 性能低:使用模糊查询,左边有通配符,不会走索引,会全表扫描,性能低
  2. 功能弱:如果以”华为手机“作为条件,查询不出来数据

Es使用倒排索引,对title 进行分词

在这里插入图片描述

  1. 使用“手机”作为关键字查询

    生成的倒排索引中,词条会排序,形成一颗树形结构,提升词条的查询速度

  2. 使用“华为手机”作为关键字查询

    华为:1,3

    手机:1,2,3

    在这里插入图片描述

2.4-ES概念详解

•ElasticSearch是一个基于Lucene的搜索服务器

在这里插入图片描述

•是一个分布式、高扩展、高实时的搜索与数据分析引擎

•基于RESTful web接口

•Elasticsearch是用Java语言开发的,并作为Apache许可条款下的开放源码发布,是一种流行的企业级搜索引擎

•官网:https://www.elastic.co/

应用场景

•搜索:海量数据的查询

•日志数据分析

•实时数据分析

3-安装ElasticSearch

3.1-ES安装

参见ElasticSearch-ES安装.md

查看elastic是否启动

ps -ef|grep elastic

3.2-ES辅助工具安装

参见ElasticSearch-ES安装.md

后台启动

nohup ../bin/kibana &

4-ElasticSearch核心概念

索引(index)

ElasticSearch存储数据的地方,可以理解成关系型数据库中的数据库概念。

映射(mapping)

mapping定义了每个字段的类型、字段所使用的分词器等。相当于关系型数据库中的表结构。

文档(document)

Elasticsearch中的最小数据单元,常以json格式显示。一个document相当于关系型数据库中的一行数据。

倒排索引

一个倒排索引由文档中所有不重复词的列表构成,对于其中每个词,对应一个包含它的文档id列表。

类型(type)

一种type就像一类表。如用户表、角色表等。在Elasticsearch7.X默认type为_doc

 \- ES 5.x中一个index可以有多种type。

  \- ES 6.x中一个index只能有一种type。

  \- ES 7.x以后,将逐步移除type这个概念,现在的操作已经不再使用,默认_doc

5-脚本操作ES

5.1-RESTful风格介绍

RESTful(Representational State Transfer),表述性状态转移,是一组架构约束条件和原则。满足这些约束条件和原则的应用程序或设计就是RESTful。就是一种定义接口的规范。

  • 基于HTTP。

  • 使用XML格式定义或JSON格式定义。

  • 每一个URI代表1种资源。

  • 客户端使用GET、POST、PUT、DELETE 4个表示操作方式的动词对服务端资源进行操作:

    • GET:用来获取资源
    • POST:用来新建资源(也可以用于更新资源)
    • PUT:用来更新资源
    • DELETE:用来删除资源

在这里插入图片描述

5.2-操作索引

用Post操作那个索引:

添加索引

PUT http://ip:端口/索引名称

查询索引

GET http://ip:端口/索引名称  # 查询单个索引信息
GET http://ip:端口/索引名称1,索引名称2    # 查询多个索引信息
GET http://ip:端口/_all  # 查询所有索引信息

•删除索引

DELETE http://ip:端口/索引名称

•关闭、打开索引

POST http://ip:端口/索引名称/_close  
POST http://ip:端口/索引名称/_open 

5.3-ES数据类型

  1. 简单数据类型
  • 字符串

聚合:相当于mysql 中的运算

text:会分词,不支持聚合

keyword:不会分词,将全部内容作为一个词条,支持聚合
  • 数值

  • 布尔:boolean

  • 二进制:binary

  • 范围类型

integer_range, float_range, long_range, double_range, date_range 
  • 日期:date

在这里插入图片描述

  1. 复杂数据类型

•数组

•对象

在这里插入图片描述

5.4-操作映射

 PUT person
 
 GET person
 #添加映射
 PUT person/_mapping
 {
   "properties":{
     "name":{
       "type":"text"
     },
     "age":{
       "type":"integer"
     }
   }
 }

#创建索引并添加映射

 
 #创建索引并添加映射
 PUT /person1
{
  "mappings": {
    "properties": {
      "name": {
        "type": "text"
      },
      "age": {
        "type": "integer"
      }
    }
  }
}

GET person1/_mapping

添加字段

#添加字段
PUT person1/_mapping
{
  "properties":{
    "address":{
      "type": "text"
    }
  }
}

5.5-操作文档

•添加文档,指定id

POST /person1/_doc/2
{
  "name":"张三",
  "age":18,
  "address":"北京"
}

GET /person1/_doc/2


•添加文档,不指定id

#添加文档,不指定id, 会随机生成一个id
POST /person1/_doc
{
  "name":"张三",
  "age":18,
  "address":"北京"
}

#查询所有文档
GET /person1/_search

修改文档

PUT person1/_doc/1
{
  "name": "万手哥",
  "age": 18,
  "address": "西湖"
}

删除指定id文档

#删除指定id文档
DELETE /person1/_doc/1

6-分词器

6.1 分词器-介绍

  • 分词器(Analyzer):将一段文本,按照一定逻辑,分析成多个词语的一种工具

​ 如:华为手机 — > 华为、手、手机

ElasticSearch 内置分词器

​ • Standard Analyzer - 默认分词器,按词切分,小写处理

​ • Simple Analyzer - 按照非字母切分(符号被过滤), 小写处理

​ • Stop Analyzer - 小写处理,停用词过滤(the,a,is)

​ • Whitespace Analyzer - 按照空格切分,不转小写

​ • Keyword Analyzer - 不分词,直接将输入当作输出

​ • Patter Analyzer - 正则表达式,默认\W+(非字符分割)

​ • Language - 提供了30多种常见语言的分词器

ElasticSearch 内置分词器对中文很不友好,处理方式为:一个字一个词, 我们可以安装中文分词器

6.2 分词器-介绍

•IKAnalyzer是一个开源的,基于java语言开发的轻量级的中文分词工具包

•是一个基于Maven构建的项目

•具有60万字/秒的高速处理能力

•支持用户词典扩展定义

•下载地址:https://github.com/medcl/elasticsearch-analysis-ik/archive/v7.4.0.zip

安装包在资料文件夹中提供

6.3-ik分词器安装

参见 ik分词器安装.md

执行如下命令时如果出现 打包失败(501码)将maven镜像换成阿里云的

mvn package

/opt/apache-maven-3.1.1/conf/setting.xml

	<mirror>
        <id>alimaven</id>
        <name>aliyun maven</name>
        <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
        <mirrorOf>central</mirrorOf>
    </mirror>

6.4-ik分词器使用

IK分词器有两种分词模式:ik_max_word和ik_smart模式。

1、ik_max_word

会将文本做最细粒度的拆分,比如会将“乒乓球明年总冠军”拆分为“乒乓球、乒乓、球、明年、总冠军、冠军。

#方式一ik_max_word
GET /_analyze
{
  "analyzer": "ik_max_word",
  "text": "乒乓球明年总冠军"
}

ik_max_word分词器执行如下:

{
  "tokens" : [
    {
      "token" : "乒乓球",
      "start_offset" : 0,
      "end_offset" : 3,
      "type" : "CN_WORD",
      "position" : 0
    },
    {
      "token" : "乒乓",
      "start_offset" : 0,
      "end_offset" : 2,
      "type" : "CN_WORD",
      "position" : 1
    },
    {
      "token" : "球",
      "start_offset" : 2,
      "end_offset" : 3,
      "type" : "CN_CHAR",
      "position" : 2
    },
    {
      "token" : "明年",
      "start_offset" : 3,
      "end_offset" : 5,
      "type" : "CN_WORD",
      "position" : 3
    },
    {
      "token" : "总冠军",
      "start_offset" : 5,
      "end_offset" : 8,
      "type" : "CN_WORD",
      "position" : 4
    },
    {
      "token" : "冠军",
      "start_offset" : 6,
      "end_offset" : 8,
      "type" : "CN_WORD",
      "position" : 5
    }
  ]
}

2、ik_smart
会做最粗粒度的拆分,比如会将“乒乓球明年总冠军”拆分为乒乓球、明年、总冠军。

#方式二ik_smart
GET /_analyze
{
  "analyzer": "ik_smart",
  "text": "乒乓球明年总冠军"
}

ik_smart分词器执行如下:

{
  "tokens" : [
    {
      "token" : "乒乓球",
      "start_offset" : 0,
      "end_offset" : 3,
      "type" : "CN_WORD",
      "position" : 0
    },
    {
      "token" : "明年",
      "start_offset" : 3,
      "end_offset" : 5,
      "type" : "CN_WORD",
      "position" : 1
    },
    {
      "token" : "总冠军",
      "start_offset" : 5,
      "end_offset" : 8,
      "type" : "CN_WORD",
      "position" : 2
    }
  ]
}

由此可见 使用ik_smart可以将文本"text": "乒乓球明年总冠军"分成了【乒乓球】【明年】【总冠军】

这样看的话,这样的分词效果达到了我们的要求。

6.5 使用IK分词器-查询文档

•词条查询:term

​ 词条查询不会分析查询条件,只有当词条和查询字符串完全匹配时才匹配搜索

•全文查询:match

​ 全文查询会分析查询条件,先将查询条件进行分词,然后查询,求并集

二者区别?

term是代表完全匹配,即不进行分词器分析,文档中必须包含整个搜索的词汇 . 而match查询的时候,elasticsearch会根据你给定的字段先分词 再查询取并集.

1.创建索引,添加映射,并指定分词器为ik分词器

PUT person
{
  "mappings": {
    "properties": {
      "name": {
        "type": "keyword"
      },
      "address": {
        "type": "text",
        "analyzer": "ik_max_word"
      }
    }
  }
}

2.添加文档

POST /person2/_doc/1
{
  "name":"张三",
  "age":18,
  "address":"北京海淀区"
}

POST /person2/_doc/2
{
  "name":"李四",
  "age":18,
  "address":"北京朝阳区"
}

POST /person2/_doc/3
{
  "name":"王五",
  "age":18,
  "address":"北京昌平区"
}

3.查询映射

GET person2

在这里插入图片描述

4.查看分词效果

GET _analyze
{
  "analyzer": "ik_max_word",
  "text": "北京海淀"
}

5.词条查询:term

查询person2中匹配到"北京"两字的词条

GET /person2/_search
{
  "query": {
    "term": {
      "address": {
        "value": "北京天安门"
      }
    }
  }
}

6.全文查询:match

​ 全文查询会分析查询条件,先将查询条件进行分词,然后查询,求并集

GET /person2/_search
{
  "query": {
    "match": {
      "address":"北京昌平"
    }
  }
}

添加的时候生效的:

字符串的类型 address(text) :南京雨花台区人才公寓 ik_max_word

text(会分词,不支持聚合) keyword(不会分词 ,但是支持聚合)

ik分词器的安装后

ik_max_word(细粒度拆分词条) ik_smart(粗粒度拆分词条)

查询的时候使用的

两种查询的方式:(对搜索框中输入的字符串是否分词)

term查询(搜索框中输入的内容要和索引库中的词条完全匹配) match全文查询(会对你在搜索框中输入的字符串 先分词 后查询)

南京 雨花台区(查询不到)

7-ElasticSearch JavaApi-

7.1SpringBoot整合ES

①搭建SpringBoot工程

②引入ElasticSearch相关坐标

<!--引入es的坐标-->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.4.0</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-client</artifactId>
            <version>7.4.0</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.4.0</version>
        </dependency>

③测试

ElasticSearchConfig

@Configuration
@ConfigurationProperties(prefix="elasticsearch")
public class ElasticSearchConfig {

    private String host;

    private int port;

 
    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }
    @Bean
    public RestHighLevelClient client(){
        return new RestHighLevelClient(RestClient.builder(
                new HttpHost(host,port,"http")
        ));
    }
}

ElasticsearchDay01ApplicationTests

注意:使用@Autowired注入RestHighLevelClient 如果报红线,则是因为配置类所在的包和测试类所在的包,包名不一致造成的

@SpringBootTest
class ElasticsearchDay01ApplicationTests {

    @Autowired
    RestHighLevelClient client;

    /**
     * 测试
     */
    @Test
    void contextLoads() {

        System.out.println(client);
    }
}

7.2-创建索引

1.添加索引

/**
    * 添加索引
    * @throws IOException
    */
   @Test
   public void addIndex() throws IOException {
      //1.使用client获取操作索引对象
       IndicesClient indices = client.indices();
       //2.具体操作获取返回值
       //2.1 设置索引名称
       CreateIndexRequest createIndexRequest=new CreateIndexRequest("itheima");

       CreateIndexResponse createIndexResponse = indices.create(createIndexRequest, RequestOptions.DEFAULT);
       //3.根据返回值判断结果
       System.out.println(createIndexResponse.isAcknowledged());
   }

2.添加索引,并添加映射

 /**
     * 添加索引,并添加映射
     */
    @Test
    public void addIndexAndMapping() throws IOException {
       //1.使用client获取操作索引对象
        IndicesClient indices = client.indices();
        //2.具体操作获取返回值
        //2.具体操作,获取返回值
        CreateIndexRequest createIndexRequest = new CreateIndexRequest("itcast");
        //2.1 设置mappings
        String mapping = "{\n" +
                "      \"properties\" : {\n" +
                "        \"address\" : {\n" +
                "          \"type\" : \"text\",\n" +
                "          \"analyzer\" : \"ik_max_word\"\n" +
                "        },\n" +
                "        \"age\" : {\n" +
                "          \"type\" : \"long\"\n" +
                "        },\n" +
                "        \"name\" : {\n" +
                "          \"type\" : \"keyword\"\n" +
                "        }\n" +
                "      }\n" +
                "    }";
        createIndexRequest.mapping(mapping,XContentType.JSON);

        CreateIndexResponse createIndexResponse = indices.create(createIndexRequest, RequestOptions.DEFAULT);
        //3.根据返回值判断结果
        System.out.println(createIndexResponse.isAcknowledged());
    }

7.3-查询、删除、判断索引

查询索引


   

    /**
     * 查询索引
     */
    @Test
    public void queryIndex() throws IOException {
        IndicesClient indices = client.indices();

        GetIndexRequest getRequest=new GetIndexRequest("itcast");
        GetIndexResponse response = indices.get(getRequest, RequestOptions.DEFAULT);
        Map<String, MappingMetaData> mappings = response.getMappings();
        //iter 提示foreach
        for (String key : mappings.keySet()) {
            System.out.println(key+"==="+mappings.get(key).getSourceAsMap());
        }
    }

   
   

删除索引

 /**
     * 删除索引
     */
    @Test
    public void deleteIndex() throws IOException {
         IndicesClient indices = client.indices();
        DeleteIndexRequest deleteRequest=new DeleteIndexRequest("itheima");
        AcknowledgedResponse delete = indices.delete(deleteRequest, RequestOptions.DEFAULT);
        System.out.println(delete.isAcknowledged());

    }

索引是否存在

 /**
     * 索引是否存在
     */
    @Test
    public void existIndex() throws IOException {
        IndicesClient indices = client.indices();

        GetIndexRequest getIndexRequest=new GetIndexRequest("itheima");
        boolean exists = indices.exists(getIndexRequest, RequestOptions.DEFAULT);


        System.out.println(exists);

    }
    

7.4-添加文档

1.添加文档,使用map作为数据

 @Test
    public void addDoc1() throws IOException {
        Map<String, Object> map=new HashMap<>();
        map.put("name","张三");
        map.put("age","18");
        map.put("address","北京二环");
        IndexRequest request=new IndexRequest("itcast").id("1").source(map);
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
        System.out.println(response.getId());
    }

2.添加文档,使用对象作为数据

@Test
public void addDoc2() throws IOException {
    Person person=new Person();
    person.setId("2");
    person.setName("李四");
    person.setAge(20);
    person.setAddress("北京三环");
    String data = JSON.toJSONString(person);
    IndexRequest request=new IndexRequest("itcast").id(person.getId()).source(data,XContentType.JSON);
    IndexResponse response = client.index(request, RequestOptions.DEFAULT);
    System.out.println(response.getId());
}

7.5-修改、查询、删除文档

1.修改文档:添加文档时,如果id存在则修改,id不存在则添加

    /**
     * 修改文档:添加文档时,如果id存在则修改,id不存在则添加
     */

    @Test
    public void UpdateDoc() throws IOException {
        Person person=new Person();
        person.setId("2");
        person.setName("李四");
        person.setAge(20);
        person.setAddress("北京三环车王");

        String data = JSON.toJSONString(person);

        IndexRequest request=new IndexRequest("itcast").id(person.getId()).source(data,XContentType.JSON);
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
        System.out.println(response.getId());
    }

2.根据id查询文档

    /**
     * 根据id查询文档
     */
    @Test
    public void getDoc() throws IOException {

        //设置查询的索引、文档
        GetRequest indexRequest=new GetRequest("itcast","2");

        GetResponse response = client.get(indexRequest, RequestOptions.DEFAULT);
        System.out.println(response.getSourceAsString());
    }

3.根据id删除文档

/**
     * 根据id删除文档
     */
    @Test
    public void delDoc() throws IOException {

        //设置要删除的索引、文档
        DeleteRequest deleteRequest=new DeleteRequest("itcast","1");

        DeleteResponse response = client.delete(deleteRequest, RequestOptions.DEFAULT);
        System.out.println(response.getId());
    }

(“北京三环车王”);

    String data = JSON.toJSONString(person);

    IndexRequest request=new IndexRequest("itcast").id(person.getId()).source(data,XContentType.JSON);
    IndexResponse response = client.index(request, RequestOptions.DEFAULT);
    System.out.println(response.getId());
}

2.根据id查询文档

```java
    /**
     * 根据id查询文档
     */
    @Test
    public void getDoc() throws IOException {

        //设置查询的索引、文档
        GetRequest indexRequest=new GetRequest("itcast","2");

        GetResponse response = client.get(indexRequest, RequestOptions.DEFAULT);
        System.out.println(response.getSourceAsString());
    }

3.根据id删除文档

/**
     * 根据id删除文档
     */
    @Test
    public void delDoc() throws IOException {

        //设置要删除的索引、文档
        DeleteRequest deleteRequest=new DeleteRequest("itcast","1");

        DeleteResponse response = client.delete(deleteRequest, RequestOptions.DEFAULT);
        System.out.println(response.getId());
    }
Elasticsearch 简介 ElasticSearch是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。Elasticsearch是用Java开发的,并作为Apache许可条款下的开放源码发布,是当前流行的企业级搜索引擎。设计用于云计算中,能够达到实时搜索,稳定,可靠,快速,安装使用方便。elasticSearch 的使用场景 1、在海量数据前提下,对数据进行检索。比如:京东,淘宝等电商项目课程目标: 1. 了解企业级搜索引擎2. 安装elasticsearch 课程目录: 01 课程介绍02 elasticsearch 简介03 elasticsearch 使用场景04 安装elasticsearch 之前先安装jdk05 安装elasticsearch06 测试elasticsearch是否安装成功 07 安装kibana08 elasticsearch 基本认识 以及添加索引和删除索引09 elasticsearch 添加查询数据10 elasticsearch 修改删除数据11 elasticsearch 有条件的查询12 分词子属性fuzzy查询13 elasticsearch 过滤使用14 elasticsearch 排序与分页15 elasticsearch 如何查询指定的字段16 elasticsearch 高亮显示17 elasticsearch 聚合18 elasticsearch mapping 概念19 elasticsearch 的中文词库20 elasticsearch 中文词库安装测试21 elasticsearch 中文词库的使用案例22 elasticsearch 自定义词库配置23 安装nginx 配置中文词库24 测试elasticsearch 自定义中文词库25 搭建项目父工程26 搭建项目bean-interface-common27 搭建search 的service web 项目28 测试项目是否能与elasticsearch联通29 创建数据库并搭建首页30 数据上传功能的实现类完成31 数据上传控制器完成32 dubbo 介绍以及安装zookeeper33 将数据从mysql 上传到elasticsearch 中34 elasticsearch查询功能分析35 编写业务需求的dsl 语句36 编写输入参数返回结果集的实体类37 实现类编写38 编写实现类中dsl 语句39 返回集结果转换40 结果测试41 测试通过输入查询条件并将数据显示到页面
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值