创建java工程访问elasticsearch


导入pom

点击查看代码
<?xml version="1.0" encoding="UTF-8"?>

    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.5.6
         
    
    com.fch
    myelasticsearch
    0.0.1-SNAPSHOT
    myelasticsearch
    Demo project for Spring Boot
    
        1.8
    
    
        
            org.projectlombok
            lombok
            true
        

        
            org.springframework.boot
            spring-boot-starter-web
        

        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            2.0.0
        

        
        
            mysql
            mysql-connector-java
        

        
        
            com.alibaba
            druid
            1.1.12
        
        
        
            org.springframework.boot
            spring-boot-starter-data-elasticsearch
        
        
        
            org.springframework.boot
            spring-boot-starter-data-elasticsearch
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
            
                
                    org.junit.vintage
                    junit-vintage-engine
                
            
        
    
    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
            
            
                org.apache.maven.plugins
                maven-resources-plugin
                2.6
            
        
    



配置yml

点击查看代码
server:
  port: 8080
spring:
  application:
    #应用名称
    name: service-sms
    #数据库连接配置
  datasource:
    #配置当前使用的数据源的操作类型
    type: com.alibaba.druid.pool.DruidDataSource
    #配置MySQL的驱动程序类
    driver-class-name: com.mysql.cj.jdbc.Driver
    #数据库连接地址
    url: jdbc:mysql://xxxxxx:3306/esdb?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
    #数据库连接用户名
    username: root
    #数据库连接密码
    password: 1111
    #进行数据库连接池的配置
    dbcp2:
      #初始化提供的连接数
      initial-size: 5
      #数据库连接池的最小维持连接数
      min-idle: 5
      #最大的连接数
      max-total: 5
      #等待连接获取的最大超时时间
      max-wait-millis: 200
      validation-query: SELECT 1
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
  data:
    elasticsearch:
      repositories:
        enabled: true
  elasticsearch:
    rest:
      uris: http://xxxxx:9200
mybatis:
  mapper-locations:
    - classpath:mapper/*.xml

RestClientConfig

点击查看代码
package com.fch.myelasticsearch.config;

import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.RestClients;
import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;

@Configuration
public class RestClientConfig extends AbstractElasticsearchConfiguration {
    @Override
    @Bean
    public RestHighLevelClient elasticsearchClient() {
        final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
                .connectedTo("xxxxx:9200")
                .build();

        return RestClients.create(clientConfiguration).rest();
    }
}

EsController

点击查看代码
package com.fch.myelasticsearch.controller;

import com.alibaba.druid.support.json.JSONUtils;
import com.fch.myelasticsearch.dao.ElastRepository;
import com.fch.myelasticsearch.dao.EsDao;
import com.fch.myelasticsearch.entity.EsProduct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Optional;

@Controller
public class EsController {

    @Autowired
    private EsDao esDao;
    @Autowired
    private ElastRepository elastRepository;

    @RequestMapping("/test")
    @ResponseBody
    public String start(){
        List all = esDao.getAll();
        System.out.println(all);
        for(EsProduct esProduct:all){
            System.out.println("esProduct:"+esProduct);
            elastRepository.save(esProduct);
        }
        return "ok";
    }
    @RequestMapping("/test1")
    @ResponseBody
    public String start1(){
        List zhangsan = elastRepository.findByName("name0");
        System.out.println(zhangsan);
        return "ok1";
    }

    @RequestMapping("/test2")
    @ResponseBody
    public String start2(){

        elastRepository.deleteById("1");
        return "ok2";
    }
}

EsProduct

点击查看代码
package com.fch.myelasticsearch.entity;

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;
@Document(indexName = "myuser",shards = 1,replicas = 0)
public class EsProduct implements Serializable{
    private static final long serialVersionUID = -1L;

    @Id
    private Integer id;
    @Field(type = FieldType.Text)
    private String name;
    @Field(type = FieldType.Text)
    private String sex;
    @Field(type = FieldType.Text)
    private String address;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "EsProduct{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

ElastRepository,导入jpa实现像sql一样的查询

点击查看代码
package com.fch.myelasticsearch.dao;

import com.fch.myelasticsearch.entity.EsProduct;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

import java.util.List;

public interface ElastRepository extends ElasticsearchRepository {
    //1.根据姓名查询
    List findByName(String name);
//
//    //2.根据年龄查询
//    List findByAge(Integer age);
//
//    //3.根据姓名和年龄查询
//    List findByUserNameAndAge(String userName,Integer age);
//
//    //4.根据姓名或年龄查询
//    List findByUserNameOrAge(String userName,Integer age);
//
//    //5.查询年龄大于等于25
//    List findByAgeGreaterThanEqual(Integer age);

}