javascript
SpringData ElasticSearch入门案例
導(dǎo)入需要的依賴坐標(biāo)
<dependencies><dependency><groupId>org.elasticsearch</groupId><artifactId>elasticsearch</artifactId><version>5.6.8</version></dependency><dependency><groupId>org.elasticsearch.client</groupId><artifactId>transport</artifactId><version>5.6.8</version></dependency><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-to-slf4j</artifactId><version>2.9.1</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId><version>1.7.24</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-simple</artifactId><version>1.7.21</version></dependency><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.12</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-core</artifactId><version>2.8.1</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.8.1</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-annotations</artifactId><version>2.8.1</version></dependency><dependency><groupId>org.springframework.data</groupId><artifactId>spring-data-elasticsearch</artifactId><version>3.0.5.RELEASE</version><exclusions><exclusion><groupId>org.elasticsearch.plugin</groupId><artifactId>transport-netty4-client</artifactId></exclusion></exclusions></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.0.4.RELEASE</version></dependency> </dependencies>創(chuàng)建applicationContext.xml配置文件,引入elasticsearch命名空間
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xmlns:elasticsearch="http://www.springframework.org/schema/data/elasticsearch"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/data/elasticsearchhttp://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch-1.0.xsd"> <!-- 掃描Dao包,自動創(chuàng)建實(shí)例 --> <elasticsearch:repositories base-package="com.itheima.repository"/><!-- 掃描Service包,創(chuàng)建Service的實(shí)體 --> <context:component-scan base-package="com.itheima.service"/><!-- 配置elasticSearch的連接 --> <!-- 配置elasticSearch的連接 --> <elasticsearch:transport-client id="client" cluster-nodes="127.0.0.1:9300" cluster-name="elasticsearch"/><!-- ElasticSearch模版對象 --> <bean id="elasticsearchTemplate" class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate"><constructor-arg name="client" ref="client"></constructor-arg> </bean> </beans>編寫實(shí)體Article
基于spring data elasticsearch注解配置索引、映射和實(shí)體的關(guān)系
配置映射
@Document文檔對象(索引信息、文檔類型)
@Id文檔主鍵,是唯一標(biāo)識
@Field每個文檔的字段配置(類型、是否分詞、是否存儲、分詞器)
其中,注解解釋如下:
@Document(indexName=“blog6”,type=“article”):
indexName:索引的名稱(必填項(xiàng))
type:索引的類型
@Id:主鍵的唯一標(biāo)識
@Field(index=true,analyzer=“ik_smart”,store=true,searchAnalyzer=“ik_smart”,type = FieldType.text)
index:是否設(shè)置分詞
analyzer:存儲時使用的分詞器
searchAnalyze:搜索時使用的分詞器
store:是否存儲
type: 數(shù)據(jù)類型
=======================================
編寫Dao
package com.itheima.repository; import com.itheima.domain.Article; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import org.springframework.stereotype.Repository;@Repository public interface ArticleRepository extends ElasticsearchRepository<Article, Integer> {}編寫Service接口 CRUD操作
package com.itheima.service;import com.itheima.domain.Article;import java.util.List;public interface ArticleService { // 添加索引void save(Article article); //刪除索引 void delete(Article article); //修改索引 void update(Article article); //查詢所有 Iterable<Article> findAll(); //分頁查詢 Iterable<Article> findByPage(int page, int size); //添加多個 void saveAll(List<Article> articles);}編寫service實(shí)現(xiàn)類
package com.itheima.service.impl; import com.itheima.domain.Article; import com.itheima.repository.ArticleRepository; import com.itheima.service.ArticleService; import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service;import java.util.List;@Service public class ArticleServiceImpl implements ArticleService {@Autowired private ArticleRepository articleRepository; //增 public void save(Article article) {articleRepository.save(article); } //刪 public void delete(Article article) {articleRepository.delete(article); } //改 public void update(Article article) {articleRepository.save(article); } //添加所有 public void saveAll(List<Article> articles) {articleRepository.saveAll(articles); } //查詢所有 public Iterable<Article> findAll() {return articleRepository.findAll(); } //分頁查詢 public Iterable<Article> findByPage(int page, int size) {PageRequest pageRequest = PageRequest.of(page, size);return articleRepository.findAll(pageRequest);} }創(chuàng)建測試類SpringDataESTest
package com.itheima; import com.itheima.domain.Article; import com.itheima.service.ArticleService; import org.elasticsearch.index.query.QueryBuilders; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; import org.springframework.data.elasticsearch.core.query.NativeSearchQuery; import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import java.util.ArrayList; import java.util.List;@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:applicationContext.xml")public class SpringDataESTest {@Autowiredprivate ElasticsearchTemplate elasticsearchTemplate;@Autowiredprivate ArticleService articleService;/*** 創(chuàng)建索引* 配置映射*/@Testpublic void createIndex(){elasticsearchTemplate.createIndex(Article.class);elasticsearchTemplate.putMapping(Article.class);}/*** 刪除索引* 配置映射*/ @Test public void deleteIndex(){elasticsearchTemplate.deleteIndex(Article.class);} /*** 創(chuàng)建文檔*/ @Test public void createDocument(){Article article = new Article();article.setId(1);article.setTitle("nihao");article.setContent("wohao");articleService.save(article);}/*** 刪除文檔*/ public void deleteDoc(){Article article = new Article();article.setId(1);articleService.delete(article); } /*** 更新文檔*/ @Test public void UpdateDocument(){Article article = new Article();article.setId(1);article.setTitle("hi");article.setContent("hello");articleService.update(article); }/*** 添加所有*/ @Test public void saveAll(){List<Article> articles = new ArrayList<Article>();for (int i = 0; i < 100; i++) {Article article = new Article();article.setId(i);article.setTitle(i+"標(biāo)題");article.setContent(i+"內(nèi)容");articles.add(article);}articleService.saveAll(articles);} /*** 查詢所有*/ @Test public void findAll(){Iterable<Article> articles = articleService.findAll();for (Article article : articles) {System.out.println(article);}} /*** 分頁查詢*/ @Test public void findByPage(){int page = 1;int size = 5;Iterable<Article> articles = articleService.findByPage(page,size);for (Article article : articles) {System.out.println(article);} }/*** 原生查詢*/ @Test public void termNativequery(){NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();nativeSearchQueryBuilder.withQuery(QueryBuilders.termQuery("title","搜索"));nativeSearchQueryBuilder.withPageable(PageRequest.of(1,5));NativeSearchQuery build = nativeSearchQueryBuilder.build();List<Article> articles = elasticsearchTemplate.queryForList(build, Article.class);for (Article article : articles) {System.out.println(article);}} /*** 原生查詢*/ @Test public void queryStringQuery(){NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();nativeSearchQueryBuilder.withQuery(QueryBuilders.queryStringQuery("搜索"));NativeSearchQuery build = nativeSearchQueryBuilder.build();List<Article> articles = elasticsearchTemplate.queryForList(build, Article.class);for (Article article : articles) {System.out.println(article);}} }常用查詢命名規(guī)則
查詢方法測試
dao層實(shí)現(xiàn)
package com.itheima.dao;
service層實(shí)現(xiàn)
public interface ArticleService {//根據(jù)標(biāo)題查詢List<Article> findByTitle(String condition);//根據(jù)標(biāo)題查詢(含分頁)Page<Article> findByTitle(String condition, Pageable pageable); }service實(shí)現(xiàn)類
package com.itheima.service.impl; import com.itheima.dao.ArticleRepository; import com.itheima.domain.Article; import com.itheima.service.ArticleService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service;import java.util.List;@Service public class ArticleServiceImpl implements ArticleService {@Autowiredprivate ArticleRepository articleRepository;public List<Article> findByTitle(String condition) {return articleRepository.findByTitle(condition);}public Page<Article> findByTitle(String condition, Pageable pageable) {return articleRepository.findByTitle(condition,pageable);}}測試代碼
package com.itheima.test; import com.itheima.domain.Article; import com.itheima.service.ArticleService; import org.elasticsearch.client.transport.TransportClient; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import java.util.List;@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations="classpath:applicationContext.xml") public class SpringDataESTest {@Autowired private ArticleService articleService;@Autowired private TransportClient client;@Autowired private ElasticsearchTemplate elasticsearchTemplate;/**條件查詢*/ @Test public void findByTitle(){String condition = "版本";List<Article> articleList = articleService.findByTitle(condition);for(Article article:articleList){System.out.println(article);} }/**條件分頁查詢*/ @Test public void findByTitlePage(){String condition = "版本";Pageable pageable = PageRequest.of(2,10);Page<Article> page = articleService.findByTitle(condition,pageable);for(Article article:page.getContent()){System.out.println(article);} }}帶高亮顯示查詢
@Testpublic void findByNativeQueryWithHighlighting() {//創(chuàng)建一個SearchQuery對象SearchQuery searchQuery = new NativeSearchQueryBuilder()//設(shè)置查詢條件,此處可以使用QueryBuilders創(chuàng)建多種查詢.withQuery(QueryBuilders.queryStringQuery("備份節(jié)點(diǎn)上沒有數(shù)據(jù)").defaultField("title"))//還可以設(shè)置分頁信息.withPageable(PageRequest.of(1, 5))//設(shè)置高亮條件.withHighlightFields(new HighlightBuilder.Field("title").preTags("<span>").postTags("</span>"))//創(chuàng)建SearchQuery對象.build();//使用模板對象執(zhí)行查詢elasticsearchTemplate.queryForPage(searchQuery, Article.class, new SearchResultMapper() {@Overridepublic <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {List<Article> articles = new ArrayList<>();//取查詢結(jié)果SearchHits hits = searchResponse.getHits();Iterator<SearchHit> iterator = hits.iterator();//遍歷結(jié)果集,包括取高亮結(jié)果while (iterator.hasNext()) {SearchHit searchHit = iterator.next();Article article = new Article();//取idarticle.setId(Integer.parseInt(searchHit.getSource().get("id").toString()));//取title,高亮結(jié)果String title = "";HighlightField highlightField = searchHit.getHighlightFields().get("title");//如果有高亮結(jié)果就取高亮if (highlightField != null) {title = highlightField.getFragments()[0].toString();//如果沒有高亮就取原文檔中的field} else {title = searchHit.getSource().get("title").toString();}article.setTitle(title);//取contentarticle.setContent(searchHit.getSource().get("content").toString());//將結(jié)果添加到列表articles.add(article);}//創(chuàng)建返回結(jié)果對象AggregatedPage result = new AggregatedPageImpl(articles, pageable, hits.getTotalHits());return result;}}).forEach(a-> System.out.println(a));}總結(jié)
以上是生活随笔為你收集整理的SpringData ElasticSearch入门案例的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring Data ElasticS
- 下一篇: SpringBoot整合RabbitMQ