springboot2.X整合spring-data-elasticsearch

springboot2整合spring-data-elasticsearch

一、简介

二、安装elasticsearch

三、springboot2整合spring-data-elasticsearch

1、版本

  • spring-boot 2.1.3.RELEASE
  • elasticsearch 6.5.0
  • spring-data-elasticsearch 3.1.5.RELEASE

2、引入坐标

 <dependency>
   <groupId>org.springframework.data</groupId>
   <artifactId>spring-data-elasticsearch</artifactId>
 </dependency>

3、增加配置

spring:
  data:
    elasticsearch:
      cluster-name: docker-cluster
      cluster-nodes: 127.0.0.1:9200
      repositories:
        enabled: true

cluster-name 可以访问 http://{ip}:{port} 获取

eg: http://localhost:9200/

完成以上三步,基础工作已经做完了

四、使用spring-data-elasticsearch

1.定义数据模型

比如我这边是以商品为模型

@Data
@Document(indexName = "product",type = "product",shards = 3,replicas = 1)
public class ESProduct implements Serializable{

    @ESId
    @Id
    private String id;
    private String title;
    //private String desc;
    private String sellPoint;
    private Double price;
    private Integer num;
    private String barcode;
    private String image;
    private String cid;
    private String cname;
    private Integer status;
    private Date created;
    private Date updated;

}

2. 建立索引,定义type类型,并定义个字段类型

PUT /product


PUT /product
{
  "settings": {
    "number_of_shards": 3,
    "number_of_replicas": 1
  },
  "mappings": {
    "product": {
			"properties": {
				"updated": {
					"type": "date",
					"format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis"
				},
				"created": {
					"type": "date",
					"format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis"
				},
				"status": {
					"type": "integer"
				},
				"cname": {
					"type": "text"
				},
				"cid": {
					"type": "text"
				},
				"image": {
					"type": "keyword"
				},
				"num": {
					"type": "integer"
				},
				"price": {
					"type": "double"
				},
				"sellPoint": {
					"type": "text"
				},
				"title": {
					"type": "text"
				},
				"id": {
					"type": "keyword"
				}
			}
		}
  }
}

3. 导入数据。

这里留个坑位,以后补

4. 使用

(1)创建es dao

直接继承ElasticsearchRepository这个类,基本的CRUD方法都有了,直接使用

@Repository
public interface ProductRepository extends ElasticsearchRepository<ESProduct,String> {

}

(2)创建es manager

定义接口


public interface ESProductManager {

    //批量增加数据
    void addDocuments(List<ESProduct> products);

    //根据ID查询数据
    ESProduct getProductById(String id);

    //根据产品类别名称分页搜索
    Page<ESProduct> findByCName(String cname, Integer page,Integer count);

    //根据产品类别Id分页搜索
    Page<ESProduct> findByCId(String cname, Pageable pageable);

    //根据时间段检索产品,并且对 sellPoint字段 查询
    Page<ESProduct> getProductByCreateTime(Date startTime, Date endTime,String sellPoint, Pageable pageable,Sort sort);

}

实现


@Service
@Slf4j
public class ESProductManagerImpl implements ESProductManager {

    @Autowired
    ProductRepository productRepository;
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Override
    public void addDocuments(List<ESProduct> products) {
        if (CollectionUtils.isEmpty(products)){
            return;
        }
        List<ESProduct> collect = products.stream().filter(Objects::nonNull).collect(Collectors.toList());
        productRepository.saveAll(collect);
    }

    @Override
    public ESProduct getProductById(String id) {
        Optional<ESProduct> byId = productRepository.findById(id);
        return byId.isPresent()? byId.get() : null;
    }

    @Override
    public Page<ESProduct> findByCName(String cname, Integer page,Integer count) {
        SearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(matchPhraseQuery("cname",cname))
                .withIndices("product")
                .withTypes("product")
                .withPageable(PageRequest.of(page,count))
                .withSort(new FieldSortBuilder("updated").order(SortOrder.DESC))
                .build();
        return productRepository.search(searchQuery);
    }

    @Override
    public Page<ESProduct> findByCId(String cid, Pageable pageable) {
        //BoolQueryBuilder queryBuilder = new BoolQueryBuilder();
        //queryBuilder.must(QueryBuilders.matchQuery("cid", cid));
        SearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.termQuery("cid",cid))
                .withIndices("product")
                .withTypes("product")
                .withPageable(pageable)
                .build();
        return productRepository.search(searchQuery);
    }

    @Override
    public Page<ESProduct> getProductByCreateTime(Date startTime, Date endTime,String sellPoint, Pageable pageable, Sort sort) {

        CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria()
                .and(new Criteria("updated").greaterThanEqual(
                        startTime.getTime()).lessThanEqual(endTime.getTime()))
                .and(new Criteria("sellPoint").contains("北京")))
                .setPageable(pageable)
                .addSort(sort);
        return elasticsearchTemplate.queryForPage(criteriaQuery,ESProduct.class);
    }
}

ElasticsearchTemplate 这个模板类,也有很多有用的API。

(3)Test controller

@RestController
@RequestMapping("/es/product")
public class ESProductController {


    @Autowired
    ItemService itemService;
    @Autowired
    ESProductManager esProductManager;

    @RequestMapping("/syncData")
    public Object syncData(){
        itemService.syncData();
        return "1223";
    }


    @RequestMapping("/search")
    @ResponseBody
    public Object getById() throws Exception {
        Map<String,Object> res = Maps.newHashMap();
        //根据Id查询
        ESProduct productById = esProductManager.getProductById("536563");
        res.put("getProductById",productById);

        //根据产品类别名称分页搜索
        Page<ESProduct> findByCName = esProductManager.findByCName("手机", 1, 5);
        res.put("findByCName",findByCName);
        //根据产品类别Id分页搜索
        Page<ESProduct> findByCId = esProductManager.findByCId("560", PageRequest.of(1,5));
        res.put("findByCId",findByCId);

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //根据时间段检索产品,并且对 sellPoint字段 查询
         Page<ESProduct> getProductByCreateTime = esProductManager.getProductByCreateTime(dateFormat.parse("2015-03-08 21:33:18"), new Date(),"北京", PageRequest.of(2,5) ,Sort.by("updated").descending());
        res.put("getProductByCreateTime",getProductByCreateTime);
        return res;
    }


(4)结果

    {
    	"findByCId": {
    		"content": [{
    			"id": "1023438",
    			"title": "苹果(Apple) iPhone 5s (A1518) 16GB 深空灰色 移动4G手机",
    			"sellPoint": "移动用户请认准移动4G版iPhone,中国移动4G【和】iPhone 5s,带您畅享全球领先的飞速4G/3G网络,快人一步!",
    			"price": 409900.0,
    			"num": 99999,
    			"barcode": null,
    			"image": "http://image.e3mall.cn/jd/3ded2f8d3c694f70b29269ecaf2ce4c5.jpg",
    			"cid": "560",
    			"cname": "手机",
    			"status": 1,
    			"created": "2015-03-08T21:27:54.000+0000",
    			"updated": "2015-03-08T21:27:54.000+0000"
    		}, {
    			"id": "1089822",
    			"title": "努比亚 (nubia) 牛魔王X6 32GB 皓月白 移动联通4G电信3G手机",
    			"sellPoint": "努比亚神器,前后双1300W摄像头,能拍星星的手机!",
    			"price": 249900.0,
    			"num": 99999,
    			"barcode": null,
    			"image": "http://image.e3mall.cn/jd/cc1bf510417140aa90ad9876baac22b8.jpg",
    			"cid": "560",
    			"cname": "手机",
    			"status": 1,
    			"created": "2015-03-08T21:27:49.000+0000",
    			"updated": "2015-03-08T21:27:49.000+0000"
    		}, {
    			"id": "1118849",
    			"title": "百加 (100+) V6 32G版 瓷白 移动3G手机 双卡双待",
    			"sellPoint": "5.5英寸FHD高清屏,八核处理器,2G+32G超大内存,1300+500万摄像头!",
    			"price": 88800.0,
    			"num": 99999,
    			"barcode": null,
    			"image": "http://image.e3mall.cn/jd/921b4802940e419592c27e6ca0494557.jpg",
    			"cid": "560",
    			"cname": "手机",
    			"status": 1,
    			"created": "2015-03-08T21:27:49.000+0000",
    			"updated": "2015-03-08T21:27:49.000+0000"
    		}, {
    			"id": "1124089",
    			"title": "华为 Ascend P7 (P7-L00) 黑色 联通4G手机 双卡双待双通",
    			"sellPoint": "华为年度旗舰,5英寸FHD屏,四核1.8GHz,2G+16G内存,1300万像素!畅享联通3G、4G网络!<a  target=\"blank\"  href=\"http://sale.jd.com/act/gABGw4eCDxHL.html\">『三羊开泰,7象万千』活动中奖名单请戳</a>",
    			"price": 238800.0,
    			"num": 99999,
    			"barcode": null,
    			"image": "http://image.e3mall.cn/jd/b0d49c7361cb49f887299a7c30ca351c.jpg",
    			"cid": "560",
    			"cname": "手机",
    			"status": 1,
    			"created": "2015-03-08T21:27:49.000+0000",
    			"updated": "2015-03-08T21:27:49.000+0000"
    		}, {
    			"id": "1150491",
    			"title": "HTC M8St (E8) 鎏金摩登灰 移动4G手机",
    			"sellPoint": "双曲面柔美机身,极速高通骁龙2.5GHz处理器,双前置立体动感音效,智能预知,感应启动,1300万后置+500万前置摄像头,卓越省电模式!",
    			"price": 232800.0,
    			"num": 99999,
    			"barcode": null,
    			"image": "http://image.e3mall.cn/jd/9d9e261cd0cc43d5a94c416e50418eb0.jpg",
    			"cid": "560",
    			"cname": "手机",
    			"status": 1,
    			"created": "2015-03-08T21:27:49.000+0000",
    			"updated": "2015-03-08T21:27:49.000+0000"
    		}],
    		"pageable": {
    			"sort": {
    				"sorted": false,
    				"unsorted": true,
    				"empty": true
    			},
    			"offset": 5,
    			"pageSize": 5,
    			"pageNumber": 1,
    			"paged": true,
    			"unpaged": false
    		},
    		"facets": [],
    		"aggregations": null,
    		"scrollId": null,
    		"maxScore": 0.25921416,
    		"totalElements": 721,
    		"totalPages": 145,
    		"number": 1,
    		"size": 5,
    		"sort": {
    			"sorted": false,
    			"unsorted": true,
    			"empty": true
    		},
    		"numberOfElements": 5,
    		"first": false,
    		"last": false,
    		"empty": false
    	},
    	"findByCName": {
    		"content": [{
    			"id": "1124677",
    			"title": "小米 红米1S 金属灰 联通3G手机 双卡双待",
    			"sellPoint": "4.7英寸四核处理器,8GB ROM+1GB RAM内存,800+160万摄像头!",
    			"price": 79900.0,
    			"num": 99999,
    			"barcode": null,
    			"image": "http://image.e3mall.cn/jd/a7af09ca9523411ba11375f38ffc3802.jpg",
    			"cid": "560",
    			"cname": "手机",
    			"status": 1,
    			"created": "2015-03-08T21:33:47.000+0000",
    			"updated": "2015-03-08T21:33:47.000+0000"
    		}, {
    			"id": "1229269",
    			"title": "小米 4 联通合约版 白色 联通4G手机 不含合约计划",
    			"sellPoint": "",
    			"price": 209900.0,
    			"num": 99999,
    			"barcode": null,
    			"image": "http://image.e3mall.cn/jd/f539e3add44c4b3a8eb455bc6b722fbd.jpg",
    			"cid": "560",
    			"cname": "手机",
    			"status": 1,
    			"created": "2015-03-08T21:33:47.000+0000",
    			"updated": "2015-03-08T21:33:47.000+0000"
    		}, {
    			"id": "1187781",
    			"title": "小米 3 联通16G 星空灰 联通3G手机",
    			"sellPoint": "四核处理器,5英寸1920*1080高清大屏,16GB ROM+2GB RAM内存,1300+200万摄像头!",
    			"price": 139900.0,
    			"num": 99999,
    			"barcode": null,
    			"image": "http://image.e3mall.cn/jd/feb5851fa5b749fcbdea9f2d298419c1.jpg",
    			"cid": "560",
    			"cname": "手机",
    			"status": 1,
    			"created": "2015-03-08T21:33:47.000+0000",
    			"updated": "2015-03-08T21:33:47.000+0000"
    		}, {
    			"id": "1231490",
    			"title": "小米4 白色 联通3G手机",
    			"sellPoint": "卖完下柜!不锈钢金属边框,5英寸屏超窄边,骁龙四核2.5GHz处理器,3G RAM,1300W+800W摄像头!",
    			"price": 199900.0,
    			"num": 99999,
    			"barcode": null,
    			"image": "http://image.e3mall.cn/jd/99b517fcefcc4240995fe2156accb8da.jpg",
    			"cid": "560",
    			"cname": "手机",
    			"status": 1,
    			"created": "2015-03-08T21:33:47.000+0000",
    			"updated": "2015-03-08T21:33:47.000+0000"
    		}, {
    			"id": "973267",
    			"title": "优快(U&K) U97 四防对讲手机",
    			"sellPoint": "返100元!四防手机对讲,企业通讯必备;电信天翼、深度定制、一键通全国!",
    			"price": 198000.0,
    			"num": 99999,
    			"barcode": null,
    			"image": "http://image.e3mall.cn/jd/82cdd90503aa4dabb2bb4e5984d6d8b4.jpg",
    			"cid": "560",
    			"cname": "手机",
    			"status": 1,
    			"created": "2015-03-08T21:33:18.000+0000",
    			"updated": "2015-03-08T21:33:18.000+0000"
    		}],
    		"pageable": {
    			"sort": {
    				"sorted": false,
    				"unsorted": true,
    				"empty": true
    			},
    			"offset": 5,
    			"pageSize": 5,
    			"pageNumber": 1,
    			"paged": true,
    			"unpaged": false
    		},
    		"facets": [],
    		"aggregations": null,
    		"scrollId": null,
    		"maxScore": "NaN",
    		"totalElements": 721,
    		"totalPages": 145,
    		"number": 1,
    		"size": 5,
    		"sort": {
    			"sorted": false,
    			"unsorted": true,
    			"empty": true
    		},
    		"numberOfElements": 5,
    		"first": false,
    		"last": false,
    		"empty": false
    	},
    	"getProductByCreateTime": {
    		"content": [],
    		"pageable": {
    			"sort": {
    				"sorted": false,
    				"unsorted": true,
    				"empty": true
    			},
    			"offset": 10,
    			"pageSize": 5,
    			"pageNumber": 2,
    			"paged": true,
    			"unpaged": false
    		},
    		"facets": [],
    		"aggregations": null,
    		"scrollId": null,
    		"maxScore": "NaN",
    		"totalElements": 0,
    		"totalPages": 0,
    		"number": 2,
    		"size": 5,
    		"sort": {
    			"sorted": false,
    			"unsorted": true,
    			"empty": true
    		},
    		"numberOfElements": 0,
    		"first": false,
    		"last": true,
    		"empty": true
    	},
    	"getProductById": {
    		"id": "536563",
    		"title": "new2 - 阿尔卡特 (OT-927) 炭黑 联通3G手机 双卡双待",
    		"sellPoint": "清仓!仅北京,武汉仓有货!",
    		"price": 2.99E7,
    		"num": 99999,
    		"barcode": "",
    		"image": "http://image.e3mall.cn/jd/4ef8861cf6854de9889f3db9b24dc371.jpg",
    		"cid": "560",
    		"cname": "手机",
    		"status": 1,
    		"created": "2015-03-08T21:33:18.000+0000",
    		"updated": "2015-04-11T20:38:38.000+0000"
    	}
    }
Elasticsearch 简介 ElasticSearch是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。Elasticsearch是用Java开发的,并作为Apache许可条款下的开放源码发布,是当前流行的企业级搜索引擎。设计用于云计算中,能够达到实时搜索,稳定,可靠,快速,安装使用方便。elasticSearch 的使用场景 1、在海量数据前提下,对数据进行检索。比如:京东,淘宝等电商项目课程目标: 1. 了解企业级搜索引擎2. 安装elasticsearch 课程目录: 01 课程介绍02 elasticsearch 简介03 elasticsearch 使用场景04 安装elasticsearch 之前先安装jdk05 安装elasticsearch06 测试elasticsearch是否安装成功 07 安装kibana08 elasticsearch 基本认识 以及添加索引和删除索引09 elasticsearch 添加查询数据10 elasticsearch 修改删除数据11 elasticsearch 有条件的查询12 分词子属性fuzzy查询13 elasticsearch 过滤使用14 elasticsearch 排序与分页15 elasticsearch 如何查询指定的字段16 elasticsearch 高亮显示17 elasticsearch 聚合18 elasticsearch mapping 概念19 elasticsearch 的中文词库20 elasticsearch 中文词库安装测试21 elasticsearch 中文词库的使用案例22 elasticsearch 自定义词库配置23 安装nginx 配置中文词库24 测试elasticsearch 自定义中文词库25 搭建项目父工程26 搭建项目bean-interface-common27 搭建search 的service web 项目28 测试项目是否能与elasticsearch联通29 创建数据库并搭建首页30 数据上传功能的实现类完成31 数据上传控制器完成32 dubbo 介绍以及安装zookeeper33 将数据从mysql 上传到elasticsearch 中34 elasticsearch查询功能分析35 编写业务需求的dsl 语句36 编写输入参数返回结果集的实体类37 实现类编写38 编写实现类中dsl 语句39 返回集结果转换40 结果测试41 测试通过输入查询条件并将数据显示到页面
<think>好的,我现在需要解决用户关于Spring Boot 2.3.4与spring-boot-starter-data-elasticsearch兼容的Elasticsearch版本的问题。首先,我应该回忆一下Spring Boot版本和Elasticsearch之间的兼容性通常是如何确定的。 记得Spring Boot的官方文档中会列出每个版本对应的依赖项版本,这通常在“Dependency Versions”部分。用户提到的是Spring Boot 2.3.4,那么我需要找到该版本对应的spring-boot-starter-data-elasticsearch所依赖的Elasticsearch客户端版本。 接下来,可能需要查看Spring Boot 2.3.x的文档或发布说明,特别是关于Elasticsearch的部分。例如,Spring Boot 2.3.x可能默认使用Elasticsearch 6.x或7.x的客户端。但具体到2.3.4这个补丁版本,是否有变化呢?一般来说,小版本之间的依赖版本可能不会有太大变动,但最好确认具体的兼容性信息。 另外,spring-boot-starter-data-elasticsearch依赖于Elasticsearch的Java客户端,而客户端的版本需要与Elasticsearch服务端版本匹配。例如,Elasticsearch Java High Level REST Client的版本通常需要与Elasticsearch服务端版本一致,或者遵循一定的兼容性矩阵。 可能需要参考Spring Data Elasticsearch的版本,因为spring-boot-starter-data-elasticsearch会间接依赖它。Spring Boot 2.3.4对应的Spring Data版本应该是某个特定的发布版本,例如Spring Data Elasticsearch 3.3.x或4.0.x,而不同版本的Spring Data Elasticsearch支持的Elasticsearch版本不同。 例如,Spring Data Elasticsearch 3.x可能支持Elasticsearch 6.x,而4.x支持7.x。因此,需要确定Spring Boot 2.3.4中使用的Spring Data Elasticsearch版本,然后查找该版本对应的Elasticsearch兼容性。 查阅资料,Spring Boot 2.3.4.RELEASE对应的Spring Data版本应为Neumann-SR5,对应Spring Data Elasticsearch 3.3.x。根据Spring Data Elasticsearch文档,3.3.x版本兼容Elasticsearch 6.8.x到7.6.x。但需要注意,Java客户端版本可能需要与服务端版本一致,可能推荐使用6.8.x或7.x中的某个特定版本。 但有时候官方会有明确的说明,例如在Spring Boot的官方文档中,可能会有明确的兼容性列表。例如,Spring Boot 2.3.x的参考文档可能指出spring-boot-starter-data-elasticsearch默认支持Elasticsearch 7.6.2。因此,用户应该使用与该客户端版本对应的Elasticsearch服务端版本,即7.6.2。 不过,也有可能存在一定的版本弹性,即客户端可以兼容同一主版本的不同小版本。例如,7.x的客户端可能兼容7.x的所有服务端版本,但最好严格匹配。 另外,用户提供的引用信息中有关于MongoDB的配置,这可能无关,但需要注意是否有可能混淆了不同模块的配置。确保引用的正确性。 总结,我需要给出Spring Boot 2.3.4对应的Elasticsearch版本,并建议用户查阅官方文档或相关参考资料以确认。此外,可能需要说明如何找到这些信息,例如通过查看Spring Boot的依赖管理部分,或者Spring Data Elasticsearch的版本兼容性表格。</think>Spring Boot 2.3.4 中,`spring-boot-starter-data-elasticsearch` 默认兼容的 Elasticsearch 服务端版本为 **7.6.2**。该版本对应的客户端为 Elasticsearch High Level REST Client 7.6.2[^1]。 ### 版本兼容性验证方法 1. **查看Spring Boot官方文档** Spring Boot每个版本的文档中会明确列出依赖库的版本。例如,Spring Boot 2.3.4对应的依赖管理文件(`spring-boot-dependencies`)中定义了Elasticsearch客户端的版本: ```xml <elasticsearch.version>7.6.2</elasticsearch.version> ``` 此版本号表示Spring Boot默认集成的Elasticsearch客户端版本。 2. **客户端与服务端版本匹配原则** Elasticsearch要求Java客户端的版本必须与服务端版本**严格一致**。若服务端为7.6.2,则客户端必须使用7.6.2的High Level REST Client[^2]。 3. **特殊情况处理** - 若需使用其他Elasticsearch版本(如7.x系列的其他小版本),需在项目中显式指定`elasticsearch.version`属性: ```properties # application.properties elasticsearch.version=7.9.3 ``` - 注意:跨主版本(如Elasticsearch 8.x)可能因协议变更导致不兼容。 ### 示例配置 在`pom.xml`中,依赖关系如下: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> ``` 默认关联的Elasticsearch客户端版本由Spring Boot父项目控制[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值