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"
}
}