最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot 整合Jest實例代碼講解

 更新時間:2018年08月20日 16:22:14   作者:ZhaoYingChao88  
本文通過實例代碼給大家介紹了SpringBoot 整合Jest的相關(guān)知識,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下

【1】添加Elasticsearch-starter

pom文件添加starter如下:

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

SpringBoot默認(rèn)支持兩種技術(shù)和Elasticsearch進(jìn)行交互:Spring Data Elasticsearch和Jest。

Jest默認(rèn)不生效,需要導(dǎo)入io.searchbox.client.JestClient。

這里寫圖片描述

maven依賴如下:

<!--導(dǎo)入jest依賴-->
<dependency>
 <groupId>io.searchbox</groupId>
 <artifactId>jest</artifactId>
 <version>5.3.3</version>
</dependency>

Spring Data Elasticsearch主要作用如下:

① ElasticsearchAutoConfiguration中注冊了client,屬性有clusterNodes和clusterName。

這里寫圖片描述

② ElasticsearchDataAutoConfiguration注冊了ElasticsearchTemplate來操作ES 

@Configuration
@ConditionalOnClass({ Client.class, ElasticsearchTemplate.class })
@AutoConfigureAfter(ElasticsearchAutoConfiguration.class)
public class ElasticsearchDataAutoConfiguration {
 @Bean
 @ConditionalOnMissingBean
 @ConditionalOnBean(Client.class)
 public ElasticsearchTemplate elasticsearchTemplate(Client client,
  ElasticsearchConverter converter) {
 try {
  return new ElasticsearchTemplate(client, converter);
 }
 catch (Exception ex) {
  throw new IllegalStateException(ex);
 }
 }
 @Bean
 @ConditionalOnMissingBean
 public ElasticsearchConverter elasticsearchConverter(
  SimpleElasticsearchMappingContext mappingContext) {
 return new MappingElasticsearchConverter(mappingContext);
 }
 @Bean
 @ConditionalOnMissingBean
 public SimpleElasticsearchMappingContext mappingContext() {
 return new SimpleElasticsearchMappingContext();
 }
}

③ ElasticsearchRepositoriesAutoConfiguration 啟用了ElasticsearchRepository

@Configuration
@ConditionalOnClass({ Client.class, ElasticsearchRepository.class })
@ConditionalOnProperty(prefix = "spring.data.elasticsearch.repositories", name = "enabled", havingValue = "true", matchIfMissing = true)
@ConditionalOnMissingBean(ElasticsearchRepositoryFactoryBean.class)
@Import(ElasticsearchRepositoriesRegistrar.class)
public class ElasticsearchRepositoriesAutoConfiguration {
}

ElasticsearchRepository接口源碼如下(類似于JPA中的接口):

@NoRepositoryBean
public interface ElasticsearchRepository<T, ID extends Serializable> extends ElasticsearchCrudRepository<T, ID> {
 <S extends T> S index(S var1);
 Iterable<T> search(QueryBuilder var1);
 Page<T> search(QueryBuilder var1, Pageable var2);
 Page<T> search(SearchQuery var1);
 Page<T> searchSimilar(T var1, String[] var2, Pageable var3);
 void refresh();
 Class<T> getEntityClass();
}

【2】JestClient操作測試

application.properties配置如下:

# jest url配置
spring.elasticsearch.jest.uris=http://192.168.2.110:9200

測試類如下:

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootJestTest {
 @Autowired
 JestClient jestClient;
 @Test
 public void index(){
  Article article = new Article();
  article.setId(1);
  article.setAuthor("Tom");
  article.setContent("hello world !");
  article.setTitle("今日消息");
  //構(gòu)建一個索引功能,類型為news
  Index index = new Index.Builder(article).index("jest").type("news").build();
  try {
   jestClient.execute(index);
   System.out.println("數(shù)據(jù)索引成功!");
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
 @Test
 public void search(){
  //查詢表達(dá)式
  String json = "{\n" +
    " \"query\" : {\n" +
    "  \"match\" : {\n" +
    "   \"content\" : \"hello\"\n" +
    "  }\n" +
    " }\n" +
    "}";
  //構(gòu)建搜索功能
  Search search = new Search.Builder(json).addIndex("jest").addType("news").build();
  try {
   SearchResult result = jestClient.execute(search);
   System.out.println(result.getJsonString());
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

測試存儲數(shù)據(jù)結(jié)果如下:

這里寫圖片描述

測試查詢數(shù)據(jù)結(jié)果如下:

這里寫圖片描述

【3】 Elasticsearch版本調(diào)整

application.properties進(jìn)行配置:

# Spring data elasticsearch配置
spring.data.elasticsearch.cluster-name=elasticsearch
spring.data.elasticsearch.cluster-nodes=192.168.2.110:9300

這里節(jié)點名取自如下圖:

 
這里寫圖片描述

啟動主程序,可能報錯如下(ES版本不合適):

這里寫圖片描述

查看Spring Data官網(wǎng),其中spring data elasticsearch與elasticsearch適配表如下:

這里寫圖片描述

官網(wǎng)地址:https://github.com/spring-projects/spring-data-elasticsearch

我們在上篇博文中安裝的ES版本為5.6.10,項目中SpringBoot版本為1.5.12,spring-boot-starter-data-elasticsearch為2.1.11,elasticsearch版本為2.4.6。

兩種解決辦法:① 升級SpringBoot版本;② 安裝2.4.6版本的elasticsearch。

這里修改暴露的端口,重新使用docker安裝2.4.6版本:

# 拉取2.4.6 鏡像
docker pull registry.docker-cn.com/library/elasticsearch:2.4.6
# 啟動容器
docker run -e ES_JAVA_OPTS="-Xms256m -Xmx256m" -d -p 9201:9200 -p 9301:9300 --name ES02 bc337c8e4f

這里寫圖片描述

application.properties配置文件同步修改:

# jest url配置
spring.elasticsearch.jest.uris=http://192.168.2.110:9201
# Spring data elasticsearch配置
spring.data.elasticsearch.cluster-name=elasticsearch
spring.data.elasticsearch.cluster-nodes=192.168.2.110:9301

此時再次啟動程序:

這里寫圖片描述

【4】ElasticsearchRepository使用

類似于JPA,編寫自定義Repository接口,繼承自ElasticsearchRepository:

public interface BookRepository extends ElasticsearchRepository<Book,Integer> {
 public List<Book> findByBookNameLike(String bookName);
}

這里第一個參數(shù)為對象類型,第二個參數(shù)為對象的主鍵類型。

BookRepository 所擁有的方法如下圖:

這里寫圖片描述

Book源碼如下:

// 這里注意注解
@Document(indexName = "elastic",type = "book")
public class Book {
 private Integer id;
 private String bookName;
 private String author;
 public Integer getId() {
  return id;
 }
 public void setId(Integer id) {
  this.id = id;
 }
 public String getBookName() {
  return bookName;
 }
 public void setBookName(String bookName) {
  this.bookName = bookName;
 }
 public String getAuthor() {
  return author;
 }
 public void setAuthor(String author) {
  this.author = author;
 }
 @Override
 public String toString() {
  return "Book{" +
    "id=" + id +
    ", bookName='" + bookName + '\'' +
    ", author='" + author + '\'' +
    '}';
 }
}

測試類如下:

@Autowired
 BookRepository bookRepository;
 @Test
 public void testRepository(){
  Book book = new Book();
  book.setAuthor("吳承恩");
  book.setBookName("西游記");
  book.setId(1);
  bookRepository.index(book);
  System.out.println("BookRepository 存入數(shù)據(jù)成功!");
 }

測試結(jié)果如下圖:

這里寫圖片描述

測試獲取示例如下:

 @Test
 public void testRepository2(){
  for (Book book : bookRepository.findByBookNameLike("游")) {
   System.out.println("獲取的book : "+book);
  } ;
  Book book = bookRepository.findOne(1);
  System.out.println("根據(jù)id查詢 : "+book);
 }

測試結(jié)果如下圖:

這里寫圖片描述

Elasticsearch支持方法關(guān)鍵字如下圖所示

這里寫圖片描述
這里寫圖片描述
這里寫圖片描述

即,在BookRepository中使用上述關(guān)鍵字構(gòu)造方法,即可使用,Elastic自行實現(xiàn)其功能!

支持@Query注解

如下所示,直接在方法上使用注解:

public interface BookRepository extends ElasticsearchRepository<Book, String> {
 @Query("{"bool" : {"must" : {"field" : {"name" : "?0"}}}}")
 Page<Book> findByName(String name,Pageable pageable);

}

【5】ElasticsearchTemplate使用

存入數(shù)據(jù)源碼示例如下:

@Autowired
 ElasticsearchTemplate elasticsearchTemplate;
 @Test
 public void testTemplate01(){
  Book book = new Book();
  book.setAuthor("曹雪芹");
  book.setBookName("紅樓夢");
  book.setId(2);
  IndexQuery indexQuery = new IndexQueryBuilder().withId(String.valueOf(book.getId())).withObject(book).build();
  elasticsearchTemplate.index(indexQuery);
 }

測試結(jié)果如下:

這里寫圖片描述

查詢數(shù)據(jù)示例如下:

@Test
 public void testTemplate02(){
  QueryStringQueryBuilder stringQueryBuilder = new QueryStringQueryBuilder("樓");
  stringQueryBuilder.field("bookName");
  SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(stringQueryBuilder).build();
  Page<Book> books = elasticsearchTemplate.queryForPage(searchQuery,Book.class);
  Iterator<Book> iterator = books.iterator();
  while(iterator.hasNext()){
   Book book = iterator.next();
   System.out.println("該次獲取的book:"+book);
  }
 }

測試結(jié)果如下:

這里寫圖片描述

 開源項目: https://github.com/spring-projects/spring-data-elasticsearch

 https://github.com/searchbox-io/Jest/tree/master/jest 

1.說明

本文主要講解如何使用Spring Boot快速搭建Web框架,結(jié)合Spring Data 和 Jest 快速實現(xiàn)對阿里云ElasticSearch的全文檢索功能。

主要使用組件:

Spring Boot Starter:可以幫助我們快速的搭建spring mvc 環(huán)境
Jest:一種rest訪問es的客戶端
elasticsearch:全文檢索
spring data elasticsearch:結(jié)合spring data
thymeleaf:web前端模版框架
jquery:js框架
bootstrap:前端樣式框架

2.項目Maven配置

以下為項目Maven配置,尤其需要注意各個組件的版本,以及注釋部分。

各個組件的某些版本組合下回出現(xiàn)各種異常,以下maven為測試可通過的一個版本。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>org.lewis</groupId>
 <artifactId>esweb</artifactId>
 <version>0.1</version>
 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <!--必須用2.0+,否則會有一個類
  Caused by: java.lang.NoSuchMethodError: org.elasticsearch.common.settings.Settings.settingsBuilder()Lorg/elasticsearch/common/settings/Settings$Builder;
  -->
  <version>2.0.0.M7</version>
 </parent>
 <properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  <java.version>1.8</java.version>
 </properties>
 <dependencies>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <!--
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-jpa</artifactId>
  </dependency>
  -->
  <!--不可使用version 5.3.3,會有一個類的方法找不到-->
  <dependency>
   <groupId>io.searchbox</groupId>
   <artifactId>jest</artifactId>
   <version>5.3.2</version>
  </dependency>
  <!--必須用5.0+,否則會有一個類找不到org/elasticsearch/node/NodeValidationException-->
  <dependency>
   <groupId>org.elasticsearch</groupId>
   <artifactId>elasticsearch</artifactId>
   <version>5.3.3</version>
  </dependency>
  <dependency>
   <groupId>org.springframework.data</groupId>
   <artifactId>spring-data-elasticsearch</artifactId>
   <version>3.0.0.RELEASE</version>
  </dependency>
  <dependency>
   <groupId>com.github.vanroy</groupId>
   <artifactId>spring-boot-starter-data-jest</artifactId>
   <version>3.0.0.RELEASE</version>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-devtools</artifactId>
   <optional>true</optional>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-thymeleaf</artifactId>
  </dependency>
  <!--
  不需要引用
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
  </dependency>
  -->
  <!--spring boot elasticsearch 缺少的jar,需要單獨引入-->
  <dependency>
   <groupId>net.java.dev.jna</groupId>
   <artifactId>jna</artifactId>
   <version>4.5.1</version>
  </dependency>
  <!--webjars 前端框架,整體管理前端js框架-->
  <dependency>
   <groupId>org.webjars</groupId>
   <artifactId>jquery</artifactId>
   <version>3.3.0</version>
  </dependency>
  <dependency>
   <groupId>org.webjars</groupId>
   <artifactId>bootstrap</artifactId>
   <version>4.0.0</version>
  </dependency>
  <!--When using Spring Boot version 1.3 or higher, it will automatically detect the webjars-locator library on the classpath and use it to automatically resolve the version of any WebJar assets for you. In order to enable this feature, you will need to add the webjars-locator library as a dependency of your application in the pom.xml file-->
  <dependency>
   <groupId>org.webjars</groupId>
   <artifactId>webjars-locator</artifactId>
   <version>0.30</version>
  </dependency>
 </dependencies>
 <build>
  <plugins>
   <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
     <fork>true</fork>
    </configuration>
   </plugin>
  </plugins>
 </build>
</project>

創(chuàng)建完成后,項目目錄結(jié)構(gòu)如下:


image

3.Spring Starter配置需使用SpringBootApplication啟動需禁用ElasticsearchAutoConfiguration,ElasticsearchDataAutoConfiguration,否則會有異常HighLightJestSearchResultMapper Bean留待下面解釋,主要為了解決spring data不支持elasticsearch檢索highlight問題,此處為該Bean的注冊

@SpringBootApplication
@EnableAutoConfiguration(exclude = {ElasticsearchAutoConfiguration.class, ElasticsearchDataAutoConfiguration.class})
public class App {
 public static void main(String[] args) throws Exception {
  SpringApplication.run(App.class, args);
 }
 @Bean
 public HighLightJestSearchResultMapper highLightJestSearchResultMapper(){
  return new HighLightJestSearchResultMapper();
 }
}

3.Entity配置

a) 歌曲Entity如下:

通過對Class進(jìn)行Document注解,實現(xiàn)與ElasticSearch中的Index和Type一一對應(yīng)。

該類在最終與ES返回結(jié)果映射時,僅映射其中_source部分。即如下圖部分(highlight另說,后面單獨處理了):


image

@Document(indexName = "songs",type = "sample",shards = 1, replicas = 0, refreshInterval = "-1")
public class Song extends HighLightEntity{
 @Id
 private Long id;
 private String name;
 private String href;
 private String lyric;
 private String singer;
 private String album;
 public Song(Long id, String name, String href, String lyric, String singer, String album, Map<String, List<String>> highlight) {
  //省略
 }
 public Song() {
 }
 //getter setter 省略...
}

b) 為了解決Spring data elasticsearch問題,此處增加一個抽象類:HighLightEntity,其他Entity需要繼承該類

package org.leiws.esweb.entity;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
public abstract class HighLightEntity implements Serializable{
 private Map<String, List<String>> highlight;
 public Map<String, List<String>> getHighlight() {
  return highlight;
 }
 public void setHighlight(Map<String, List<String>> highlight) {
  this.highlight = highlight;
 }
}

4.Repository配置

package org.leiws.esweb.repository;
import org.leiws.esweb.entity.Song;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
public interface SongRepository extends ElasticsearchRepository<Song,Long> {
}

5.Service配置

a) 接口

package org.leiws.esweb.service;
import org.leiws.esweb.entity.Song;
import org.springframework.data.domain.Page;
import java.util.List;
/**
 * The interface Song service.
 */
public interface SongService {
 /**
  * Search song list.
  *
  * @param pNum  the p num
  * @param pSize the p size
  * @param keywords the keywords
  * @return the list
  */
 public Page<Song> searchSong(Integer pNum, Integer pSize, String keywords);
}

b) 實現(xiàn)類

該類實現(xiàn)了具體如何分頁,如何查詢等

package org.leiws.esweb.service.impl;
import com.github.vanroy.springdata.jest.JestElasticsearchTemplate;
import org.apache.log4j.Logger;
import org.elasticsearch.common.lucene.search.function.FiltersFunctionScoreQuery;
import org.elasticsearch.index.query.MatchPhraseQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.leiws.esweb.entity.Song;
import org.leiws.esweb.repository.HighLightJestSearchResultMapper;
import org.leiws.esweb.repository.SongRepository;
import org.leiws.esweb.service.SongService;
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.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;
import static org.elasticsearch.index.query.QueryBuilders.functionScoreQuery;
import static org.elasticsearch.index.query.QueryBuilders.matchPhraseQuery;
import java.util.List;
@Service
public class SongServiceImpl implements SongService{
 private static final Logger LOGGER = Logger.getLogger(SongServiceImpl.class);
 /* 分頁參數(shù) */
 private final static Integer PAGE_SIZE = 12;   // 每頁數(shù)量
 private final static Integer DEFAULT_PAGE_NUMBER = 0; // 默認(rèn)當(dāng)前頁碼
 /* 搜索模式 */
 private final static String SCORE_MODE_SUM = "sum"; // 權(quán)重分求和模式
 private final static Float MIN_SCORE = 10.0F;  // 由于無相關(guān)性的分值默認(rèn)為 1 ,設(shè)置權(quán)重分最小值為 10
 @Autowired
 SongRepository songRepository;
 @Autowired
 JestElasticsearchTemplate jestElasticsearchTemplate;
 @Autowired
 HighLightJestSearchResultMapper jestSearchResultMapper;
 @Override
 public Page<Song> searchSong(Integer pNum, Integer pSize, String keywords) {
  // 校驗分頁參數(shù)
  if (pSize == null || pSize <= 0) {
   pSize = PAGE_SIZE;
  }
  if (pNum == null || pNum < DEFAULT_PAGE_NUMBER) {
   pNum = DEFAULT_PAGE_NUMBER;
  }
  LOGGER.info("\n searchCity: searchContent [" + keywords + "] \n ");
  // 構(gòu)建搜索查詢
  SearchQuery searchQuery = getCitySearchQuery(pNum,pSize,keywords);
  LOGGER.info("\n searchCity: searchContent [" + keywords + "] \n DSL = \n " + searchQuery.getQuery().toString());
//  Page<Song> cityPage = songRepository.search(searchQuery);
  Page<Song> cityPage = jestElasticsearchTemplate.queryForPage(searchQuery,Song.class,jestSearchResultMapper);
  return cityPage;
 }
 /**
  * 根據(jù)搜索詞構(gòu)造搜索查詢語句
  *
  * 代碼流程:
  *  - 權(quán)重分查詢
  *  - 短語匹配
  *  - 設(shè)置權(quán)重分最小值
  *  - 設(shè)置分頁參數(shù)
  *
  * @param pNum 當(dāng)前頁碼
  * @param pSize 每頁大小
  * @param searchContent 搜索內(nèi)容
  * @return
  */
 private SearchQuery getCitySearchQuery(Integer pNum, Integer pSize,String searchContent) {
  /* elasticsearch 2.4.6 版本寫法
  FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery()
    .add(QueryBuilders.boolQuery().should(QueryBuilders.matchQuery("lyric", searchContent)),
      ScoreFunctionBuilders.weightFactorFunction(1000))
    .scoreMode(SCORE_MODE_SUM).setMinScore(MIN_SCORE);
  */
  FunctionScoreQueryBuilder.FilterFunctionBuilder[] functions = {
    new FunctionScoreQueryBuilder.FilterFunctionBuilder(
      matchPhraseQuery("lyric", searchContent),
      ScoreFunctionBuilders.weightFactorFunction(1000))
  };
  FunctionScoreQueryBuilder functionScoreQueryBuilder =
    functionScoreQuery(functions).scoreMode(FiltersFunctionScoreQuery.ScoreMode.SUM).setMinScore(MIN_SCORE);
  // 分頁參數(shù)
//  Pageable pageable = new PageRequest(pNum, pSize);
  Pageable pageable = PageRequest.of(pNum, pSize);
  //高亮提示
  HighlightBuilder.Field highlightField = new HighlightBuilder.Field("lyric")
    .preTags(new String[]{"<font color='red'>", "<b>", "<em>"})
    .postTags(new String[]{"</font>", "</b>", "</em>"})
    .fragmentSize(15)
    .numOfFragments(5)
    //highlightQuery必須單獨設(shè)置,否則在使用FunctionScoreQuery時,highlight配置不生效,返回結(jié)果無highlight元素
    //官方解釋:Highlight matches for a query other than the search query. This is especially useful if you use a rescore query because those are not taken into account by highlighting by default.
    .highlightQuery(matchPhraseQuery("lyric", searchContent));
  return new NativeSearchQueryBuilder()
    .withPageable(pageable)
 //   .withSourceFilter(new FetchSourceFilter(new String[]{"name","singer","lyric"},new String[]{}))
    .withHighlightFields(highlightField)
    .withQuery(functionScoreQueryBuilder).build();
 }
}

c) 解決Spring Data ElasticSearch不支持Highlight的問題

通過自定義實現(xiàn)一個如下的JestSearchResultMapper,解決無法Highlight的問題

package org.leiws.esweb.repository;
//import 省略
public class HighLightJestSearchResultMapper extends DefaultJestResultsMapper {
 private EntityMapper entityMapper;
 private MappingContext<? extends ElasticsearchPersistentEntity<?>, ElasticsearchPersistentProperty> mappingContext;
 public HighLightJestSearchResultMapper() {
  this.entityMapper = new DefaultEntityMapper();
  this.mappingContext = new SimpleElasticsearchMappingContext();
 }
 public HighLightJestSearchResultMapper(MappingContext<? extends ElasticsearchPersistentEntity<?>, ElasticsearchPersistentProperty> mappingContext, EntityMapper entityMapper) {
  this.entityMapper = entityMapper;
  this.mappingContext = mappingContext;
 }
 public EntityMapper getEntityMapper() {
  return entityMapper;
 }
 public void setEntityMapper(EntityMapper entityMapper) {
  this.entityMapper = entityMapper;
 }
 @Override
 public <T> AggregatedPage<T> mapResults(SearchResult response, Class<T> clazz) {
  return mapResults(response, clazz, null);
 }
 @Override
 public <T> AggregatedPage<T> mapResults(SearchResult response, Class<T> clazz, List<AbstractAggregationBuilder> aggregations) {
  LinkedList<T> results = new LinkedList<>();
  for (SearchResult.Hit<JsonObject, Void> hit : response.getHits(JsonObject.class)) {
   if (hit != null) {
    T result = mapSource(hit.source, clazz);
    HighLightEntity highLightEntity = (HighLightEntity) result;
    highLightEntity.setHighlight(hit.highlight);
    results.add((T) highLightEntity);
   }
  }
  String scrollId = null;
  if (response instanceof ExtendedSearchResult) {
   scrollId = ((ExtendedSearchResult) response).getScrollId();
  }
  return new AggregatedPageImpl<>(results, response.getTotal(), response.getAggregations(), scrollId);
 }
 private <T> T mapSource(JsonObject source, Class<T> clazz) {
  String sourceString = source.toString();
  T result = null;
  if (!StringUtils.isEmpty(sourceString)) {
   result = mapEntity(sourceString, clazz);
   setPersistentEntityId(result, source.get(JestResult.ES_METADATA_ID).getAsString(), clazz);
  } else {
   //TODO(Fields results) : Map Fields results
   //result = mapEntity(hit.getFields().values(), clazz);
  }
  return result;
 }
 private <T> T mapEntity(String source, Class<T> clazz) {
  if (isBlank(source)) {
   return null;
  }
  try {
   return entityMapper.mapToObject(source, clazz);
  } catch (IOException e) {
   throw new ElasticsearchException("failed to map source [ " + source + "] to class " + clazz.getSimpleName(), e);
  }
 }
 private <T> void setPersistentEntityId(Object entity, String id, Class<T> clazz) {
  ElasticsearchPersistentEntity<?> persistentEntity = mappingContext.getRequiredPersistentEntity(clazz);
  ElasticsearchPersistentProperty idProperty = persistentEntity.getIdProperty();
  // Only deal with text because ES generated Ids are strings !
  if (idProperty != null) {
   if (idProperty.getType().isAssignableFrom(String.class)) {
    persistentEntity.getPropertyAccessor(entity).setProperty(idProperty, id);
   }
  }
 }
}

上面類的大部分代碼來源于:DefaultJestResultsMapper

重點修改部分為:

@Override
 public <T> AggregatedPage<T> mapResults(SearchResult response, Class<T> clazz, List<AbstractAggregationBuilder> aggregations) {
  LinkedList<T> results = new LinkedList<>();
  for (SearchResult.Hit<JsonObject, Void> hit : response.getHits(JsonObject.class)) {
   if (hit != null) {
    T result = mapSource(hit.source, clazz);
    HighLightEntity highLightEntity = (HighLightEntity) result;
    highLightEntity.setHighlight(hit.highlight);
    results.add((T) highLightEntity);
   }
  }
  String scrollId = null;
  if (response instanceof ExtendedSearchResult) {
   scrollId = ((ExtendedSearchResult) response).getScrollId();
  }
  return new AggregatedPageImpl<>(results, response.getTotal(), response.getAggregations(), scrollId);
 }

6.Controller

相對簡單,如普通的Spring Controller

@Controller
@RequestMapping(value = "/search")
public class SearchController {
 @Autowired
 SongService songService;
 /**
  * Song list string.
  *
  * @param map the map
  * @return the string
  */
 @RequestMapping(method = RequestMethod.GET)
 public String songList(@RequestParam(value = "pNum") Integer pNum,
       @RequestParam(value = "pSize", required = false) Integer pSize,
       @RequestParam(value = "keywords") String keywords,ModelMap map){
  map.addAttribute("pageSong",songService.searchSong(pNum,pSize,keywords));
  return "songList";
 }
}

7.前端頁面thymeleaf模版

存放目錄為:resources/templates/songList.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
 <meta charset="UTF-8"/>
 <title>Title</title>
 <link rel='stylesheet' href='/webjars/bootstrap/css/bootstrap.min.css'>
 <script src="/webjars/jquery/jquery.min.js"></script>
 <script src="/webjars/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<form action="/search" class="px-5 py-3" >
 <div class="input-group">
  <input name="keywords" type="text" class="form-control" placeholder="歌詞搜索,請輸入歌詞內(nèi)容" aria-label="歌詞搜索,請輸入歌詞內(nèi)容" aria-describedby="basic-addon2">
  <div class="input-group-append">
   <button class="btn btn-outline-secondary" type="button">搜索</button>
  </div>
  <input type="hidden" name="pNum" value="0"/>
 </div>
</form>
<div class="alert alert-light" role="alert">
 為您找到0個結(jié)果:
</div>
<ul class="list-group">
 <li th:each="song : ${pageSong.content}" class="list-group-item">
  <div class="row">
   <a th:href="${song.href}">
   <h4 scope="row" th:text="${song.name}" ></h4>
   </a>
   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
   <h6 scope="row" th:text="${song.singer}" class="align-bottom" ></h6>
  </div>
  <!--
   <td><a th:href="@{/users/update/{userId}(userId=${user.id})}" th:text="${user.name}"></a></td>
  -->
  <div class="row">
   <span th:each="highlight : ${song.highlight}">
    <span th:each="word : ${highlight.value}">
     <span th:utext="${word}"></span>...
    </span>
   </span>
  </div>
 </li>
</ul>
<nav aria-label="..." class="">
 <ul class="pagination pagination-sm justify-content-center py-5">
  <li class="page-item ">
   <a class="page-link" href="#">
    <span aria-hidden="true">&laquo;</span>
    <span class="sr-only">Previous</span>
   </a>
  </li>
  <li class="page-item"><a class="page-link" href="#">1</a></li>
  <li class="page-item"><a class="page-link" href="#">2</a></li>
  <li class="page-item"><a class="page-link" href="#">3</a></li>
  <li class="page-item">
   <a class="page-link" href="#">
   <span aria-hidden="true">&raquo;</span>
   <span class="sr-only">Next</span>
   </a>
  </li>
 </ul>
</nav>
</body>
</html>

8.阿里云ElasticSearch連接配置

在resources/application.properties中配置如下:

spring.data.jest.uri=http://1xx.xxx.xxx.xxx:8080
spring.data.jest.username=username
spring.data.jest.password=password
spring.data.jest.maxTotalConnection=50
spring.data.jest.defaultMaxTotalConnectionPerRoute=50
spring.data.jest.readTimeout=5000

9.其他

a) thymeleaf 熱啟動配置,便于測試在resources/application.properties中配置如下:

spring.thymeleaf.cache=false

在pom.xml中增加:

 <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-devtools</artifactId>
   <optional>true</optional>
  </dependency>
<build>
  <plugins>
   <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
     <fork>true</fork>
    </configuration>
   </plugin>
  </plugins>
 </build>

3.每次還是需要重新compile后,修改的thymeleaf模版代碼才會自動生效,因為spring boot啟動是以target目錄為準(zhǔn)的

b) 阿里云elasticsearch在esc上配置ngnix代理,以支持本機(jī)可以公網(wǎng)訪問,便于開發(fā)購買一臺esc在ecs上安裝ngnix,并配置代理信息server 部分如下:

server {
  listen  8080;
  #listen  [::]:80 default_server;
  server_name {本機(jī)內(nèi)網(wǎng)ip} {本機(jī)外網(wǎng)ip};
  #root   /usr/share/nginx/html;
  # Load configuration files for the default server block.
  #include /etc/nginx/default.d/*.conf;
  location / {
      proxy_pass http://{elasticsearch 內(nèi)網(wǎng) ip}:9200;
  }
 }

10. 最后,查詢效果:

image

總結(jié)

以上所述是小編給大家介紹的SpringBoot 整合Jest實例代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!

相關(guān)文章

  • SpringBoot中fastjson自定義序列化和反序列化的實戰(zhàn)分享

    SpringBoot中fastjson自定義序列化和反序列化的實戰(zhàn)分享

    在fastjson庫中,為了提供靈活的序列化和反序列化機(jī)制,設(shè)計了一系列的擴(kuò)展點,以下是在SpringBoot和SpringClould環(huán)境中對這些擴(kuò)展點的詳細(xì)介紹及其實戰(zhàn)使用,通過代碼示例講解的非常詳細(xì),需要的朋友可以參考下
    2024-07-07
  • Java中的Object類詳細(xì)介紹

    Java中的Object類詳細(xì)介紹

    這篇文章主要介紹了Java中的Object類詳細(xì)介紹,本文講解了Object類的作用、Object類的主要方法、Object類中不能被重寫的方法、Object類的equals方法重寫實例等內(nèi)容,需要的朋友可以參考下
    2015-06-06
  • Springboot整合mybatis-plus使用pageHelper進(jìn)行分頁(使用步驟)

    Springboot整合mybatis-plus使用pageHelper進(jìn)行分頁(使用步驟)

    PageHelper是一個MyBatis分頁插件,可以方便地實現(xiàn)數(shù)據(jù)庫查詢結(jié)果的分頁功能,在Maven或Gradle項目中引入依賴,并在配置文件中進(jìn)行配置,本文給大家介紹Springboot整合mybatis-plus使用pageHelper進(jìn)行分頁,感興趣的朋友跟隨小編一起看看吧
    2024-11-11
  • 解決window.location.href之后session丟失的問題

    解決window.location.href之后session丟失的問題

    今天小編就為大家分享一篇關(guān)于解決window.location.href之后session丟失的問題,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2018-12-12
  • Maven依賴管理的用法介紹

    Maven依賴管理的用法介紹

    依賴管理是項目管理中非常重要的一環(huán)。幾乎任何項目開發(fā)的時候需要都需要使用到庫。而這些庫很可能又依賴別的庫,這樣整個項目的依賴形成了一個樹狀結(jié)構(gòu),而隨著這個依賴的樹的延伸和擴(kuò)大,一系列問題就會隨之產(chǎn)生
    2022-08-08
  • java實現(xiàn)Redisson的基本使用

    java實現(xiàn)Redisson的基本使用

    Redisson是一個在Redis的基礎(chǔ)上實現(xiàn)的Java駐內(nèi)存數(shù)據(jù)網(wǎng)格客戶端,本文主要介紹了java實現(xiàn)Redisson的基本使用,具有一定的參考價值,感興趣的可以了解一下
    2023-12-12
  • nacos服務(wù)注冊命名空間指定方式

    nacos服務(wù)注冊命名空間指定方式

    文章介紹了Nacos服務(wù)注冊命名空間的用途,以及如何創(chuàng)建和指定命名空間,命名空間用于隔離不同項目的服務(wù)和配置,避免沖突,通過在配置文件中指定命名空間ID,服務(wù)會注冊到相應(yīng)的命名空間中,這樣可以更好地管理不同環(huán)境下的配置文件
    2024-12-12
  • IDEA常用插件之類Jar包搜索Maven Search解讀

    IDEA常用插件之類Jar包搜索Maven Search解讀

    文章介紹了IDEA常用插件MavenSearch的使用方法,該插件可以幫助用戶快速查找和瀏覽Maven中央存儲庫中可用的依賴項和插件,方便用戶管理項目依賴項
    2025-01-01
  • Spring配置shiro時自定義Realm中屬性無法使用注解注入的解決辦法

    Spring配置shiro時自定義Realm中屬性無法使用注解注入的解決辦法

    今天小編就為大家分享一篇關(guān)于Spring配置shiro時自定義Realm中屬性無法使用注解注入的解決辦法,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2019-03-03
  • 如何使用MybatisPlus的SQL注入器提升批量插入性能

    如何使用MybatisPlus的SQL注入器提升批量插入性能

    本文給大家介紹如何使用MybatisPlus的SQL注入器提升批量插入性能,以實戰(zhàn)視角講述如何利用該特性提升MybatisPlus?的批量插入性能,感興趣的朋友跟隨小編一起看看吧
    2024-05-05

最新評論

沙雅县| 彝良县| 河曲县| 南充市| 墨玉县| 县级市| 昆明市| 韶关市| 连山| 鄂托克旗| 曲麻莱县| 大港区| 开原市| 怀宁县| 建瓯市| 弥渡县| 太白县| 曲麻莱县| 德保县| 绵竹市| 忻城县| 鹤山市| 咸丰县| 遂川县| 舟山市| 黄骅市| 澎湖县| 文山县| 醴陵市| 亳州市| 垣曲县| 长顺县| 临武县| 盖州市| 湟中县| 老河口市| 合作市| 陆川县| 通河县| 合阳县| 宁安市|