0
点赞
收藏
分享

微信扫一扫

Java-主流框架—(12)Spring-ElasticSearch

求索大伟 2022-02-09 阅读 106

1.初始ElasticSeearch

1.1基于数据库查询的问题

1.2倒排索引

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

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

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

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

反向索引的实现就是对诗句进行分词,分成单个的词,由词推据,即为反向索引

“床前明月光”--> 分词

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

 

 1.3 ES存储和搜索的原理

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

映射:相当于mysql 的表结构

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

数据库查询存在的问题:

  1. 性能低:使用模糊查询,左边有通配符,不会走索引,会全表扫描,性能低

  2. 功能弱:如果以”华为手机“作为条件,查询不出来数据

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

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

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

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

    华为:1,3

    手机:1,2,3

 1.4ES概念详解

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

 

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

•基于RESTful web接口

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

•官网:Free and Open Search: The Creators of Elasticsearch, ELK & Kibana | Elastic

应用场景

•搜索:海量数据的查询

•日志数据分析

•实时数据分析

 2.安装ElasticSearch

2.1ElasticSearch

1、上传ElasticSearch安装包

 2、执行解压操作 ,如下图

3、创建普通用户  

因为安全问题,Elasticsearch 不允许root用户直接运行,所以要创建新用户,在root用户中创建新用户,执行如下命令:  

5、为新用户授权,如下图  

将 /opt/elasticsearch-7.4.0文件夹授权给itheima用户,由上图可见,我们的文件夹权限赋给了itheima

6、修改elasticsearch.yml文件

 

cluster.name:配置elasticsearch的集群名称,默认是elasticsearch。建议修改成一个有意义的名称

node.name:节点名,elasticsearch会默认随机指定一个名字,建议指定一个有意义的名称,方便管理

network.host:设置为0.0.0.0允许外网访问

http.port:Elasticsearch的http访问端口

cluster.initial_master_nodes:初始化新的集群时需要此配置来选举master

7、修改配置文件

新创建的itheima用户最大可创建文件数太小,最大虚拟内存太小,切换到root用户,编辑下列配置文件, 添加类似如下内容

 8、启动elasticsearch

通过上图我们可以看到elasticsearch已经成功启动

windows安装:(46条消息) win10 简单搭建ElasticSearch_q3198215426的博客-CSDN博客 

 

 

 2.2Kibana安装

1、什么是Kibana

Kibana是一个针对Elasticsearch的开源分析及可视化平台,用来搜索、查看交互存储在Elasticsearch索引中的数据。使用Kibana,可以通过各种图表进行高级数据分析及展示。

Kibana让海量数据更容易理解。它操作简单,基于浏览器的用户界面可以快速创建仪表板(dashboard)实时显示Elasticsearch查询动态。

2、上传kibana

CRT中克隆一个窗口,上传Kibana

 2、解压kibana

解压到当前目录(/opt)下

3、修改kibana配置

server.port:http访问端口

server.host:ip地址,0.0.0.0表示可远程访问

server.name:kibana服务名

elasticsearch.hosts:elasticsearch地址

elasticsearch.requestTimeout:请求elasticsearch超时时间,默认为30000,此处可根据情况设置

4、启动kibana

由于kibana不建议使用root用户启动,如果用root启动,需要加--allow-root参数

启动成功。

5、访问kibana

1.浏览器输入http://192.168.149.135:5601/,如下图:

看到这个界面,说明Kibanan已成功安装。

Discover:可视化查询分析器 Visualize:统计分析图表 Dashboard:自定义主面板(添加图表) Timelion:Timelion是一个kibana时间序列展示组件(暂时不用) Dev Tools:Console控制台(同CURL/POSTER,操作ES代码工具,代码提示,很方便) Management:管理索引库(index)、已保存的搜索和可视化结果(save objects)、设置 kibana 服务器属性。

windows安装:(46条消息) Kibana介绍、安装和使用_少年单排,记录点滴 -CSDN博客_kibana

3.ElasticSearch核心概念 

索引(index)

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

映射(mapping)

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

文档(document)

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

倒排索引

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

类型(type)

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

4.脚本操作ES

4.1RESTful风格介绍

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

2.基于HTTP。

3.使用XML格式定义或JSON格式定义。

4.每一个URI代表1种资源。

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

GET:用来获取资源

POST:用来新建资源(也可以用于更新资源)

PUT:用来更新资源

DELETE:用来删除资源

 4.2操作索引

PUT

查询

•删除索引

•关闭、打开索引

4.3ES数据类型

  1. 简单数据类型

  • 字符串

聚合:相当于mysql 中的sum(求和)

  • 数值

  • 布尔:boolean

  • 二进制:binary

  • 范围类型

  • 日期:date

  1. 复杂数据类型

•数组:[ ] Nested: nested (for arrays of JSON objects 数组类型的JSON对象)

•对象:{ } Object: object(for single JSON objects 单个JSON对象)

4.4操作映射

#创建索引并添加映射

添加字段

4.5操作文档 

•添加文档,指定id

•添加文档,不指定id  

5.分词器 

 5.1分词器介绍

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

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

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

•支持用户词典扩展定义

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

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

5.2 ik分词器安装

参见 ik分词器安装.md

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

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

5.3ik分词器使用

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

1、ik_max_word

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

ik_max_word分词器执行如下:

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

ik_smart分词器执行如下:

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

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

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

•词条查询:term

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

•全文查询:match

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

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

2.添加文档

 3.查询映射

 

 4.查看分词效果

5.词条查询:term 

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

6.全文查询:match

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

6.ElasticSearch JavaAPI

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

6.2创建索引

1.添加索引

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

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

 

 6.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);

    }

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

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

---------------------------------------------------------------------------------------------------------------------------------

内容有部分存在书籍、课堂、网络记录,如有雷同纯属巧合

举报

相关推荐

0 条评论