环境介绍:
win7系统,es服务器为6.4.2(原文提供下载地址,废了好大劲才找到,搜索引擎用的好,确实差不少)

如何快速创建springboot工程
访问https://start.spring.io/ ,搜索web,springdata,我们使用springdata方式链接es

首先给出项目结构图如下图所示(启动项目,访问对应的url,也可以通过可视化工具查看es数据)

接下来给出项目代码
controller

package com.example.demo.controller;
    import com.example.demo.resp.entity.Commodity;
    import com.example.demo.resp.service.CommodityService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.domain.Page;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.bind.annotation.RestController;
    import java.util.List;
    @RestController
    public class ElasticSearchController {
        @Autowired
        private CommodityService commodityService;
        @RequestMapping("/commodity/{name}")
        @ResponseBody
        public List<Commodity> getCommodityByName(@PathVariable String name) {
            List<Commodity> list = commodityService.findByName(name);
            System.out.println(list);
            return list;
        }
    @RequestMapping("/save")
    @ResponseBody
    public void Save() {
        Commodity commodity = new Commodity();
        commodity.setSkuId("1501009001");
        commodity.setName("原味切片面包(10片装)");
        commodity.setCategory("101");
        commodity.setPrice(880);
        commodity.setBrand("良品铺子");
        Commodity save1 = commodityService.save(commodity);
        System.out.println(save1.getSkuId() + "==========");
        commodity = new Commodity();
        commodity.setSkuId("1501009002");
        commodity.setName("原味切片面包(6片装)");
        commodity.setCategory("101");
        commodity.setPrice(680);
        commodity.setBrand("良品铺子");
        Commodity save2 = commodityService.save(commodity);
        System.out.println(save2.getSkuId() + "==========");
        commodity = new Commodity();
        commodity.setSkuId("1501009004");
        commodity.setName("元气吐司850g");
        commodity.setCategory("101");
        commodity.setPrice(120);
        commodity.setBrand("百草味");
        Commodity save3 = commodityService.save(commodity);
        System.out.println(save3.getSkuId() + "==========");
    }

    /**
     * 分页查询
     */
    @RequestMapping("/pagequery")
    @ResponseBody
    public Page<Commodity> pageQuery() {
        Page<Commodity> pageResult = commodityService.pageQuery(0, 10, "切片");
        return pageResult;
    }
}

repository

package com.example.demo.resp.dao;
import com.example.demo.resp.entity.Commodity;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface CommodityRepository extends ElasticsearchRepository<Commodity, String> {
    //springdata 帮你实现 对应的query
    // List<Commodity> findByName(String name);
}

entity(getset省略)

@Document(indexName = "commodity")
public class Commodity implements Serializable {
@Id
private String skuId;
private String name;
private String category;
private Integer price;
private String brand;
private Integer stock;

service

package com.example.demo.resp.service;
import com.example.demo.resp.entity.Commodity;
import org.springframework.data.domain.Page;
import java.util.List;
public interface CommodityService {
    long count();
    Commodity save(Commodity commodity);
    void delete(Commodity commodity);
    Iterable<Commodity> getAll();
    List<Commodity> findByName(String name);
    Page<Commodity> pageQuery(Integer pageNo, Integer pageSize, String kw);
}

service实现类

package com.example.demo.resp.service.impl;
import com.example.demo.resp.dao.CommodityRepository;
import com.example.demo.resp.entity.Commodity;
import com.example.demo.resp.service.CommodityService;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
@Service
public class CommodityServiceImpl implements CommodityService {
    @Resource
    private CommodityRepository commodityRepository;
    @Override
    public long count() {
        return commodityRepository.count();
    }

    /**
     * 插入向es商品 ,场景可以监听binlog 通过三方框架,或者mq,及时更新新增商品
     *
     * @param commodity
     * @return
     */
    @Override
    public Commodity save(Commodity commodity) {
        return commodityRepository.save(commodity);
    }

    /**
     * 删除
     *
     * @param commodity
     */
    @Override
    public void delete(Commodity commodity) {
        commodityRepository.delete(commodity);
    }

    /**
     * 查询所有商品
     *
     * @return
     */
    @Override
    public Iterable<Commodity> getAll() {
        return commodityRepository.findAll();
    }

    /**
     * @param name
     * @return
     * @Query("{"bool" : {"must" : {"field" : {"name" : "?0"}}}}")  es中查询方式 为json格式数据
     */
    @Override
    public List<Commodity> findByName(String name) {
        List<Commodity> list = new ArrayList<>();
        /**
         * 匹配查询条件  后面如果写的文章的话 会具体写查询条件
         *
         */
        MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("name", name);
        Iterable<Commodity> iterable = commodityRepository.search(matchQueryBuilder);
        iterable.forEach(e -> list.add(e));
        return list;
    }

    /**
     * @param pageNo
     * @param pageSize
     * @param kw
     * @return
     */
    @Override
    public Page<Commodity> pageQuery(Integer pageNo, Integer pageSize, String kw) {
        SearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.matchPhraseQuery("name", kw))
                .withPageable(PageRequest.of(pageNo, pageSize))
                .build();
        return commodityRepository.search(searchQuery);
    }
}

config

package com.example.demo;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
@Configuration
@EnableElasticsearchRepositories(basePackages = "com.example.demo.resp.dao")
class Config {

}

启动类

package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {

   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }
}

属性文件(链接超时没有加)

# ELASTICSEARCH (ElasticsearchProperties)
# Elasticsearch cluster name. 集群名称
spring.data.elasticsearch.cluster-name=myapplication
# Comma-separated list of cluster node addresses.
#你的ip地址
spring.data.elasticsearch.cluster-nodes=***:9300
# Whether to enable Elasticsearch repositories.
spring.data.elasticsearch.repositories.enabled=true

pom文件

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-elasticsearch -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

项目数据如下

springboot整合es查询时间段 springboot整合elasticsearch6_springboot整合es查询时间段


springboot整合es查询时间段 springboot整合elasticsearch6_elasticsearch闪退_02


集成es遇到的问题

springboot整合es查询时间段 springboot整合elasticsearch6_elasticsearch闪退_03

解决问题,主要是es的yml文件对应修改几个参数位置

springboot整合es查询时间段 springboot整合elasticsearch6_springboot整合es查询时间段_04

为什么没有用官方最高7.2版本的es?多次启动闪退?
因为springdata版本不匹配,会报一个错误,低版本的springboot链接高版本的es,es版本号为7.2,从报错来看,也说明学习netty的重要性。

多次闪退解决办法,修改yml文件的nodes注释

springboot整合es查询时间段 springboot整合elasticsearch6_springboot整合es查询时间段_05


注解去掉,就不闪退了。

springboot整合es查询时间段 springboot整合elasticsearch6_elasticsearch闪退_06


给出es6.x版本下载地址(网速可能非常慢,原文给出jar包)

通过springdata可以快速使用es,而不用了解es搜索的语法,springdata帮我们封装了。代码同关系数据库是一样的原理。

springboot整合es查询时间段 springboot整合elasticsearch6_springboot整合es查询时间段_07

总结:文章一直没发出来就是因为使用es版本过高,导致报错,其实如果你确实想用最新的es,可以自己springdata源码 ,自己打jar包去依赖,给出如下地址,感谢阅读。