SpringBoot與Elasticsearch8.0集成的實(shí)現(xiàn)步驟
前言
Elasticsearch 是一個(gè)功能強(qiáng)大的分布式搜索引擎,被廣泛應(yīng)用于日志分析、全文搜索、監(jiān)控等場(chǎng)景。Elasticsearch 8.0 帶來了許多新特性,如安全增強(qiáng)、性能優(yōu)化、API 改進(jìn)等。本文將深入探討 Spring Boot 與 Elasticsearch 8.0 的集成方法和最佳實(shí)踐,幫助你構(gòu)建更高效、更可靠的搜索應(yīng)用。
1. Elasticsearch 8.0 新特性
1.1 安全增強(qiáng)
Elasticsearch 8.0 強(qiáng)化了安全性,默認(rèn)啟用了安全功能,包括:
- HTTPS 加密:默認(rèn)啟用 HTTPS 通信
- 內(nèi)置用戶認(rèn)證:默認(rèn)創(chuàng)建內(nèi)置用戶
- 基于角色的訪問控制:更細(xì)粒度的權(quán)限控制
- 審計(jì)日志:記錄安全相關(guān)的操作
1.2 性能優(yōu)化
Elasticsearch 8.0 在性能方面進(jìn)行了多項(xiàng)優(yōu)化:
- 倒排索引優(yōu)化:提高查詢性能
- 內(nèi)存管理改進(jìn):減少內(nèi)存使用
- 寫入性能優(yōu)化:提高寫入速度
- 聚合性能改進(jìn):加速聚合操作
1.3 API 改進(jìn)
Elasticsearch 8.0 對(duì) API 進(jìn)行了改進(jìn):
- 統(tǒng)一的 REST API:簡化 API 使用
- 新的 Java 客戶端:提供更強(qiáng)大的 Java API
- 改進(jìn)的查詢 DSL:更靈活的查詢語法
- 異步 API:支持異步操作
1.4 其他新特性
- 數(shù)據(jù)生命周期管理:更靈活的數(shù)據(jù)管理
- 向量搜索:支持向量相似度搜索
- 自動(dòng)索引管理:簡化索引管理
- 改進(jìn)的監(jiān)控:更豐富的監(jiān)控指標(biāo)
2. Spring Boot 與 Elasticsearch 集成
2.1 添加依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<!-- 可選:使用 Elasticsearch 高級(jí)客戶端 -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>8.0.0</version>
</dependency>2.2 配置 Elasticsearch
spring:
elasticsearch:
uris: https://localhost:9200
username: elastic
password: your-password
connection-timeout: 10000
socket-timeout: 10000
2.3 Elasticsearch 客戶端配置
@Configuration
public class ElasticsearchConfig {
@Bean
public RestHighLevelClient elasticsearchClient() {
ClientConfiguration clientConfiguration = ClientConfiguration.builder()
.connectedTo("localhost:9200")
.withBasicAuth("elastic", "your-password")
.withConnectTimeout(Duration.ofSeconds(10))
.withSocketTimeout(Duration.ofSeconds(10))
.withTls()
.build();
return RestClients.create(clientConfiguration).rest();
}
}3. 實(shí)體映射
3.1 基本實(shí)體映射
@Document(indexName = "users")
public class User {
@Id
private String id;
@Field(type = FieldType.Text)
private String name;
@Field(type = FieldType.Integer)
private int age;
@Field(type = FieldType.Text, analyzer = "ik_max_word")
private String address;
@Field(type = FieldType.Date)
private LocalDateTime createdAt;
// getters and setters
}3.2 復(fù)雜實(shí)體映射
@Document(indexName = "products")
public class Product {
@Id
private String id;
@Field(type = FieldType.Text)
private String name;
@Field(type = FieldType.Double)
private double price;
@Field(type = FieldType.Keyword)
private String category;
@Field(type = FieldType.Nested)
private List<Review> reviews;
@Field(type = FieldType.Object)
private Manufacturer manufacturer;
// getters and setters
}
public class Review {
@Field(type = FieldType.Integer)
private int rating;
@Field(type = FieldType.Text)
private String comment;
@Field(type = FieldType.Date)
private LocalDateTime createdAt;
// getters and setters
}
public class Manufacturer {
@Field(type = FieldType.Text)
private String name;
@Field(type = FieldType.Text)
private String country;
// getters and setters
}4. 倉庫接口
4.1 基本倉庫接口
public interface UserRepository extends ElasticsearchRepository<User, String> {
// 基于方法名的查詢
List<User> findByName(String name);
List<User> findByAgeBetween(int minAge, int maxAge);
List<User> findByNameAndAge(String name, int age);
}4.2 自定義查詢
public interface ProductRepository extends ElasticsearchRepository<Product, String> {
// 使用 @Query 注解
@Query("{\"bool\": {\"must\": [{\"match\": {\"name\": \"?0\"}}, {\"range\": {\"price\": {\"lte\": ?1}}}]}}")
List<Product> findByNameAndPriceLessThanEqual(String name, double price);
// 基于方法名的復(fù)雜查詢
List<Product> findByCategoryAndReviewsRatingGreaterThan(String category, int rating);
}5. 操作示例
5.1 基本操作
@Service
public class UserService {
private final UserRepository userRepository;
@Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
// 保存用戶
public User saveUser(User user) {
return userRepository.save(user);
}
// 根據(jù) ID 查詢用戶
public Optional<User> getUserById(String id) {
return userRepository.findById(id);
}
// 查詢所有用戶
public Iterable<User> getAllUsers() {
return userRepository.findAll();
}
// 刪除用戶
public void deleteUser(String id) {
userRepository.deleteById(id);
}
// 根據(jù)名稱查詢用戶
public List<User> getUsersByName(String name) {
return userRepository.findByName(name);
}
}5.2 高級(jí)查詢
@Service
public class ProductService {
private final ProductRepository productRepository;
private final ElasticsearchOperations elasticsearchOperations;
@Autowired
public ProductService(ProductRepository productRepository, ElasticsearchOperations elasticsearchOperations) {
this.productRepository = productRepository;
this.elasticsearchOperations = elasticsearchOperations;
}
// 復(fù)雜查詢
public List<Product> searchProducts(String keyword, double maxPrice, String category) {
NativeSearchQuery query = new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.boolQuery()
.must(QueryBuilders.multiMatchQuery(keyword, "name", "description"))
.filter(QueryBuilders.rangeQuery("price").lte(maxPrice))
.filter(QueryBuilders.termQuery("category", category)))
.withSort(SortBuilders.fieldSort("price").order(SortOrder.ASC))
.withPageable(PageRequest.of(0, 10))
.build();
return elasticsearchOperations.search(query, Product.class)
.stream()
.map(SearchHit::getContent)
.collect(Collectors.toList());
}
}5.3 聚合操作
@Service
public class AnalyticsService {
private final ElasticsearchOperations elasticsearchOperations;
@Autowired
public AnalyticsService(ElasticsearchOperations elasticsearchOperations) {
this.elasticsearchOperations = elasticsearchOperations;
}
// 按類別聚合產(chǎn)品
public Map<String, Long> getProductCountByCategory() {
NativeSearchQuery query = new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.matchAllQuery())
.withAggregations(AggregationBuilders.terms("byCategory").field("category"))
.build();
SearchHits<Product> searchHits = elasticsearchOperations.search(query, Product.class);
Terms terms = searchHits.getAggregations().get("byCategory");
Map<String, Long> result = new HashMap<>();
for (Terms.Bucket bucket : terms.getBuckets()) {
result.put(bucket.getKeyAsString(), bucket.getDocCount());
}
return result;
}
// 計(jì)算平均價(jià)格
public double getAveragePrice() {
NativeSearchQuery query = new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.matchAllQuery())
.withAggregations(AggregationBuilders.avg("averagePrice").field("price"))
.build();
SearchHits<Product> searchHits = elasticsearchOperations.search(query, Product.class);
Avg avg = searchHits.getAggregations().get("averagePrice");
return avg.getValue();
}
}
6. 批量操作
6.1 批量索引
@Service
public class BulkService {
private final ElasticsearchOperations elasticsearchOperations;
@Autowired
public BulkService(ElasticsearchOperations elasticsearchOperations) {
this.elasticsearchOperations = elasticsearchOperations;
}
// 批量索引文檔
public void bulkIndex(List<User> users) {
elasticsearchOperations.bulkIndex(users, IndexCoordinates.of("users"));
}
// 批量刪除文檔
public void bulkDelete(List<String> ids) {
List<DeleteQuery> deleteQueries = ids.stream()
.map(id -> {
DeleteQuery deleteQuery = new DeleteQuery();
deleteQuery.setId(id);
return deleteQuery;
})
.collect(Collectors.toList());
elasticsearchOperations.bulkDelete(deleteQueries, User.class, IndexCoordinates.of("users"));
}
}7. 性能優(yōu)化
7.1 索引優(yōu)化
- 合理設(shè)計(jì)索引:根據(jù)業(yè)務(wù)需求設(shè)計(jì)合理的索引結(jié)構(gòu)
- 使用合適的字段類型:選擇合適的字段類型,如 keyword、text、numeric 等
- 配置分析器:為文本字段配置合適的分析器
- 設(shè)置合理的分片和副本:根據(jù)數(shù)據(jù)量和查詢需求設(shè)置分片和副本數(shù)量
7.2 查詢優(yōu)化
- 使用過濾器:對(duì)不需要評(píng)分的查詢使用過濾器
- 避免深度分頁:使用 scroll API 或 search after 進(jìn)行深度分頁
- 使用聚合緩存:對(duì)頻繁使用的聚合啟用緩存
- 優(yōu)化查詢語句:避免復(fù)雜的嵌套查詢
7.3 寫入優(yōu)化
- 使用批量操作:使用 bulk API 進(jìn)行批量寫入
- 合理設(shè)置刷新間隔:根據(jù)業(yè)務(wù)需求設(shè)置合適的刷新間隔
- 使用異步寫入:使用異步 API 進(jìn)行寫入操作
- 避免實(shí)時(shí)索引:對(duì)非實(shí)時(shí)數(shù)據(jù)使用延遲索引
8. 最佳實(shí)踐
8.1 代碼組織
// 推薦的代碼組織結(jié)構(gòu) com.example ├── entity/ // 實(shí)體類 ├── repository/ // 倉庫接口 ├── service/ // 業(yè)務(wù)邏輯 ├── controller/ // 控制器 └── config/ // 配置類
8.2 錯(cuò)誤處理
@Service
public class UserService {
private final UserRepository userRepository;
@Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public User getUserById(String id) {
try {
return userRepository.findById(id)
.orElseThrow(() -> new EntityNotFoundException("User not found"));
} catch (ElasticsearchException e) {
throw new RuntimeException("Error querying Elasticsearch", e);
}
}
}8.3 監(jiān)控與日志
management:
endpoints:
web:
exposure:
include: health,info,metrics,prometheus
endpoint:
health:
show-details: always
logging:
level:
org.elasticsearch.client: debug9. 案例分析
9.1 全文搜索系統(tǒng)
某電商平臺(tái)使用 Elasticsearch 實(shí)現(xiàn)全文搜索功能,主要包括:
- 商品索引:將商品信息索引到 Elasticsearch
- 全文搜索:支持商品名稱、描述的全文搜索
- 過濾和排序:支持按價(jià)格、類別等過濾和排序
- 聚合分析:提供商品分類統(tǒng)計(jì)、價(jià)格分布等分析
9.2 日志分析系統(tǒng)
某企業(yè)使用 Elasticsearch 實(shí)現(xiàn)日志分析系統(tǒng),主要包括:
- 日志收集:使用 Logstash 收集應(yīng)用日志
- 日志索引:將日志索引到 Elasticsearch
- 日志查詢:支持按時(shí)間、級(jí)別、關(guān)鍵詞等查詢?nèi)罩?/li>
- 監(jiān)控告警:基于日志內(nèi)容設(shè)置告警規(guī)則
9.3 實(shí)時(shí)數(shù)據(jù)分析
某金融機(jī)構(gòu)使用 Elasticsearch 實(shí)現(xiàn)實(shí)時(shí)數(shù)據(jù)分析,主要包括:
- 數(shù)據(jù)采集:實(shí)時(shí)采集交易數(shù)據(jù)
- 數(shù)據(jù)索引:將數(shù)據(jù)索引到 Elasticsearch
- 實(shí)時(shí)查詢:支持實(shí)時(shí)查詢和分析
- 可視化:使用 Kibana 可視化數(shù)據(jù)
10. 未來趨勢(shì)
10.1 向量搜索
Elasticsearch 8.0 開始支持向量搜索,這將為 AI 應(yīng)用提供強(qiáng)大的支持,例如:
- 語義搜索:基于文本語義進(jìn)行搜索
- 圖像搜索:基于圖像特征進(jìn)行搜索
- 推薦系統(tǒng):基于用戶行為向量進(jìn)行推薦
10.2 邊緣計(jì)算
Elasticsearch 正在向邊緣計(jì)算擴(kuò)展,支持在邊緣設(shè)備上部署輕量級(jí)實(shí)例,實(shí)現(xiàn):
- 本地?cái)?shù)據(jù)處理:在邊緣設(shè)備上處理數(shù)據(jù)
- 低延遲查詢:減少網(wǎng)絡(luò)延遲
- 離線操作:支持離線環(huán)境下的搜索
10.3 AI 集成
Elasticsearch 與 AI 技術(shù)的集成將成為未來的趨勢(shì),例如:
- 智能搜索:使用 AI 提高搜索準(zhǔn)確性
- 自動(dòng)索引:使用 AI 自動(dòng)優(yōu)化索引結(jié)構(gòu)
- 異常檢測(cè):使用 AI 檢測(cè)異常數(shù)據(jù)
11. 總結(jié)
Spring Boot 與 Elasticsearch 8.0 的集成是構(gòu)建高性能搜索應(yīng)用的重要組成部分。通過本文的介紹,你應(yīng)該對(duì) Spring Boot 與 Elasticsearch 8.0 的集成方法和最佳實(shí)踐有了更深入的了解。
Elasticsearch 8.0 的新特性為我們提供了更強(qiáng)大的功能和更好的性能,通過合理使用這些特性,我們可以構(gòu)建更高效、更可靠的搜索應(yīng)用。
結(jié)語
Elasticsearch 是一個(gè)功能強(qiáng)大的搜索引擎,它為我們提供了豐富的功能和靈活的 API。Spring Boot 與 Elasticsearch 的集成使得我們可以更方便地使用 Elasticsearch 的功能,構(gòu)建各種搜索和分析應(yīng)用。
隨著 Elasticsearch 的不斷發(fā)展,它將為我們提供更多強(qiáng)大的功能,幫助我們解決各種復(fù)雜的搜索和分析問題。
到此這篇關(guān)于SpringBoot與Elasticsearch8.0集成的文章就介紹到這了,更多相關(guān)SpringBoot Elasticsearch8.0集成內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot集成ElasticSearch實(shí)現(xiàn)搜索功能
- SpringBoot3集成ElasticSearch的方法詳解
- SpringBoot集成elasticsearch使用圖文詳解
- SpringBoot集成ElasticSearch的示例代碼
- Springboot集成Elasticsearch的步驟與相關(guān)功能
- SpringBoot框架集成ElasticSearch實(shí)現(xiàn)過程示例詳解
- springboot集成elasticsearch7的圖文方法
- SpringBoot集成Elasticsearch過程實(shí)例
- Springboot集成spring data elasticsearch過程詳解
相關(guān)文章
springboot實(shí)現(xiàn)以代碼的方式配置sharding-jdbc水平分表
這篇文章主要介紹了springboot實(shí)現(xiàn)以代碼的方式配置sharding-jdbc水平分表,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-11-11
mybatis關(guān)聯(lián)關(guān)系映射的實(shí)現(xiàn)
MyBatis的關(guān)聯(lián)關(guān)系映射在復(fù)雜數(shù)據(jù)模型中至關(guān)重要,使開發(fā)人員能夠以最靈活的方式滿足不同項(xiàng)目的需求,本文就來介紹一下mybatis關(guān)聯(lián)關(guān)系映射的實(shí)現(xiàn),感興趣的可以了解一下2023-09-09
基于OAuth2.0授權(quán)系統(tǒng)的驗(yàn)證碼功能的實(shí)現(xiàn)
本篇教程給大家分享基于OAuth2.0授權(quán)系統(tǒng)的驗(yàn)證碼功能的實(shí)現(xiàn),驗(yàn)證碼功能的實(shí)現(xiàn)是采用Zuul網(wǎng)關(guān)的Filter過濾器進(jìn)行校驗(yàn)驗(yàn)證碼,具體實(shí)現(xiàn)代碼跟隨小編一起看看吧2021-05-05
Springboot通過請(qǐng)求頭獲取當(dāng)前用戶信息方法詳細(xì)示范
這篇文章主要介紹了Springboot通過請(qǐng)求頭獲取當(dāng)前用戶信息的方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2022-11-11
springboot指定profiles啟動(dòng)失敗問題及解決
這篇文章主要介紹了springboot指定profiles啟動(dòng)失敗問題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-04-04
SpringBoot2.X Kotlin系列之?dāng)?shù)據(jù)校驗(yàn)和異常處理詳解
這篇文章主要介紹了SpringBoot 2.X Kotlin系列之?dāng)?shù)據(jù)校驗(yàn)和異常處理詳解,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2019-04-04
親測(cè)SpringBoot參數(shù)傳遞及@RequestBody注解---踩過的坑及解決
這篇文章主要介紹了親測(cè)SpringBoot參數(shù)傳遞及@RequestBody注解---踩過的坑及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-10-10

