SpringBoot集成ElasticSearch(ES)實(shí)現(xiàn)全文搜索功能
Document可以看作表中的一條記錄,Index可以看作Database數(shù)據(jù)庫,而Type就是里面的Table表。
一、依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency>
二、在application.properties文件中添加ElasticSearch連接信息
server.port=8080 #es 配置信息 spring.main.allow-bean-definition-overriding=true elasticsearch.host=127.0.0.1 elasticsearch.port=9300 elasticsearch.clustername=elasticsearch elasticsearch.search.pool.size=5
啟動類
@SpringBootApplication
public class SSD08Application {
public static void main(String[] args) {
SpringApplication.run(SSD08Application.class, args);
}
}
三、創(chuàng)建Elasticsearch配置類
@Slf4j
@Configuration
@EnableElasticsearchRepositories(basePackages = "com.yoodb.study.demo08.service")
public class ElasticsearchConfig{
@Value("${elasticsearch.host}")
private String esHost;
@Value("${elasticsearch.port}")
private int esPort;
@Value("${elasticsearch.clustername}")
private String esClusterName;
@Value("${elasticsearch.search.pool.size}")
private Integer threadPoolSearchSize;
@Bean
public Client client() throws Exception{
Settings esSettings = Settings.builder()
.put("cluster.name",esClusterName)
.put("client.transoprt.sniff",true)
.put("thread_pool.search.size",threadPoolSearchSize)
.build();
return new PreBuiltTransportClient(esSettings)
.addTransoprtAddress(new TransportAddress(InetAddress.getByName(esHost), esPort));
}
@Bean(name="elasticsearchTemplate")
public ElasticsearchOperations elasticsearchTemplateCustom() throws Exception {
ElasticsearchTemplate elasticsearchTemplate;
try{
elasticsearchTemplate = new ElasticsearchTemplate(client());
return elasticsearchTemplate;
}catch(Exception e){
return new ElasticsearchTemplate(client());
}
}
}
四、創(chuàng)建Article實(shí)體類
@Document 作用在類,標(biāo)記實(shí)體類為文檔對象,一般有兩個(gè)屬性
indexName:對應(yīng)索引庫名稱
type:對應(yīng)在索引庫中的類型
shards:分片數(shù)量,默認(rèn)分5片
replicas:副本數(shù)量,默認(rèn)1份
- @Id 作用在成員變量,標(biāo)記一個(gè)字段作為id主鍵
- @Field 作用在成員變量,標(biāo)記為文檔的字段,并指定字段映射屬性
type:字段類型,取值是枚舉:FieldType
index:是否索引,布爾類型,默認(rèn)是true
store:是否存儲,布爾類型,默認(rèn)是false
analyzer和searchAnalyzer中參數(shù)名稱保持一直,ik_max_word可以改成ik_smart
ik_max_word和ik_smart的區(qū)別?
- ik_max_word參數(shù)采用窮盡式的分詞,比如“我愛家鄉(xiāng)”,可能會分出“我”,“我愛”,“家鄉(xiāng)”等
- ik_smart參數(shù)分的會比較粗,如上語句可能會分出“我愛”,“家鄉(xiāng)”這樣
如果想要搜索出的結(jié)果盡可能全,可以使用ik_max_word參數(shù),如果需要結(jié)果盡可能精確,可以使用ik_smart參數(shù)
Document(indexName = "blog",type = "article")
public class Article {
/**
* 主鍵ID
*/
@Field(type = FieldType.Keyword)
private String id;
/**
* 文章標(biāo)題
*/
@Field(type = FieldType.Text, analyzer = "ik_max_word",searchAnalyzer = "ik_max_word")
private String title;
/**
* 文章內(nèi)容
*/
@Field(type = FieldType.Text, analyzer = "ik_max_word",searchAnalyzer = "ik_max_word")
private String content;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
五、繼承ElasticsearchRepository接口
public interface ElasticRepository extends ElasticsearchRepository<Article, String> {
}
六、IElasticService接口以及實(shí)現(xiàn)類
public interface IElasticService {
public void save(Article article);
public void saveAll(List<Article> list);
public Iterator<Article> findAll();
public List<Article> findArticleByTitle(String title);
}
@Service("elasticService")
public class ElasticServiceImpl implements IElasticService {
@Autowired
private ElasticRepository elasticRepository;
@Override
public void save(Article article) {
elasticRepository.deleteAll();
elasticRepository.save(article);
}
@Override
public void saveAll(List<Article> list) {
elasticRepository.saveAll(list);
}
@Override
public Iterator<Article> findAll() {
return elasticRepository.findAll().iterator();
}
public List<Article> findArticleByTitle(String title) {
//matchQuery 對關(guān)鍵字分詞后進(jìn)行搜索
MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("title", title);
QueryBuilders.commonTermsQuery("title",title);
Iterable<Article> search = elasticRepository.search(matchQueryBuilder);
Iterator<Article> iterator = search.iterator();
List<Article> list = new ArrayList<>();
while (iterator.hasNext()){
Article next = iterator.next();
list.add(next);
}
return list;
}
}
七、控制層Controller
@Log4j2
@RestController
@RequestMapping("/elastic")
public class ElasticController {
@Autowired
private IElasticService elasticService;
@GetMapping("/init")
public void init(){
String title = "關(guān)注“Java精選”微信公眾號";
String content = "Java精選專注程序員推送一些Java開發(fā)知識,包括基礎(chǔ)知識、各大流行框架" +
"(Mybatis、Spring、Spring Boot等)、大數(shù)據(jù)技術(shù)(Storm、Hadoop、MapReduce、Spark等)、" +
"數(shù)據(jù)庫(Mysql、Oracle、NoSQL等)、算法與數(shù)據(jù)結(jié)構(gòu)、面試專題、面試技巧經(jīng)驗(yàn)、職業(yè)規(guī)劃以及" +
"優(yōu)質(zhì)開源項(xiàng)目等。其中一部分由小編總結(jié)整理,另一部分來源于網(wǎng)絡(luò)上優(yōu)質(zhì)資源,希望對大家的學(xué)習(xí)" +
"和工作有所幫助。";
Article article = createArticle(title, content);
elasticService.save(article);
title = "關(guān)注素文宅博客";
content = "素文宅博客主要關(guān)于一些Java技術(shù)類型文章分享。";
article = createArticle(title, content);
List<Article> list = new ArrayList<>();
list.add(article);
elasticService.saveAll(list);
}
public static Article createArticle(String title,String content){
UUID uuid = UUID.randomUUID();
String id = uuid.toString();
Article article = new Article();
article.setId(id);
article.setTitle(title);
article.setContent(content);
return article;
}
@GetMapping("/all")
public Iterator<Article> all(){
return elasticService.findAll();
}
@GetMapping("/key")
public List<Article> all(String title){
return elasticService.findArticleByTitle(title);
}
}
運(yùn)行程序
1)啟動ElasticSearch服務(wù)


2)啟動SpringBoot項(xiàng)目訪問地址
初始化生成索引文件訪問地址
http://localhost:8080/elastic/init
獲取所有索引內(nèi)容訪問地址
http://localhost:8080/elastic/all
[{"id":"62e73653-4658-4d72-9b2e-e541a3ae7d53","title":"關(guān)注“Java精選”微信公眾號","content":"Java精選專注程序員推送一些Java開發(fā)知識,包括基礎(chǔ)知識、各大流行框架(Mybatis、Spring、Spring Boot等)、大數(shù)據(jù)技術(shù)(Storm、Hadoop、MapReduce、Spark等)、數(shù)據(jù)庫(Mysql、Oracle、NoSQL等)、算法與數(shù)據(jù)結(jié)構(gòu)、面試專題、面試技巧經(jīng)驗(yàn)、職業(yè)規(guī)劃以及優(yōu)質(zhì)開源項(xiàng)目等。其中一部分由小編總結(jié)整理,另一部分來源于網(wǎng)絡(luò)上優(yōu)質(zhì)資源,希望對大家的學(xué)習(xí)和工作有所幫助。"},{"id":"1e7c2f0b-e07e-4037-a3a3-3385d8b7d2c1","title":"關(guān)注素文宅博客","content":"素文宅博客主要關(guān)于一些Java技術(shù)類型文章分享。"}]
根據(jù)搜索條件,獲取索引內(nèi)容訪問地址
http://localhost:8080/elastic/key?title=Java%E7%B2%BE%E9%80%89
返回結(jié)果:
[{"id":"62e73653-4658-4d72-9b2e-e541a3ae7d53","title":"關(guān)注“Java精選”微信公眾號","content":"Java精選專注程序員推送一些Java開發(fā)知識,包括基礎(chǔ)知識、各大流行框架(Mybatis、Spring、Spring Boot等)、大數(shù)據(jù)技術(shù)(Storm、Hadoop、MapReduce、Spark等)、數(shù)據(jù)庫(Mysql、Oracle、NoSQL等)、算法與數(shù)據(jù)結(jié)構(gòu)、面試專題、面試技巧經(jīng)驗(yàn)、職業(yè)規(guī)劃以及優(yōu)質(zhì)開源項(xiàng)目等。其中一部分由小編總結(jié)整理,另一部分來源于網(wǎng)絡(luò)上優(yōu)質(zhì)資源,希望對大家的學(xué)習(xí)和工作有所幫助。"}]
以上就是SpringBoot集成ElasticSearch(ES)實(shí)現(xiàn)全文搜索功能的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot ElasticSearch全文搜索的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Java使用x-www-form-urlencoded發(fā)請求方式
在開發(fā)中經(jīng)常使用JSON格式,但遇到x-www-form-urlencoded格式時(shí),可以通過重新封裝處理,POSTMan和APIpost工具中對此編碼的稱呼不同,分別是x-www-form-urlencoded和urlencoded,分享這些經(jīng)驗(yàn)希望對他人有所幫助2024-09-09
SpringSecurit鹽值加密的密碼驗(yàn)證以及強(qiáng)密碼驗(yàn)證過程
在密碼加密過程中,鹽值的使用可以增強(qiáng)密碼的安全性,如果忘記存儲鹽值,將無法驗(yàn)證密碼,強(qiáng)密碼應(yīng)包含數(shù)字、字母和特殊字符,長度應(yīng)在8到30位之間,以提高賬戶安全2023-03-03
javafx 如何將項(xiàng)目打包為 Windows 的可執(zhí)行文件exe
文章介紹了三種將JavaFX項(xiàng)目打包為.exe文件的方法:方法1使用jpackage(適用于JDK14及以上版本),方法2使用Launch4j(適用于所有JDK版本),方法3使用InnoSetup(用于創(chuàng)建安裝包),每種方法都有其特點(diǎn)和適用范圍,可以根據(jù)項(xiàng)目需求選擇合適的方法,感興趣的朋友一起看看吧2025-01-01
Java Web基于Session的登錄實(shí)現(xiàn)方法
這篇文章主要介紹了Java Web基于Session的登錄實(shí)現(xiàn)方法,涉及Java針對session的操作及表單提交與驗(yàn)證技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-10-10
Java8?CompletableFuture?runAsync學(xué)習(xí)總結(jié)submit()?execute()等
這篇文章主要介紹了Java8?CompletableFuture?runAsync學(xué)習(xí)總結(jié)submit()?execute()等,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-10-10
一文帶你看懂Java8中的lambda表達(dá)式和方法引用
Lambda 表達(dá)式是 Java 8 引入的一項(xiàng)重要特性,它提供了一種簡潔、清晰且靈活的語法來表示可傳遞的匿名函數(shù),下面就跟隨小編一起學(xué)習(xí)一下Java8中的lambda表達(dá)式和方法引用的相關(guān)知識吧2023-12-12
Springcloud Config支持本地配置文件的方法示例
這篇文章主要介紹了Springcloud Config支持本地配置文件的方法示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-02-02
SpringBoot?Validation快速實(shí)現(xiàn)數(shù)據(jù)校驗(yàn)的示例代碼
在實(shí)際開發(fā)中,肯定會經(jīng)常遇到對參數(shù)字段進(jìn)行校驗(yàn)的場景,通常我們只能寫大量的if else來完成校驗(yàn)工作,而如果使用SpringBoot Validation則可以輕松的通過注解來完成,接下來小編給大家介紹下利用SpringBoot?Validation快速實(shí)現(xiàn)數(shù)據(jù)校驗(yàn)的示例代碼,需要的朋友參考下吧2022-06-06

