【java_wxid项目】【第十三章】【Elasticsearch集成】

这篇具有很好参考价值的文章主要介绍了【java_wxid项目】【第十三章】【Elasticsearch集成】。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

主项目链接:https://gitee.com/java_wxid/java_wxid
项目架构及博文总结:

  • 点击:【使用Spring Boot快速构建应用】
  • 点击:【使用Spring Cloud Open Feign基于动态代理动态构造请求实现与其他系统进行交互】
  • 点击:【使用Spring Cloud Hystrix实现服务容错、熔断、降级、监控】
  • 点击:【使用Spring Cloud Ribbon以库的方式集成到服务的消费方实现客户端负载均衡】
  • 点击:【使用Spring Cloud Gateway作为API网关服务进行请求拦截、服务分发、降级、限流】
  • 点击:【使用Spring Cloud Security Oauth2作为微服务统一认证中心实现用户认证和授权访问】
  • 点击:【使用Spring Cloud Stream作为消息驱动用于动态的切换中间件】
  • 点击:【使用Spring Cloud Skywalking基于字节码注入通过探针方式进行链路追踪、分布式追踪、性能指标分析、应用和服务依赖分析】
  • 点击:【使用Spring Cloud Alibaba Nacos实现服务注册/发现/续约/剔除/下线、心跳检测、服务配置管理、基于长轮训机制实现配置动态变更】
  • 点击:【使用Spring Cloud Alibaba Seata作为对项目代码无入侵的分布式事务解决方案】
  • 点击:【使用Spring Cloud Alibaba Sentinel实现高可用流量防护】
  • 点击:【使用Apache ShardingSphere作为关系型数据库中间件实现分库分表、读写分离】
  • 点击:【使用Apache Mybatis作为持久层框架用于定制化SQL、存储过程以及高级映射】
  • 点击:【使用Redis作为高性能分布式缓存数据库】
  • 点击:【使用ElasticSearch全文搜索】
  • 点击:【使用MongoDB非关系型数据库】
  • 点击:【使用xxl-job作为分布式任务调度平台】
  • 点击:【使用Elasticsearch + Logstash + Kibana作为日志收集系统】
  • 点击:【使用Apifox作为API文档、API调试、API Mock、API自动化测试】
  • 点击:【使用Apache Spark作为基于内存计算的大数据分析引擎用于批处理、交互式查询】
  • 点击:【使用ETL工具将数据源抽取到HDFS作为高可靠、高吞吐量的分布式文件系统存储,通过Hive清洗、处理和计算原始数据,Hive清洗处理后的结果,将存入Hbase,海量数据随机查询场景从HBase查询数据】
  • 点击:【使用领域驱动DDD设计和设计模式进行开发】
  • 点击:【使用Netty基于Java NIO封装的高性能的网络通信框架】
  • 点击:【使用k8s、docker、docker-compose、宝塔面板进行环境搭建和部署】
  • 点击:【使用Vue渐进式JavaScript框架作为适用场景丰富的Web前端框架】
  • 点击:【分享人才筛选、工作分配、高效办公、项目推动等团队管理经验】

项目模块:
前期规划,实现部分

java_wxid   
├── demo                                                            // 演示模块
│     └── 模块名称:apache-mybatis-demo模块                            //Apache Mybatis集成(已实现并有博文总结)
│     └── 模块名称:apache-shardingsphere-demo模块                     //Apache ShardingSphere集成(已实现并有博文总结)
│     └── 模块名称:design-demo模块                                    //设计模式实战落地(已实现并有博文总结)
│     └── 模块名称:elasticsearch-demo模块                             //ElasticSearch集成(已实现并有博文总结)
│     └── 模块名称:mongodb-demo模块                                   //MongoDB集成(已实现并有博文总结)
│     └── 模块名称:redis-demo模块                                     //Redis集成(已实现并有博文总结)
│     └── 模块名称:spring-boot-demo模块                               //Spring Boot快速构建应用(已实现并有博文总结)
│     └── 模块名称:spring-cloud-alibaba-nacos-demo模块                //Spring Cloud Alibaba Nacos集成(已实现并有博文总结)
│     └── 模块名称:spring-cloud-alibaba-seata-demo模块                //Spring Cloud Alibaba Seata集成(已实现并有博文总结)
│     └── 模块名称:spring-cloud-alibaba-sentinel-demo模块             //Spring Cloud Alibaba Sentinel集成(已实现并有博文总结)
│     └── 模块名称:spring-cloud-gateway-demo模块                      //Spring Cloud Gateway集成(已实现并有博文总结)
│     └── 模块名称:spring-cloud-hystrix-demo模块                      //Spring Cloud Hystrix集成(已实现并有博文总结)
│     └── 模块名称:spring-cloud-open-feign-demo模块                   //Spring Cloud Open Feign集成(已实现并有博文总结)
│     └── 模块名称:spring-cloud-ribbon-demo模块                       //Spring Cloud Ribbon集成(已实现并有博文总结)
│     └── 模块名称:spring-cloud-security-oauth2-demo模块              //Spring Cloud Security Oauth2集成(已实现并有博文总结)
│     └── 模块名称:spring-cloud-security-oauth2-sso-client-demo模块   //Spring Cloud Security Oauth2集成(已实现并有博文总结)
│     └── 模块名称:spring-cloud-skywalking-demo模块                   //Spring Cloud Skywalking集成(已实现并有博文总结)
│     └── 模块名称:spring-cloud-stream-demo模块                       //Spring Cloud Stream集成(已实现并有博文总结)
│     └── 模块名称:swagger-demo模块                                   //springfox-swagger2集成(已实现并有博文总结)
│     └── 模块名称:xxl-job模块                                        //xxl-job集成(已实现并有博文总结)
│     └── 模块名称:apache-spark-demo模块                              //Apache Spark集成
│     └── 模块名称:etl-hdfs-hive-hbase-demo模块                       //ETL、HDFS、Hive、Hbase集成
│     └── 模块名称:ddd-mode-demo模块                                  //DDD领域设计
│     └── 模块名称:netty-demo模块                                     //Netty集成
│     └── 模块名称:vue-demo模块                                       //前端vue集成
├── document                                                        // 文档
│     └── JavaKnowledgeDocument                                     //java知识点
│           └── java基础知识点.md                     
│           └── mq知识点.md
│           └── mysql知识点.md
│           └── redis知识点.md
│           └── springcould知识点.md
│           └── spring知识点.md
│     └── FounderDocument                                           //创始人
│           └── 创始人.md

系列文章:快速集成各种微服务相关的技术,帮助大家可以快速集成到自己的项目中,节约开发时间。
提示:系列文章还未全部完成,后续的文章,会慢慢补充进去的。

准备工作

创建一个新的虚拟机,文章地址:https://blog.csdn.net/java_wxid/article/details/127132378

安装Elasticsearch

下载软件安装包:
链接:https://pan.baidu.com/s/1XRGHX9lqF21k0gaaHv8ReA?pwd=2022
提取码:2022
–来自百度网盘超级会员V2的分享
安装es可能会出现的错误解决办法:https://blog.csdn.net/ADCadc123456789/article/details/104806771

创建普通用户

ES不能使用root用户来启动,必须使用普通用户来安装启动。这里我们创建一个普通用户以及定义一些常规目录用于存放我们的数据文件以及安装包等。

创建一个es专门的用户(必须)
使用root用户在服务器执行以下命令

先创建组, 再创建用户:
1)创建 elasticsearch 用户组

groupadd elasticsearch

2)创建用户 liaozhiwei 并设置密码

useradd liaozhiwei
passwd liaozhiwei

3)# 创建es文件夹,
并修改owner为 liaozhiwei用户

mkdir -p /usr/local/es

4)用户es 添加到 elasticsearch 用户组

usermod -G elasticsearch liaozhiwei

先上传安装包elasticsearch-7.6.1-linux-x86_64.tar.gz进行解压,解压目录为/usr/local/es,然后授权

tar -zxvf elasticsearch-7.6.1-linux-x86_64.tar.gz
chown -R liaozhiwei /usr/local/es/elasticsearch-7.6.1

5)设置sudo权限
#为了让普通用户有更大的操作权限,我们一般都会给普通用户设置sudo权限,方便普通用户的操作
#三台机器使用root用户执行visudo命令然后为es用户添加权限

visudo

#在root ALL=(ALL) ALL 一行下面
#添加liaozhiwei用户 如下:

liaozhiwei ALL=(ALL) ALL

#添加成功保存后切换到liaozhiwei用户操作
[root@localhost ~]# su liaozhiwei
[liaozhiwei@localhost root]$

上传压缩包并解压

将es的安装包下载并上传到服务器的/user/local/es路径下,然后进行解压
使用liaozhiwei用户来执行以下操作,将es安装包上传到指定服务器,并使用es用户执行以下命令解压。

su root
cd /usr/local/es/
sudo chmod 777 elasticsearch-7.6.1-linux-x86_64.tar.gz 
tar -zvxf elasticsearch-7.6.1-linux-x86_64.tar.gz -C /usr/local/es/
修改配置文件
修改elasticsearch.yml

进入服务器使用baiqi用户来修改配置文件

cd /usr/local/es/elasticsearch-7.6.1/config
mkdir -p /usr/local/es/elasticsearch-7.6.1/log
mkdir -p /usr/local/es/elasticsearch-7.6.1/data
rm -rf elasticsearch.yml
vim elasticsearch.yml


cluster.name: liaozhiwei-es
node.name: node1
path.data: /usr/local/es/elasticsearch-7.6.1/data
path.logs: /usr/local/es/elasticsearch-7.6.1/log
network.host: 192.168.160.128
http.port: 9200
discovery.seed_hosts: ["192.168.160.128"]
cluster.initial_master_nodes: ["node1"]
bootstrap.system_call_filter: false
bootstrap.memory_lock: false
http.cors.enabled: true
http.cors.allow-origin: "*"
xpack.security.enabled: true
xpack.license.self_generated.type: basic
xpack.security.transport.ssl.enabled: true
修改jvm.option

修改jvm.option配置文件,调整jvm堆内存大小。
node1.liaozhiwei.cn使用liaozhiwei用户执行以下命令调整jvm堆内存大小,每个人根据自己服务器的内存大小来进行调整。

cd /usr/local/es/elasticsearch-7.6.1/config
vim jvm.options
-Xms2g
-Xmx2g
修改系统配置,解决启动时候的问题

由于现在使用普通用户来安装es服务,且es服务对服务器的资源要求比较多,包括内存大小,线程数等。所以我们需要给普通用户解开资源的束缚。

普通用户打开文件的最大数限制

问题错误信息描述:
max file descriptors [4096] for elasticsearch process likely too low, increase to at least [65536]

ES因为需要大量的创建索引文件,需要大量的打开系统的文件,所以我们需要解除linux系统当中打开文件最大数目的限制,不然ES启动就会抛错,三台机器使用baiqi用户执行以下命令解除打开文件数据的限制。

sudo vi /etc/security/limits.conf

添加如下内容: 注意*不要去掉了

* soft nofile 65536
* hard nofile 131072
* soft nproc 2048
* hard nproc 4096
此文件修改后需要重新登录用户,才会生效

普通用户启动线程数限制
问题错误信息描述
max number of threads [1024] for user [es] likely too low, increase to at least [4096]

修改普通用户可以创建的最大线程数
max number of threads [1024] for user [es] likely too low, increase to at least [4096]

原因:无法创建本地线程问题,用户最大可创建线程数太小

解决方案:修改90-nproc.conf 配置文件。
三台机器使用baiqi用户执行以下命令修改配置文件

Centos6
sudo vi /etc/security/limits.d/90-nproc.conf
Centos7
sudo vi /etc/security/limits.d/20-nproc.conf

找到如下内容:

* soft nproc 1024#修改为
* soft nproc 4096
普通用户调大虚拟内存

错误信息描述:
max virtual memory areas vm.max_map_count [65530] likely too low, increase to at least [262144]

原因:最大虚拟内存太小,解决方案:调大系统的虚拟内存,每次启动机器都手动执行下。三台机器执行以下命令

vim /etc/sysctl.conf

追加以下内容:

vm.max_map_count=262144 

保存后,执行:

sysctl -p

备注:以上三个问题解决完成之后,重新连接secureCRT或者重新连接xshell生效

设置用户密码登录
cd /usr/local/es/elasticsearch-7.6.1/bin
./elasticsearch-setup-passwords interactive

这里会设置六个账号的密码:elastic,apm_system,kibana,logstash_system,beats_system,remote_monitoring_user.
我这里统一使用liaozhiwei作为这六个账号的密码

elastic作为我直接访问es的账号

启动ES服务

三台机器使用liaozhiwei用户执行以下命令启动es服务

nohup /usr/local/es/elasticsearch-7.6.1/bin/elasticsearch 2>&1 &

后台启动ES 进入bin目录 ./elasticsearch -d
启动成功之后jsp即可看到es的服务进程,并且访问页面

http://192.168.160.128:9200/?pretty

上面配置了用户密码这里访问也需要输入

elastic
liaozhiwei

【java_wxid项目】【第十三章】【Elasticsearch集成】

能够看到es启动之后的一些信息
注意:如果哪一台机器服务启动失败,那么就到哪一台机器的

/usr/local/es/elasticsearch-7.6.1/log

这个路径下面去查看错误日志

开启Linux防火墙

systemctl start firewalld 
systemctl enable firewalld

centos开放端口宿主机访问

firewall-cmd --add-port=9200/tcp --permanent
firewall-cmd --reload

查询端口是否开启命令

firewall-cmd --query-port=9200/tcp

注意:启动ES的时候出现 Permission denied。原因:当前的用户没有对XX文件或目录的操作权限。

客户端Kibana安装

ES主流客户端Kibana,开放9200端口与图形界面客户端交互
1)下载Kibana放之/usr/local/es目录中
2)解压文件:tar -zxvf kibana-X.X.X-linux-x86_64.tar.gz
3)进入/usr/local/es/kibana-X.X.X-linux-x86_64/config目录
4)使用vi编辑器:

vi /usr/local/es/kibana-7.6.1-linux-x86_64/config/kibana.yml
server.port: 5601
server.host: "192.168.160.128"
elasticsearch.hosts: ["http://192.168.160.128:9200"]
elasticsearch.username: "kibana"
elasticsearch.password: "liaozhiwei"
i18n.locale: "zh-CN"

centos开放端口宿主机访问

firewall-cmd --add-port=5601/tcp --permanent
firewall-cmd --reload

查询端口是否开启命令

firewall-cmd --query-port=5601/tcp

切换root用户 给es用户这个文件的权限

su root
sudo chown -R liaozhiwei /usr/local/es/kibana-7.6.1-linux-x86_64

5)启动Kibana

./usr/local/es/kibana-7.6.1-linux-x86_64/bin/kibana

后台启动kibana

cd /usr/local/es/kibana-7.6.1-linux-x86_64/bin/
nohup  ./kibana &

6)访问Kibana

http://192.168.160.128:5601/app/kibana

上面配置了用户密码这里访问也需要输入

elastic
liaozhiwei

安装IK分词器

我们后续也需要使用Elasticsearch来进行中文分词,所以需要单独给Elasticsearch安装IK分词器插件。以下为具体安装步骤:
下载Elasticsearch IK分词器
https://github.com/medcl/elasticsearch-analysis-ik/releases

切换到liaozhiwei用户,并在es的安装目录下/plugins创建ik

mkdir -p /usr/local/es/elasticsearch-7.6.1/plugins/ik

将下载的ik分词器上传并解压到该目录

cd /usr/local/es/elasticsearch-7.6.1/plugins/ik
unzip  elasticsearch-analysis-ik-7.6.1.zip 

重启Elasticsearch

ps -ef | grep elastic
kill -9 PID
nohup /usr/local/es/elasticsearch-7.6.1/bin/elasticsearch 2>&1 &

创建elasticsearch-demo项目

项目代码:https://gitee.com/java_wxid/java_wxid/tree/master/demo/elasticsearch-demo
项目结构如下(示例):
【java_wxid项目】【第十三章】【Elasticsearch集成】

修改pom.xml

代码如下(示例):

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>


    <groupId>com.example</groupId>
    <artifactId>elasticsearch-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>elasticsearch-demo</name>
    <description>Demo project for Spring Boot</description>
    <!--    属性配置-->
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <!--引入 Spring Boot、Spring Cloud、Spring Cloud Alibaba 三者 BOM 文件,进行依赖版本的管理,防止不兼容。
        在 https://dwz.cn/mcLIfNKt 文章中,Spring Cloud Alibaba 开发团队推荐了三者的依赖关系-->
        <spring.boot.version>2.3.12.RELEASE</spring.boot.version>
        <spring.cloud.version>Hoxton.SR12</spring.cloud.version>
        <spring.cloud.alibaba.version>2.2.7.RELEASE</spring.cloud.alibaba.version>
        <elasticsearch.version>7.12.0</elasticsearch.version>
    </properties>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--        代表web模块,在这个模块中含了许多JAR包,有spring相关的jar,内置tomcat服务器,jackson等,这些web项目中常用的的功能都会自动引入-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--        在SpringBoot 2.4.x的版本之后,对于bootstrap.properties/bootstrap.yaml配置文件(我们合起来成为Bootstrap配置文件)的支持,其实这个jar包里什么都没有,就只有一个标识类Marker,用来标识要开启Bootstrap配置文件的支持,由于父类用了2.5.6版本需要导入如下的依赖-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-bootstrap</artifactId>
            <version>3.1.0</version>
        </dependency>

        <!-- 重写覆盖 spring-boot-dependencies 中的依赖版本  -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-elasticsearch</artifactId>
            <version>4.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>${elasticsearch.version}</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>${elasticsearch.version}</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-client</artifactId>
            <version>${elasticsearch.version}</version>
        </dependency>

        <!--        lombok插件-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>

    </dependencies>

    <!--
    引入 Spring Boot、Spring Cloud、Spring Cloud Alibaba 三者 BOM 文件,进行依赖版本的管理,防止不兼容。
    在 https://dwz.cn/mcLIfNKt 文章中,Spring Cloud Alibaba 开发团队推荐了三者的依赖关系
 -->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-parent</artifactId>
                <version>${spring.boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring.cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${spring.cloud.alibaba.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
</project>

创建ElasticSearchController

代码如下(示例):

package com.example.elasticsearchdemo.controller;

import com.example.elasticsearchdemo.model.Userinfo;
import com.example.elasticsearchdemo.service.ElasticsearchService;
import org.springframework.data.elasticsearch.core.SearchPage;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Iterator;

/**
 * @author zhiwei Liao
 * @Description
 * @Date create in 2022/9/12 0012 21:03
 */
@RestController
public class ElasticSearchController {

    @Autowired
    private ElasticsearchService elasticsearchService;

    @GetMapping("/importData")
    public void importData() {
        elasticsearchService.importData();
    }

    @GetMapping("/search")
    public SearchPage<Userinfo> search(){
        return elasticsearchService.search();
    }


    @GetMapping("/findAll")
    public Iterator<Userinfo> findAll(){
        return elasticsearchService.findAll();
    }
}

创建ElasticsearchDao

代码如下(示例):

package com.example.elasticsearchdemo.dao;

/**
 * @author zhiwei Liao
 * @Description
 * @Date create in 2022/9/12 0012 21:03
 */
import com.example.elasticsearchdemo.model.Userinfo;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;

@Repository
//Userinfo对应实体 Long对应主键
public interface ElasticsearchDao extends ElasticsearchRepository<Userinfo,Long> {
}

创建Userinfo

代码如下(示例):

package com.example.elasticsearchdemo.model;

import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
import java.io.Serializable;

/**
 * @author zhiwei Liao
 * @Description
 * @Date create in 2022/9/12 0012 21:03
 */

@Data
@Document(indexName = "user", shards = 2, replicas = 2)  //对应索引库和类型
public class Userinfo implements Serializable {

    @Id
    @Field(store = false, type = FieldType.Long)
    private long id;
    @Field(store = false, type = FieldType.Text,analyzer = "ik_smart",searchAnalyzer = "ik_smart")
    private String name;
    @Field(store = false, type = FieldType.Text,analyzer = "ik_smart",searchAnalyzer = "ik_smart")
    private String city;
    @Field(store = false, type = FieldType.Long)
    private Integer age;
    @Field(store = false, type = FieldType.Text,analyzer = "ik_smart",searchAnalyzer = "ik_smart")
    private String remark;
}


创建ElasticsearchService

代码如下(示例):

package com.example.elasticsearchdemo.service;

import com.example.elasticsearchdemo.model.Userinfo;
import org.springframework.data.elasticsearch.core.SearchPage;
import java.util.Iterator;
/**
 * @author zhiwei Liao
 * @Description
 * @Date create in 2022/9/12 0012 21:03
 */
public interface ElasticsearchService {

    void importData();

    SearchPage<Userinfo> search();

    Iterator<Userinfo> findAll();
}

创建ElasticsearchServiceImpl

代码如下(示例):

package com.example.elasticsearchdemo.service.impl;

import com.example.elasticsearchdemo.dao.ElasticsearchDao;
import com.example.elasticsearchdemo.model.Userinfo;
import com.example.elasticsearchdemo.service.ElasticsearchService;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHitSupport;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.SearchPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author zhiwei Liao
 * @Description
 * @Date create in 2022/9/12 0012 21:03
 */
@Service
public class ElasticsearchServiceImpl implements ElasticsearchService {

    @Autowired
    private ElasticsearchDao dao;
    @Resource
    private ElasticsearchDao elasticsearchDao;
    @Resource
    private ElasticsearchRestTemplate elasticsearchTemplate;

    /** @description 导入数据
     * @params []
     * @return void
     * @author lxy
     * @date 2020/9/29 11:06
     **/
    @Override
    public void importData(){
        //从mysql查出所有数据 一般来说可以先查出来是一个对象javabean,然后转换成索引对象Userinfo就行,我这里是直接用的userinfo对象
        List<Userinfo> user = new ArrayList<>();
        Userinfo userinfo = new Userinfo();
        userinfo.setAge(25);
        userinfo.setCity("上海");
        userinfo.setName("廖志伟");
        userinfo.setRemark("remark");
        userinfo.setId(1);
        user.add(userinfo);
        //导入到es
        dao.saveAll(user);
    }

    /** @description es搜索
     * @params [parm]
     * @return java.util.List<com.bwwl.hive.model.Userinfo>
     * @author lxy
     * @date 2020/9/29 11:32
     **/
    @Override
    public SearchPage<Userinfo> search() {
        //TODO 构建查询对象用于封装各种查询条件  NativeSearchQueryBuilder
        //1.构建查询对象
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms("name")
                .field("age").size(30));
        SearchHits<Userinfo> search = elasticsearchTemplate.search(nativeSearchQueryBuilder.build(), Userinfo.class);
        int pageNo = 1;
        int pageSize = 5;
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize);
        //7.获取分页数据
        SearchPage<Userinfo> searchPageResult = SearchHitSupport.searchPageFor(search, pageable);
        System.out.println(String.format("totalPages:%d, pageNo:%d, size:%d", searchPageResult.getTotalPages(), pageNo, pageSize));
        return searchPageResult;
    }


    @Override
    public Iterator<Userinfo> findAll() {
        return elasticsearchDao.findAll().iterator();
    }
}

创建application.yml

代码如下(示例):

server:
  port: 8098
spring:
  application:
    name: elasticsearch-demo
  elasticsearch:
    rest:
      username: elastic
      password: liaozhiwei
      uris: http://192.168.160.128:9200
      connection-timeout: 1000
      read-timeout: 1000

校验Elasticsearch是否正常工作

如下图(示例):

【java_wxid项目】【第十三章】【Elasticsearch集成】

【java_wxid项目】【第十三章】【Elasticsearch集成】

【java_wxid项目】【第十三章】【Elasticsearch集成】文章来源地址https://www.toymoban.com/news/detail-405776.html

到了这里,关于【java_wxid项目】【第十三章】【Elasticsearch集成】的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 第十三章 python之爬虫

    Python基础、函数、模块、面向对象、网络和并发编程、数据库和缓存、 前端、django、Flask、tornado、api、git、爬虫、算法和数据结构、Linux、设计题、客观题、其他

    2024年02月04日
    浏览(38)
  • 《微服务实战》 第十三章 JWT

    【项目实战】Spring boot整合JWT、Vue案例展示用户鉴权 【微服务实战】JWT JSON Web Token(JWT)是目前最流行的跨域身份验证解决方案。 基于JSON的开发标准 用户信息加密到token里,服务器不保存任何用户信息 在传统的用户登录认证中,因为http是无状态的,所以都是采用session方式

    2024年02月06日
    浏览(58)
  • 第十三章 Unity 移动和旋转(上)

    移动和旋转是游戏对象最频繁地操作。我们上个章节简单介绍了Cube的移动和旋转。移动是修改transform的position属性,旋转是修改transform的eulerAngles(欧拉角)属性,两者属性值均可以使用Vector3向量来实现。需要大家注意的是,transform.forward和Vector3.forward的区别(参考坐标系是

    2024年02月05日
    浏览(38)
  • 第十三章_Redis中的BigKey

    MoreKey案例 大批量往redis里面插入2000W测试数据key  Linux Bash下面执行,插入100W # 生成100W条redis批量设置kv的语句(key=kn,value=vn)写入到/tmp目录下的redisTest.txt文件中 for((i=1;i=100*10000;i++)); do echo \\\"set k$i v$i\\\" /tmp/redisTest.txt ;done; 通过redis提供的管道--pipe命令插入100W大批量数据 结合自己

    2024年02月03日
    浏览(33)
  • 精读《图解密码技术》——第十三章 PGP

      PGP是一款由个人编写的密码软件,PGP是为了保护处于极端状况下的人们的隐私而开发的,如果这些人的信息被窃听,那么可能是性命攸关的大事件。   OpenPGP是对密文和数字签名格式进行定义的标准规格。   GNU Privacy Guard ( GnuPG、GPG)是一款基于OpenPGP标准开发的密码学

    2024年02月05日
    浏览(40)
  • 第十三章,枚举与泛型例题

    例题1 结果   例题2 结果   例题3 结果     例题4 结果 例题5  结果 例题6  结果 例题7  结果 例题8  结果

    2024年02月06日
    浏览(41)
  • 《TCP IP网络编程》第十三章

    Linux 中的 send recv:          send 函数定义:         recv 函数的定义:         send 和 recv 函数的最后一个参数是收发数据的可选项,该选项可以用位或(bit OR)运算符(| 运算符)同时传递多个信息。send recv 函数的可选项意义: MSG_OOB:发送紧急消息 :     

    2024年02月15日
    浏览(28)
  • 第十三章 opengl之模型(导入3D模型)

    使用Assimp并创建实际的加载和转换代码。Model类结构如下: Model类包含一个Mesh对象的vector,构造器参数需要一个文件路径。 构造器通过loadModel来加载文件。私有函数将会处理Assimp导入过程中的一部分,私有函数还存储了 文件路径的目录,加载纹理时会用到。 Draw函数的作用:

    2024年02月05日
    浏览(31)
  • 《c++ primer笔记》第十三章 拷贝控制

    1.1拷贝构造函数 ​ 如果一个构造函数的第一个参数是自身类类型的 引用 ,且任何额外参数都由默认值,则此构造函数成为拷贝构造函数。 拷贝构造函数在某些情况下会被隐式地使用,所以不能定义为 expicit 。 合成拷贝构造函数 ​ 合成某某函数 一般出现在我们没定义该函

    2023年04月25日
    浏览(34)
  • Vue3——第十三章(插槽 Slots)

    这里有一个 FancyButton 组件,可以像这样使用: 而 FancyButton 的模板是这样的: slot 元素是一个插槽出口 (slot outlet),标示了父元素提供的插槽内容 (slot content) 将在哪里被渲染。 最终渲染出的 DOM 是这样: 通过使用插槽, FancyButton 仅负责渲染外层的 button (以及相应的样式),而

    2024年02月07日
    浏览(38)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包