開發(fā)環(huán)境:
- 所用SpringBoot版本:2.0.8.RELEASE
- 構建工具: Gradle
首先添加依賴:
implementation('org.springframework.boot:spring-boot-starter-data-elasticsearch')
然后調(diào)出依賴列表,查看對應的elasticsearch版本

image.png
能夠看到我需要安裝的是5.6.14版本的ES
去官網(wǎng)下載對應版本
附上官網(wǎng)各版本的下載頁面:
https://www.elastic.co/downloads/past-releases
安裝中文分詞器ik
官方GitHub的安裝教程已經(jīng)很詳細了,附上鏈接:
https://github.com/medcl/elasticsearch-analysis-ik
注意:
- 下載ik插件的zip后用elasticsearch-plugin install安裝會報錯,在線安裝沒問題
- 用mac的同學需要注意的是蘋果的.DS_Store會讓elasticsearch-plugin報錯,盡量在命令行里操作
- 安裝完后可以用elasticsearch-plugin list命令查看是否安裝成功
GET localhost:9200 查看ES基本信息:
{
"name": "G0DVm1w",
"cluster_name": "elasticsearch",
"cluster_uuid": "ai_dxFHoRjGBnsSxvfHWBw",
"version": {
"number": "5.6.14",
"build_hash": "f310fe9",
"build_date": "2018-12-05T21:20:16.416Z",
"build_snapshot": false,
"lucene_version": "6.6.1"
},
"tagline": "You Know, for Search"
}
cluster_name為elasticsearch
之后在SpringBoot中配置
spring:
data:
elasticsearch:
cluster-nodes: 127.0.0.1:9300
repositories:
enabled: true
cluster-name: elasticsearch
此處的cluster-name就是剛剛查到的
之后編寫實體類
@Data
// 指定根據(jù)文件構建映射
@Mapping(mappingPath = "mapping/SpuDocMapping.json")
// indexName一般為項目名,type為實體類名,注解的createIndex屬性默認為ture,
// SpringBoot啟動時會自動創(chuàng)建映射,但要注意如果已經(jīng)存在相同的index,必須先刪除
@Document(indexName = "ynec", type = "spu")
public class SpuDoc implements Serializable {
private static final long serialVersionUID = -472259879967511922L;
// 注意一定要加id注解
@Id
private Long spu_id;
private String name;
private List<String> cat_list;
private List<String> prop_list;
}
這篇文章對注解的講解很多,推薦:https://blog.csdn.net/kingice1014/article/details/73166686?utm_source=blogxgwz6
附上我的映射文件:
{
"mappings": {
"spu": {
"properties": {
"spu_id": {
"type": "long"
},
"name": {
"type": "text",
"analyzer": "ik_smart"
},
"cat_list": {
"type": "text",
"analyzer": "ik_smart"
},
"prop_list": {
"type": "text",
"analyzer": "ik_smart"
}
}
}
}
}
因為ES總是存在前后api不兼容,推薦直接去官網(wǎng)學習Mapping寫法:
https://www.elastic.co/guide/en/elasticsearch/reference/index.html
這篇中文教程也不錯:
https://blog.csdn.net/zx711166/article/details/81667862
編寫數(shù)據(jù)訪問層
public interface SpuDocRepo extends ElasticsearchRepository<SpuDoc, Long> {
}
這是JPA提供的通用的接口,還有一種是用ElasticSearchTemplate,這里有教程:
https://blog.csdn.net/tianyaleixiaowu/article/details/76149547/
編寫Service和實現(xiàn)類
service接口層省略,下面是實現(xiàn)類:
@Service
public class SearchServiceImpl implements SearchService {
// 剛剛創(chuàng)建的數(shù)據(jù)訪問層
@Autowired
SpuDocRepo spuDocRepo;
@Override
public List<Long> searchSpu(String keyword, Integer page, Integer size) {
// queryStringQuery是匹配_all的全文搜索
QueryBuilder queryBuilder = QueryBuilders.queryStringQuery(keyword);
// 構建分頁對象
Pageable pageable = PageRequest.of(page, size);
Page<SpuDoc> spuDocPage = spuDocRepo.search(queryBuilder, pageable);
// 此處我返回的是商品的id列表,可以根據(jù)業(yè)務自定義
return spuDocPage.getContent().stream().map(SpuDoc::getSpu_id).collect(Collectors.toList());
}
}