您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關elasticsearch整合SpringCloud的步驟,文章內容質量較高,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
ElasticSearch是一個基于Lucene的搜索服務器。它提供了一個分布式多用戶能力的全文搜索引擎,基于RESTful web接口。Elasticsearch是用Java開發的,并作為Apache許可條款下的開放源碼發布,是當前流行的企業級搜索引擎。設計用于云計算中,能夠達到實時搜索,穩定,可靠,快速,安裝使用方便。
注意:適用于springboot或者springcloud框架
1.首先下載相關文件
2.然后需要去啟動相關的啟動文件
3、導入相關jar包(如果有相關的依賴包不需要導入)以及配置配置文件,并且寫一個dao接口繼承一個類,在啟動類上標注地址
<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 倉庫(默認值:true) spring.data.elasticsearch.repositories.enabled=true spring.data.elasticsearch.cluster-nodes=localhost:9300 spring.data.elasticsearch.cluster-name=myes
Shop:是下面創建的實體類名稱(不能寫錯),String(傳參時的類型,我這里id也給的String,因為integer報錯)
import com.jk.user.model.Shop; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; public interface EsDao extends ElasticsearchRepository<Shop,String> { }
啟動類上加上注解,后面跟的是dao的包名
@EnableElasticsearchRepositories(basePackages = "com.jk.web.dao")
4.實體類
indexName相當于數據庫名, type 相當于表名 ,必須加上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; //優惠價格 private Long reducedprice; }
5.然后寫controller層(這里直接注入dao接口),這里新增我選的是對象循環賦值,其實可以直接賦集合(參考)
//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; // 查詢時需要 @Autowired private ElasticsearchTemplate elasticsearchTemplate ; //更新es服務器數據 @RequestMapping("addEs") public boolean addShopEs() { List<TShangpin> list = webUserService.queryShouye();//先去后臺查出數據在賦值 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<>(); //創建一個要搜索的索引庫 SearchRequestBuilder searchRequestBuilder = elasticsearchTemplate.getClient().prepareSearch("zth").setTypes("t_shangpin"); //創建組合查詢 BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder(); if (name!=null && !"".equals(name)){ boolQueryBuilder.should(QueryBuilders.matchQuery("shopname",name)); } //設置查詢的類型 searchRequestBuilder.setSearchType(SearchType.DFS_QUERY_THEN_FETCH); searchRequestBuilder.setQuery(boolQueryBuilder); //分頁 searchRequestBuilder.setFrom((page-1)*rows); searchRequestBuilder.setSize(rows); //設置高亮字段 HighlightBuilder highlightBuilder = new HighlightBuilder(); highlightBuilder.field("shopname") .preTags("<font color='red'>") .postTags("</font>"); searchRequestBuilder.highlighter(highlightBuilder); //直接搜索返回響應數據 (json) SearchResponse searchResponse = searchRequestBuilder.get(); SearchHits hits = searchResponse.getHits(); //獲取總條數 long totalHits = hits.getTotalHits(); resultMap.put("total",totalHits); ArrayList<Map<String,Object>> list = new ArrayList<>(); //獲取Hits中json對象數據 SearchHit[] hits1 = hits.getHits(); for (int i=0;i<hits1.length;i++){ //獲取Map對象 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.最后 如果無法搜索,可能是需要加一個ik的json文件,因為在實體類中規定了是ik分詞器,如果不規定當它存進去后其實是還沒有分詞。
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" ] } } } } }
以上就是elasticsearch整合SpringCloud的步驟,看完之后是否有所收獲呢?如果想了解更多相關內容,歡迎關注億速云行業資訊,感謝各位的閱讀。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。