es(elasticsearch)整合SpringCloud(SpringBoot)搭建教程詳解
注意:適用于springboot或者springcloud框架
1.首先下載相關(guān)文件
2.然后需要去啟動(dòng)相關(guān)的啟動(dòng)文件


3、導(dǎo)入相關(guān)jar包(如果有相關(guān)的依賴包不需要導(dǎo)入)以及配置配置文件,并且寫一個(gè)dao接口繼承一個(gè)類,在啟動(dòng)類上標(biāo)注地址
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency>
## ElasticSearch - start #開啟 Elasticsearch 倉(cāng)庫(kù)(默認(rèn)值:true) spring.data.elasticsearch.repositories.enabled=true spring.data.elasticsearch.cluster-nodes=localhost:9300 spring.data.elasticsearch.cluster-name=myes
Shop:是下面創(chuàng)建的實(shí)體類名稱(不能寫錯(cuò)),String(傳參時(shí)的類型,我這里id也給的String,因?yàn)閕nteger報(bào)錯(cuò))
import com.jk.user.model.Shop;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
public interface EsDao extends ElasticsearchRepository<Shop,String> {
}
啟動(dòng)類上加上注解,后面跟的是dao的包名
@EnableElasticsearchRepositories(basePackages = "com.jk.web.dao")
4.實(shí)體類
indexName相當(dāng)于數(shù)據(jù)庫(kù)名, type 相當(dāng)于表名 ,必須加上id,type 類型,analyzer 分詞器名稱(ik分詞)
@Document(indexName = "zth",type = "t_shangpin")
public class Shop implements Serializable {
private static final long serialVersionUID = 2006762641515872124L;
private String id;
@Field(type = FieldType.Text, analyzer = "ik_max_word")
//商品名稱
private String shopname;
//優(yōu)惠價(jià)格
private Long reducedprice;
}
5.然后寫controller層(這里直接注入dao接口),這里新增我選的是對(duì)象循環(huán)賦值,其實(shí)可以直接賦集合(參考)
//elasticsearch 生成表
// @RequestMapping("el")
// @ResponseBody
// public void el(){
// List<ElasticsearchBean> list=shoppService.queryelasticsearch();
// for (ElasticsearchBean ss: list) {
// ss.setScrenicName(ss.getScrenicName()+""+ss.getHotelName());
// }
// elasticsearch.saveAll(list);
// }
@Autowired
private EsDao esDao;
// 查詢時(shí)需要
@Autowired
private ElasticsearchTemplate elasticsearchTemplate ;
//更新es服務(wù)器數(shù)據(jù)
@RequestMapping("addEs")
public boolean addShopEs() {
List<TShangpin> list = webUserService.queryShouye();//先去后臺(tái)查出數(shù)據(jù)在賦值
Shop shop = new Shop();
try {
for (int i = 0; i < list.size(); i++) {
shop.setId(list.get(i).getShopid().toString());
shop.setShopname(list.get(i).getShopname());
esDao.save(shop);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
//es搜索商品
@RequestMapping("queryShop")
public List ellist(String name, HttpSession session, Integer page, Integer rows){
if (name==null||"".equals(name)){
name = session.getAttribute("name").toString();
}
page=1;
rows=3;
HashMap<String, Object> resultMap = new HashMap<>();
//創(chuàng)建一個(gè)要搜索的索引庫(kù)
SearchRequestBuilder searchRequestBuilder = elasticsearchTemplate.getClient().prepareSearch("zth").setTypes("t_shangpin");
//創(chuàng)建組合查詢
BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
if (name!=null && !"".equals(name)){
boolQueryBuilder.should(QueryBuilders.matchQuery("shopname",name));
}
//設(shè)置查詢的類型
searchRequestBuilder.setSearchType(SearchType.DFS_QUERY_THEN_FETCH);
searchRequestBuilder.setQuery(boolQueryBuilder);
//分頁(yè)
searchRequestBuilder.setFrom((page-1)*rows);
searchRequestBuilder.setSize(rows);
//設(shè)置高亮字段
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.field("shopname")
.preTags("<font color='red'>")
.postTags("</font>");
searchRequestBuilder.highlighter(highlightBuilder);
//直接搜索返回響應(yīng)數(shù)據(jù) (json)
SearchResponse searchResponse = searchRequestBuilder.get();
SearchHits hits = searchResponse.getHits();
//獲取總條數(shù)
long totalHits = hits.getTotalHits();
resultMap.put("total",totalHits);
ArrayList<Map<String,Object>> list = new ArrayList<>();
//獲取Hits中json對(duì)象數(shù)據(jù)
SearchHit[] hits1 = hits.getHits();
for (int i=0;i<hits1.length;i++){
//獲取Map對(duì)象
Map<String, Object> sourceAsMap = hits1[i].getSourceAsMap();
//獲取高亮字段
Map<String, HighlightField> highlightFields = hits1[i].getHighlightFields();
//??!如果有高亮字段就取出賦給上面sourceAsMap中原有的名字給他替換掉?。?
if (name!=null && !"".equals(name)){
sourceAsMap.put("shopname",highlightFields.get("shopname").getFragments()[0].toString());
}
list.add(sourceAsMap);
}
return list;
}
6.最后 如果無法搜索,可能是需要加一個(gè)ik的json文件,因?yàn)樵趯?shí)體類中規(guī)定了是ik分詞器,如果不規(guī)定當(dāng)它存進(jìn)去后其實(shí)是還沒有分詞。
film-mapping.json
{
"film":
{
"_all":
{
"enabled": true
},
"properties":
{ "id":
{
"type": "integer"
},"name":
{
"type": "text", "analyzer": "ikSearchAnalyzer", "search_analyzer": "ikSearchAnalyzer", "fields":
{ "pinyin": {
"type": "text", "analyzer": "pinyinSimpleIndexAnalyzer", "search_analyzer": "pinyinSimpleIndexAnalyzer"
} } },
"nameOri": { "type": "text"
},"publishDate":
{ "type": "text" },"type":
{ "type": "text"
},"language":
{ "type": "text"
},"fileDuration":
{ "type": "text"
},"director":
{ "type": "text",
"index": "true", "analyzer": "ikSearchAnalyzer"
},"created":
{
"type": "date", "format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis"
} } } }
film-setting.json

{ "index": { "analysis":
{ "filter":
{ "edge_ngram_filter":
{ "type": "edge_ngram", "min_gram": 1, "max_gram": 50
},"pinyin_simple_filter":
{
"type": "pinyin", "first_letter": "prefix", "padding_char": " ", "limit_first_letter_length": 50, "lowercase": true
}
},"char_filter":
{
"tsconvert": { "type": "stconvert", "convert_type": "t2s"
}
},"analyzer":
{ "ikSearchAnalyzer":
{ "type": "custom", "tokenizer": "ik_max_word", "char_filter": [ "tsconvert" ]
},"pinyinSimpleIndexAnalyzer":
{ "tokenizer": "keyword", "filter": [ "pinyin_simple_filter", "edge_ngram_filter", "lowercase" ]
} } } } }

總結(jié)
到此這篇關(guān)于es(elasticsearch)整合SpringCloud(SpringBoot)搭建教程詳解的文章就介紹到這了,更多相關(guān)elasticsearch 整合SpringCloud內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 解決SpringBoot整合ElasticSearch遇到的連接問題
- SpringBoot整合Elasticsearch游標(biāo)查詢的示例代碼(scroll)
- SpringBoot整合Spring Data Elasticsearch的過程詳解
- SpringBoot整合Elasticsearch7.2.0的實(shí)現(xiàn)方法
- SpringBoot整合Elasticsearch并實(shí)現(xiàn)CRUD操作
- 解決springboot無法注入JpaRepository的問題
- SpringBoot3整合 Elasticsearch 8.x 使用Repository構(gòu)建增刪改查示例應(yīng)用
相關(guān)文章
Spring Boot延遲執(zhí)行實(shí)現(xiàn)方法
本文介紹了在Spring Boot項(xiàng)目中延遲執(zhí)行方法的實(shí)現(xiàn),以及延遲執(zhí)行下聲明式事務(wù)和編程式事務(wù)的使用情況,感興趣的朋友一起看看吧2020-12-12
線程池ThreadPoolExecutor并行處理實(shí)現(xiàn)代碼
這篇文章主要介紹了線程池ThreadPoolExecutor并行處理實(shí)現(xiàn)代碼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-11-11
RabbitMQ 在 Spring Boot 項(xiàng)目中的深度應(yīng)用與實(shí)戰(zhàn)解析
RabbitMQ 作為一款廣受歡迎的開源消息隊(duì)列系統(tǒng),遵循 AMQP 協(xié)議,能夠在分布式系統(tǒng)里實(shí)現(xiàn)應(yīng)用程序之間的異步通信、解耦以及流量削峰等關(guān)鍵功能,這篇文章主要介紹了RabbitMQ 在 Spring Boot 項(xiàng)目中的深度應(yīng)用與實(shí)戰(zhàn)解析,需要的朋友可以參考下2025-01-01
SpringBoot啟動(dòng)時(shí)自動(dòng)執(zhí)行指定方法的幾種實(shí)現(xiàn)方式
在Spring Boot應(yīng)用程序中,要實(shí)現(xiàn)在應(yīng)用啟動(dòng)時(shí)自動(dòng)執(zhí)行某些代碼,本文主要介紹了SpringBoot啟動(dòng)時(shí)自動(dòng)執(zhí)行指定方法的幾種方式,文中有相關(guān)的代碼示例供大家參考,需要的朋友可以參考下2024-03-03
springboot實(shí)現(xiàn)string轉(zhuǎn)json json里面帶數(shù)組
這篇文章主要介紹了springboot實(shí)現(xiàn)string轉(zhuǎn)json json里面帶數(shù)組,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-06-06
淺談SpringBoot在使用測(cè)試的時(shí)候是否需要@RunWith
本文主要介紹了淺談SpringBoot在使用測(cè)試的時(shí)候是否需要@RunWith,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-01-01
SpringCloud之分布式配置中心Spring Cloud Config高可用配置實(shí)例代碼
這篇文章主要介紹了SpringCloud之分布式配置中心Spring Cloud Config高可用配置實(shí)例代碼,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-04-04
Java Hutool 包工具類推薦 ExcelUtil詳解
這篇文章主要介紹了Java Hutool 包工具類推薦 ExcelUtil詳解,需要引入hutool包,版本號(hào)可根據(jù)實(shí)際情況更換,除hutool包之外,還需要引入操作Excel必要包,本文給大家介紹的非常詳細(xì),需要的朋友可以參考下2022-09-09

