一、前言
进行SpringBoot整合Spring Data ES的时候遇到了一些坑,基本都是版本控制导致,同样在搭建ES Linux环境的时候也遇到了一些坑,还是总结一下,避免新人遇到跟我一样的情况

二、ES 在Linux下的环境搭建

因为搭建其实是比较基础,且简单的,我这边只会指出容易出错的地方,避免大家遇到类似问题

  1. 首先去官方下载最新的依赖包,我这边选用的是ES 5.5.0版本,为了跟spring data ES整合使用,后面会讲到

https://www.elastic.co/cn/downloads/past-releases#elasticsearch

  1. 将对应的包放在Linux终端下并解压,es目录我改了名字,初学者不要疑惑
    在这里插入图片描述

  2. 由于ES在Linux下的限制,需要作如下配置,否则会启动失败

  3. 修改/etc/security/limits.conf 文件

* soft nofile 65536
* hard nofile 131072
* soft nproc 2048
* hard nproc 4096
  1. 修改 /etc/sysctl.conf 增加 vm.max_map_count=262145
  2. 修改ES config目录下的elasticsearch.yml及jvm.options配置文件
    在这里插入图片描述
    我的配置如图
######elasticsearch.yml########
node.name: node-1 #配置当前es节点名称(默认是被注释的,并且默认有一个节点名)
cluster.name: my-application #默认是被注释的,并且默认有一个集群名
path.data: /home/es/data # 数据目录位置
path.logs: /home/es/logs # 日志目录位置
network.host: 0.0.0.0   #绑定的ip:默认只允许本机访问,修改为0.0.0.0后则可以远程访问cluster.initial_master_nodes: ["node-1", "node-2"] #默认是被注释的 设置master节点列表 用逗号分隔

######jvm.options#######
-Xms256m    -Xmx256m   #修改为自定义的的内存大小
  1. 由于ES必须要普通用户才能启动,添加普通用户,并且对es目录赋予权限
adduser es
chown -R es:es + es目录及配置文件制定的data、logs目录同样赋予权限否则会报错
  1. 切换到es用户下,启动es
su es
./es/elasticsearch/bin/elasticsearch   #启动脚本
  1. 出现如图所示表示启动成功,并通过端口访问ip:9200

防火墙必须关闭,否则无法请求成功
在这里插入图片描述
在这里插入图片描述

四、ES基础概念及基础语法使用

  • ES是一个分布式搜索型的数据库,它的数据存储方式是以json形式存储,而json数据属于轻量级可序列化,而且简单、简洁、易于阅读,详情参考官方中文文档

https://www.elastic.co/guide/cn/elasticsearch/guide/current/_document_oriented.html

  • ES中的index、type、document、filed的概念

index,索引就类似于MySQL中的数据库的概念
type,类型就类似于MySQL中的表的概念
document,文档就类似于MySQL中的每行记录
filed,字段就类似于MySQL中的column字段属性

  • 当然ES中还有一个分词器的概念,这个分词器对ES倒排索引起到了决定性作用,而且倒排索引是ES被各大企业青睐的原因所在,可参考官方文档好好了解这块

基础语法使用

由于ES支持RestFull API形式并结合DSL语言特性进行请求来对数据进行CRUD操作

  • 复合查询
//根据gameId、uid匹配查询
http://192.168.55.37:9200/索引/类型/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "uid": 90001388   
          }
        },
        {
          "match": {
            "gameId": "ioszhengbanziyunying"
          }
        }
      ]
    }
  }
}
  • 精准查询

//【term可用match代替】
http://192.168.55.37:9200/索引/类型/_search
{
  "query": {
    "term": {
      "uid": 90001388
    }
  }
}

  • 范围查询

http://192.168.55.37:9200/索引/类型/_search
{
  "query": {
    "range": {
      "utime": {
        "gte": 1527860849,
        "lte": 1533131249
      }
    }
  }
}

  • 聚合查询
// 最大/最小值查询可将sum改成max/min即可
http://192.168.55.37:9200/索引/类型/_search
{
  "query": {
    "term": {
      "uid": 90001352
    }
  },
  "size": 0,
  "aggs": {
    "payPrice_of_sum": {
      "sum": {
        "field": "payPrice"
      }
    }
  }
}
  • 删除语法

curl -XDELETE 'http://192.168.55.37:9200/索引/类型/_query?pretty' -d 
'{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "uid": "90001794"
          }
        },
        {
          "term": {
            "gameId": "1483086858573"
          }
        }
      ]
    }
  }
}'

  • 筛选求时间差值下符合条件的数据

GET /track_log-2020-*/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "app_id.keyword": {
              "value": "34234234234234"
            }
          }
        }
      ],
      "filter": {
        "script": {
          "script": {
            "source": "doc['server_time'].value.millis-doc['client_time'].value.millis>60000",
            "lang":"painless"
          }
        }
      }
    }
  }
}

四、后端SpringBoot整合Spring Data ES

  • 首先pom依赖包
<!-- springboot选用的是2.0.8.RELEASE,同样spring data ES也是2.0.8.RELEASE -->
 <parent>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-parent</artifactId>
     <version>2.0.8.RELEASE</version>
     <relativePath/> <!-- lookup parent from repository -->
 </parent>

 <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
 </dependency>
 <dependency>
    <groupId>org.springframework.boot</groupId>
 	<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
 </dependency>
  • 打点进去能够看到spring-boot-starter-data-elasticsearch的依赖的ES客户端版本是5.5.0版本,与我搭建ES server想匹配
    在这里插入图片描述
  • 编写application.yml配置

server:
  port: 8011
spring:
  data:
    elasticsearch:
      cluster-nodes: 192.168.245.128:9300
      cluster-name: my-application
      repositories:
        enabled: true
  • 定义一个实体类,与ES数据进行映射
@Data
@Document(indexName = "test",type = "test_table")   //定义索引、类型
public class TrackerLog {

    @Id
    private Long id;

    private Date clientTime;

    private Date serverTime;

    private String content;

}

  • 自定义接口来继承ElasticsearchRepository来实现CRUD操作
// ElasticsearchRepository传实体类对象,主键类型
public interface BaseElasticsearchRepository extends ElasticsearchRepository<TrackerLog,Long> {
    //自定义查询方法
    List<TrackerLog> findByContent(String content);
}
  • 定义EsController通过web形式进行接口调用

这边就简单写,正常要controller - > servcie -> dao

@RestController
public class EsController {

    @Autowired
    private BaseElasticsearchRepository baseEs;
    
    //创建索引、类型
    @GetMapping("/index")
    public String initEs(){
        TrackerLog trackerLog = new TrackerLog();
        baseEs.save(trackerLog);
        return "true";
    }
    //往ES写入数据
    @GetMapping("/create/{id}")
    public String putEsData(@PathVariable("id") Long id){
        TrackerLog trackerLog = new TrackerLog();

        trackerLog.setId(id);
        trackerLog.setClientTime(new Date());
        trackerLog.setServerTime(new Date());
        trackerLog.setContent("测试");

        baseEs.save(trackerLog);
        return "true";
    }
    //查询ES数据
    @GetMapping("/get/{id}")
    public TrackerLog getEsData(@PathVariable("id")Long id){
        Optional<TrackerLog> datas = baseEs.findById(id);
        return datas.get();
    }

}
  • 启动主启动类,访问localhost:8011端口进行接口调用即可

在这里插入图片描述
在这里插入图片描述

五、ES与springdataES版本控制

  • 大家要严格按照官方提供的版本匹配来,否则会因为版本不匹配出现一系列错误,我在这方面踩坑较多,希望大家不要跟我浪费同样的时间
    在这里插入图片描述
GitHub 加速计划 / li / linux-dash
10.39 K
1.2 K
下载
A beautiful web dashboard for Linux
最近提交(Master分支:22 天前 )
186a802e added ecosystem file for PM2 4 年前
5def40a3 Add host customization support for the NodeJS version 4 年前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐