使用Spring Boot集成中間件:Elasticsearch基礎(chǔ)->提高篇
導(dǎo)言
Elasticsearch是一個(gè)開(kāi)源的分布式搜索和分析引擎,廣泛用于構(gòu)建實(shí)時(shí)的搜索和分析應(yīng)用。在本篇博客中,我們將深入講解如何使用Spring Boot集成Elasticsearch,實(shí)現(xiàn)數(shù)據(jù)的索引、搜索和分析。
一、 Elasticsearch一些基本操作和配置
1. 準(zhǔn)備工作
在開(kāi)始之前,確保已經(jīng)完成以下準(zhǔn)備工作:
- 安裝并啟動(dòng)Elasticsearch集群
- 創(chuàng)建Elasticsearch索引和映射(Mapping)
2. 添加依賴(lài)
首先,需要在Spring Boot項(xiàng)目中添加Elasticsearch的依賴(lài)。在pom.xml
文件中加入以下依賴(lài):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
3. 配置Elasticsearch連接
在application.properties
或application.yml
中配置Elasticsearch的連接信息:
spring.data.elasticsearch.cluster-nodes=localhost:9200
4. 創(chuàng)建實(shí)體類(lèi)
創(chuàng)建一個(gè)Java實(shí)體類(lèi),用于映射Elasticsearch中的文檔。
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
@Document(indexName = "blog", type = "article")
public class Article {
@Id
private String id;
private String title;
private String content;
// Getters and setters
}
在上述代碼中,我們使用了@Document
注解定義了Elasticsearch中的索引名和文檔類(lèi)型。
5. 創(chuàng)建Repository接口
使用Spring Data Elasticsearch提供的ElasticsearchRepository
接口來(lái)定義對(duì)Elasticsearch的操作。
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
public interface ArticleRepository extends ElasticsearchRepository<Article, String> {
List<Article> findByTitle(String title);
List<Article> findByContent(String content);
}
通過(guò)繼承ElasticsearchRepository
,我們可以直接使用Spring Data提供的方法進(jìn)行數(shù)據(jù)的CRUD操作。
6. 編寫(xiě)Service
創(chuàng)建一個(gè)Service類(lèi),封裝業(yè)務(wù)邏輯,調(diào)用Repository進(jìn)行數(shù)據(jù)操作。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ArticleService {
private final ArticleRepository articleRepository;
@Autowired
public ArticleService(ArticleRepository articleRepository) {
this.articleRepository = articleRepository;
}
public List<Article> searchByTitle(String title) {
return articleRepository.findByTitle(title);
}
public List<Article> searchByContent(String content) {
return articleRepository.findByContent(content);
}
}
7. 使用示例
在Controller層使用我們創(chuàng)建的Service進(jìn)行數(shù)據(jù)的操作。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/articles")
public class ArticleController {
private final ArticleService articleService;
@Autowired
public ArticleController(ArticleService articleService) {
this.articleService = articleService;
}
@GetMapping("/searchByTitle")
public List<Article> searchByTitle(@RequestParam String title) {
return articleService.searchByTitle(title);
}
@GetMapping("/searchByContent")
public List<Article> searchByContent(@RequestParam String content) {
return articleService.searchByContent(content);
}
}
8. 運(yùn)行和測(cè)試
通過(guò)訪問(wèn)Controller提供的接口,我們可以進(jìn)行數(shù)據(jù)的索引、搜索等操作:
curl -X GET http://localhost:8080/articles/searchByTitle?title=Elasticsearch
二、 Elasticsearch 保存實(shí)體類(lèi)在表中的映射
Elasticsearch 與傳統(tǒng)的關(guān)系型數(shù)據(jù)庫(kù)不同,它采用的是文檔型數(shù)據(jù)庫(kù)的思想,數(shù)據(jù)以文檔的形式存儲(chǔ)。在 Elasticsearch 中,我們不再創(chuàng)建表,而是創(chuàng)建索引(Index),每個(gè)索引包含多個(gè)文檔(Document),每個(gè)文檔包含多個(gè)字段。
以下是 Elasticsearch 中建立索引和實(shí)體類(lèi)的映射的基本步驟:
1. 創(chuàng)建索引
在 Elasticsearch 中,索引是存儲(chǔ)相關(guān)文檔的地方。我們可以通過(guò) RESTful API 或者在 Spring Boot 項(xiàng)目中使用 Elasticsearch 的 Java 客戶(hù)端創(chuàng)建索引。以下是通過(guò) RESTful API 創(chuàng)建索引的示例:
PUT /my_index
上述命令創(chuàng)建了一個(gè)名為 my_index
的索引。在 Spring Boot 項(xiàng)目中,可以使用 IndexOperations
類(lèi)來(lái)創(chuàng)建索引,示例如下:
@Autowired
private ElasticsearchRestTemplate elasticsearchRestTemplate;
public void createIndex() {
elasticsearchRestTemplate.indexOps(MyEntity.class).create();
}
2. 定義實(shí)體類(lèi)
實(shí)體類(lèi)用于映射 Elasticsearch 中的文檔結(jié)構(gòu)。每個(gè)實(shí)體類(lèi)的實(shí)例對(duì)應(yīng)于一個(gè)文檔。在實(shí)體類(lèi)中,我們可以使用注解來(lái)定義字段的映射關(guān)系。以下是一個(gè)簡(jiǎn)單的實(shí)體類(lèi)示例:
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
@Document(indexName = "my_index", type = "my_entity")
public class MyEntity {
@Id
private String id;
@Field(type = FieldType.Text)
private String name;
@Field(type = FieldType.Keyword)
private String category;
// 其他字段和方法
}
上述示例中,通過(guò) @Document
注解定義了索引名為 my_index
,類(lèi)型名為 my_entity
。通過(guò) @Field
注解定義了字段的映射關(guān)系,例如 name
字段映射為 Text 類(lèi)型,category
字段映射為 Keyword 類(lèi)型。
3. 保存文檔
保存文檔是將實(shí)體類(lèi)的實(shí)例存儲(chǔ)到 Elasticsearch 中的過(guò)程。在 Spring Boot 項(xiàng)目中,可以使用 ElasticsearchTemplate
或者 ElasticsearchRepository
進(jìn)行文檔的保存。以下是使用 ElasticsearchRepository
的示例:
public interface MyEntityRepository extends ElasticsearchRepository<MyEntity, String> {
}
在上述示例中,MyEntityRepository
繼承了 ElasticsearchRepository
接口,泛型參數(shù)為實(shí)體類(lèi)類(lèi)型和 ID 類(lèi)型。Spring Data Elasticsearch 將根據(jù)實(shí)體類(lèi)的結(jié)構(gòu)自動(dòng)生成相應(yīng)的 CRUD 方法。通過(guò)調(diào)用 save
方法,可以保存實(shí)體類(lèi)的實(shí)例到 Elasticsearch 中。
@Autowired
private MyEntityRepository myEntityRepository;
public void saveDocument() {
MyEntity entity = new MyEntity();
entity.setName("Document Name");
entity.setCategory("Document Category");
myEntityRepository.save(entity);
}
上述代碼示例中,我們創(chuàng)建了一個(gè) MyEntity
類(lèi)的實(shí)例,并使用 save
方法將其保存到 Elasticsearch 中。
提高篇
一 實(shí)際案例:使用Spring Boot集成Elasticsearch的深度提高篇
在這個(gè)實(shí)際案例中,我們將以一個(gè)圖書(shū)搜索引擎為例,詳細(xì)講解如何使用Spring Boot集成Elasticsearch進(jìn)行深度提高,包括性能調(diào)優(yōu)、復(fù)雜查詢(xún)、分頁(yè)和聚合等方面。
1. 準(zhǔn)備工作
首先,確保你已經(jīng)搭建好Elasticsearch集群,并且在Spring Boot項(xiàng)目中添加了Elasticsearch的依賴(lài)。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
2. 配置文件
在application.properties
或application.yml
中配置Elasticsearch的連接信息:
spring.data.elasticsearch.cluster-nodes=localhost:9200
3. 實(shí)體類(lèi)
創(chuàng)建一個(gè)圖書(shū)實(shí)體類(lèi),用于映射Elasticsearch中的文檔。
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
@Document(indexName = "books", type = "book")
public class Book {
@Id
private String id;
private String title;
private String author;
private String genre;
// Getters and setters
}
4. Repository 接口
創(chuàng)建一個(gè)Elasticsearch Repository接口,繼承自ElasticsearchRepository
,用于對(duì)圖書(shū)文檔進(jìn)行操作。
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import java.util.List;
public interface BookRepository extends ElasticsearchRepository<Book, String> {
List<Book> findByTitleLike(String title);
List<Book> findByAuthorAndGenre(String author, String genre);
// 更多自定義查詢(xún)方法
}
5. 服務(wù)類(lèi)
創(chuàng)建一個(gè)服務(wù)類(lèi),用于處理業(yè)務(wù)邏輯,調(diào)用Repository進(jìn)行圖書(shū)文檔的操作。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class BookService {
private final BookRepository bookRepository;
@Autowired
public BookService(BookRepository bookRepository) {
this.bookRepository = bookRepository;
}
public List<Book> searchBooksByTitle(String title) {
return bookRepository.findByTitleLike(title);
}
public List<Book> searchBooksByAuthorAndGenre(String author, String genre) {
return bookRepository.findByAuthorAndGenre(author, genre);
}
// 更多業(yè)務(wù)邏輯和自定義查詢(xún)方法
}
6. 性能調(diào)優(yōu)
6.1 配置文件調(diào)優(yōu)
在application.properties
中配置Elasticsearch的連接池大小和相關(guān)參數(shù):
spring.data.elasticsearch.properties.http.max_content_length=100mb
spring.data.elasticsearch.properties.http.max_initial_line_length=100kb
spring.data.elasticsearch.properties.http.max_header_size=3kb
spring.data.elasticsearch.properties.transport.tcp.compress=true
spring.data.elasticsearch.properties.transport.tcp.connect_timeout=5s
spring.data.elasticsearch.properties.transport.tcp.keep_alive=true
spring.data.elasticsearch.properties.transport.tcp.no_delay=true
spring.data.elasticsearch.properties.transport.tcp.socket_timeout=5s
6.2 JVM調(diào)優(yōu)
修改jvm.options
文件,調(diào)整堆內(nèi)存大?。?/p>
-Xms2g
-Xmx2g
7. 復(fù)雜查詢(xún)
通過(guò)服務(wù)類(lèi)提供的自定義查詢(xún)方法實(shí)現(xiàn)復(fù)雜查詢(xún),例如按標(biāo)題模糊查詢(xún)和按作者、類(lèi)別查詢(xún):
@RestController
@RequestMapping("/books")
public class BookController {
private final BookService bookService;
@Autowired
public BookController(BookService bookService) {
this.bookService = bookService;
}
@GetMapping("/searchByTitle")
public List<Book> searchByTitle(@RequestParam String title) {
return bookService.searchBooksByTitle(title);
}
@GetMapping("/searchByAuthorAndGenre")
public List<Book> searchByAuthorAndGenre(@RequestParam String author, @RequestParam String genre) {
return bookService.searchBooksByAuthorAndGenre(author, genre);
}
}
8. 分頁(yè)和聚合
在Controller中添加分頁(yè)和聚合的方法:
@GetMapping("/searchWithPagination")
public List<Book> searchWithPagination(@RequestParam String title, @RequestParam int page, @RequestParam int size) {
PageRequest pageRequest = PageRequest.of(page, size);
return bookService.searchBooksByTitleWithPagination(title, pageRequest);
}
@GetMapping("/aggregateByGenre")
public Map<String, Long> aggregateByGenre() {
return bookService.aggregate
BooksByGenre();
}
在服務(wù)類(lèi)中實(shí)現(xiàn)分頁(yè)和聚合的方法:
public List<Book> searchBooksByTitleWithPagination(String title, Pageable pageable) {
SearchHits<Book> searchHits = bookRepository.search(QueryBuilders.matchQuery("title", title), pageable);
return searchHits.stream().map(SearchHit::getContent).collect(Collectors.toList());
}
public Map<String, Long> aggregateBooksByGenre() {
TermsAggregationBuilder aggregation = AggregationBuilders.terms("genres").field("genre").size(10);
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder().aggregation(aggregation);
SearchHits<Book> searchHits = bookRepository.search(sourceBuilder.build());
return searchHits.getAggregations().asMap().entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, e -> ((ParsedLongTerms) e.getValue()).getBuckets().size()));
}
9. 運(yùn)行與測(cè)試
二 使用Spring Boot集成Elasticsearch的更多進(jìn)階特性
1. 文檔數(shù)據(jù)處理
在實(shí)際應(yīng)用中,對(duì)文檔數(shù)據(jù)的處理常常需要更多的靈活性。我們將學(xué)習(xí)如何在實(shí)體類(lèi)中使用注解進(jìn)行更高級(jí)的字段映射和設(shè)置:
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
@Document(indexName = "books", type = "book")
public class Book {
@Id
private String id;
@Field(type = FieldType.Text, analyzer = "standard", fielddata = true)
private String title;
@Field(type = FieldType.Keyword)
private String author;
@Field(type = FieldType.Keyword)
private String genre;
// 其他字段和方法
}
在上述例子中,我們使用了@Field
注解進(jìn)行更精細(xì)的字段類(lèi)型設(shè)置和分詞配置。
2. 腳本查詢(xún)
Elasticsearch允許使用腳本進(jìn)行查詢(xún),這在某些復(fù)雜的業(yè)務(wù)邏輯下非常有用。我們將學(xué)習(xí)如何使用腳本進(jìn)行查詢(xún):
@GetMapping("/searchWithScript")
public List<Book> searchWithScript(@RequestParam String script) {
NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.scriptQuery(new Script(script)))
.build();
return elasticsearchRestTemplate.search(searchQuery, Book.class).stream()
.map(SearchHit::getContent)
.collect(Collectors.toList());
}
在上述例子中,我們通過(guò)Script
對(duì)象構(gòu)建了一個(gè)腳本查詢(xún),并使用NativeSearchQuery
進(jìn)行執(zhí)行。
3. 性能優(yōu)化 - Bulk 操作
當(dāng)需要批量操作大量文檔時(shí),使用Bulk操作可以顯著提高性能。我們將學(xué)習(xí)如何使用Bulk操作:
public void bulkIndexBooks(List<Book> books) {
List<IndexQuery> indexQueries = books.stream()
.map(book -> new IndexQueryBuilder()
.withObject(book)
.build())
.collect(Collectors.toList());
elasticsearchRestTemplate.bulkIndex(indexQueries);
elasticsearchRestTemplate.refresh(Book.class);
}
在上述例子中,我們通過(guò)bulkIndex
方法批量索引圖書(shū),并使用refresh
方法刷新索引。
4. 高級(jí)用法 - Highlight
在搜索結(jié)果中高亮顯示關(guān)鍵字是提高用戶(hù)體驗(yàn)的一種方式。我們將學(xué)習(xí)如何在查詢(xún)中使用Highlight:
public List<Book> searchBooksWithHighlight(String keyword) {
QueryStringQueryBuilder query = QueryBuilders.queryStringQuery(keyword);
HighlightBuilder.Field highlightTitle = new HighlightBuilder.Field("title")
.preTags("<span style='background-color:yellow'>")
.postTags("</span>");
NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(query)
.withHighlightFields(highlightTitle)
.build();
SearchHits<Book> searchHits = elasticsearchRestTemplate.search(searchQuery, Book.class);
return searchHits.stream()
.map(searchHit -> {
Book book = searchHit.getContent();
Map<String, List<String>> highlightFields = searchHit.getHighlightFields();
if (highlightFields.containsKey("title")) {
book.setTitle(String.join(" ", highlightFields.get("title")));
}
return book;
})
.collect(Collectors.toList());
}
在上述例子中,我們通過(guò)HighlightBuilder
設(shè)置了對(duì)title
字段的高亮顯示,然后在查詢(xún)中使用了withHighlightFields
方法。
5. 進(jìn)階用法 - SearchTemplate
Elasticsearch提供了SearchTemplate功能,允許使用模板進(jìn)行更靈活的查詢(xún)。我們將學(xué)習(xí)如何使用SearchTemplate:
public List<Book> searchBooksWithTemplate(String genre) {
Map<String, Object> params = Collections.singletonMap("genre", genre);
String script = "{\"query\":{\"match\":{\"genre\":\"{{genre}}\"}}}";
SearchResponse response = elasticsearchRestTemplate.query(searchRequest -> {
searchRequest
.setScript(new Script(ScriptType.INLINE, "mustache", script, params))
.setIndices("books")
.setTypes("book");
}, SearchResponse.class);
return Arrays.stream(response.getHits().getHits())
.map(hit -> elasticsearchRestTemplate.getConverter().read(Book.class, hit))
.collect(Collectors.toList());
}
在上述例子中,我們通過(guò)SearchTemplate
使用了一個(gè)簡(jiǎn)單的Mustache模板進(jìn)行查詢(xún)。
高級(jí)使用篇
Elasticsearch常見(jiàn)的高級(jí)使用篇
在一部分中,我們將深入討論Elasticsearch的一些常見(jiàn)的高級(jí)使用技巧,包括聚合、地理空間搜索、模糊查詢(xún)、索引別名等。
1. 聚合(Aggregation)
聚合是Elasticsearch中一項(xiàng)強(qiáng)大的功能,它允許對(duì)數(shù)據(jù)集進(jìn)行復(fù)雜的數(shù)據(jù)分析和匯總。以下是一些常見(jiàn)的聚合類(lèi)型:
1.1 桶聚合(Bucket Aggregation)
桶聚合將文檔分配到不同的桶中,然后對(duì)每個(gè)桶進(jìn)行聚合計(jì)算。
GET /my_index/_search
{
"size": 0,
"aggs": {
"categories": {
"terms": {
"field": "category.keyword"
}
}
}
}
上述例子中,通過(guò)桶聚合統(tǒng)計(jì)了每個(gè)類(lèi)別的文檔數(shù)量。
1.2 指標(biāo)聚合(Metric Aggregation)
指標(biāo)聚合計(jì)算某個(gè)字段的統(tǒng)計(jì)指標(biāo),比如平均值、最大值、最小值等。
GET /my_index/_search
{
"size": 0,
"aggs": {
"average_price": {
"avg": {
"field": "price"
}
}
}
}
上述例子中,通過(guò)指標(biāo)聚合計(jì)算了字段"price"的平均值。
2. 地理空間搜索
Elasticsearch提供了強(qiáng)大的地理空間搜索功能,支持地理點(diǎn)、地理形狀等多種地理數(shù)據(jù)類(lèi)型。
2.1 地理點(diǎn)搜索
GET /my_geo_index/_search
{
"query": {
"geo_distance": {
"distance": "10km",
"location": {
"lat": 40,
"lon": -70
}
}
}
}
上述例子中,通過(guò)地理點(diǎn)搜索找到距離指定坐標(biāo)(緯度40,經(jīng)度-70)10公里范圍內(nèi)的文檔。
2.2 地理形狀搜索
GET /my_geo_shape_index/_search
{
"query": {
"geo_shape": {
"location": {
"shape": {
"type": "envelope",
"coordinates": [[-74.1,40.73], [-73.9,40.85]]
},
"relation": "within"
}
}
}
}
上述例子中,通過(guò)地理形狀搜索找到在指定矩形區(qū)域內(nèi)的文檔。
3. 模糊查詢(xún)
Elasticsearch支持多種模糊查詢(xún),包括通配符查詢(xún)、模糊查詢(xún)、近似查詢(xún)等。
3.1 通配符查詢(xún)
GET /my_index/_search
{
"query": {
"wildcard": {
"name": "el*"
}
}
}
上述例子中,通過(guò)通配符查詢(xún)找到名字以"el"開(kāi)頭的文檔。
3.2 模糊查詢(xún)
GET /my_index/_search
{
"query": {
"fuzzy": {
"name": {
"value": "elastic",
"fuzziness": "AUTO"
}
}
}
}
上述例子中,通過(guò)模糊查詢(xún)找到與"elastic"相似的文檔。
4. 索引別名
索引別名是一個(gè)指向一個(gè)或多個(gè)索引的虛擬索引名稱(chēng),它可以用于簡(jiǎn)化查詢(xún)、切換索引版本、重命名索引等操作。
POST /_aliases
{
"actions": [
{
"add": {
"index": "new_index",
"alias": "my_alias"
}
}
]
}
上述例子中,創(chuàng)建了一個(gè)別名"my_alias"指向索引"new_index"。
5. 深度分頁(yè)
當(dāng)需要深度分頁(yè)時(shí),常規(guī)的from
和size
可能會(huì)導(dǎo)致性能問(wèn)題。這時(shí)可以使用search_after
進(jìn)行優(yōu)化。
GET /my_index/_search
{
"size": 10,
"query": {
"match_all": {}
},
"sort": [
{
"date": {
"order": "asc"
}
}
]
}
上述例子中,通過(guò)search_after
分頁(yè)查詢(xún),可以避免使用from
和size
導(dǎo)致的性能問(wèn)題。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-805008.html
結(jié)語(yǔ)
通過(guò)這篇高級(jí)使用篇博客,我們?cè)敿?xì)介紹了如何使用Spring Boot集成Elasticsearch,包括添加依賴(lài)、配置連接、創(chuàng)建實(shí)體類(lèi)和Repository接口、編寫(xiě)Service以及使用示例。我們深入了解了Elasticsearch的一些高級(jí)功能,包括聚合、地理空間搜索、模糊查詢(xún)、索引別名等。這些技巧將有助于你更靈活、高效地處理各種復(fù)雜的數(shù)據(jù)查詢(xún)和分析任務(wù)。希望這些內(nèi)容對(duì)你在實(shí)際項(xiàng)目中的應(yīng)用有所幫助。感謝閱讀!文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-805008.html
到了這里,關(guān)于使用Spring Boot集成中間件:Elasticsearch基礎(chǔ)->提高篇的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!