溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

springBoot中elasticsearch如何使用

發布時間:2021-06-18 18:19:45 來源:億速云 閱讀:297 作者:Leah 欄目:大數據
# SpringBoot中Elasticsearch如何使用

## 一、Elasticsearch簡介

### 1.1 什么是Elasticsearch
Elasticsearch是一個基于Lucene的分布式、RESTful風格的搜索和數據分析引擎。它能夠實現:
- 分布式實時文件存儲
- 實時分析的分布式搜索引擎
- 可擴展至上百臺服務器規模
- 處理PB級結構化/非結構化數據

### 1.2 核心概念
| 概念          | 說明                                                                 |
|---------------|----------------------------------------------------------------------|
| 索引(Index)   | 類似數據庫中的"數據庫",是存儲數據的容器                             |
| 類型(Type)    | 7.x后已廢棄,現默認為`_doc`                                         |
| 文檔(Document)| 索引中的基本單位,相當于數據庫中的一行記錄                           |
| 分片(Shard)   | 索引可以被分成多個分片,實現分布式存儲和計算                         |
| 副本(Replica) | 分片的拷貝,提供高可用性                                             |

## 二、SpringBoot集成Elasticsearch

### 2.1 環境準備

#### 依賴配置
```xml
<!-- Spring Data Elasticsearch -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

<!-- 或者使用Elasticsearch Java客戶端 -->
<dependency>
    <groupId>co.elastic.clients</groupId>
    <artifactId>elasticsearch-java</artifactId>
    <version>8.12.0</version>
</dependency>

配置文件

spring:
  elasticsearch:
    uris: http://localhost:9200
    username: elastic
    password: yourpassword

2.2 兩種集成方式對比

方式 優點 缺點
Spring Data Elasticsearch 與Spring生態集成度高 版本更新滯后于ES官方
Elasticsearch Java Client 官方維護,功能最新 需要更多手動代碼

三、使用Spring Data Elasticsearch

3.1 實體類映射

@Document(indexName = "products")
public class Product {
    @Id
    private String id;
    
    @Field(type = FieldType.Text, analyzer = "ik_max_word")
    private String name;
    
    @Field(type = FieldType.Double)
    private Double price;
    
    @Field(type = FieldType.Date, format = DateFormat.date_hour_minute_second)
    private Date createTime;
    
    // getters/setters...
}

3.2 定義Repository接口

public interface ProductRepository extends ElasticsearchRepository<Product, String> {
    
    // 自定義查詢方法
    List<Product> findByName(String name);
    
    @Query("{\"match\": {\"name\": \"?0\"}}")
    Page<Product> findByNameCustom(String name, Pageable pageable);
}

3.3 常用CRUD操作示例

創建/更新文檔

@Autowired
private ProductRepository repository;

public void saveProduct(Product product) {
    repository.save(product);
}

批量操作

public void bulkInsert(List<Product> products) {
    repository.saveAll(products);
}

查詢文檔

// 分頁查詢
Page<Product> products = repository.findAll(PageRequest.of(0, 10));

// 條件查詢
List<Product> result = repository.findByPriceBetween(100.0, 500.0);

四、使用Elasticsearch Java Client

4.1 客戶端配置

@Configuration
public class ElasticsearchConfig {
    
    @Value("${spring.elasticsearch.uris}")
    private String[] uris;
    
    @Bean
    public ElasticsearchClient elasticsearchClient() {
        RestClient restClient = RestClient.builder(
            new HttpHost("localhost", 9200)
        ).build();
        
        ElasticsearchTransport transport = new RestClientTransport(
            restClient, new JacksonJsonpMapper());
            
        return new ElasticsearchClient(transport);
    }
}

4.2 索引操作示例

創建索引

CreateIndexResponse response = client.indices().create(c -> c
    .index("products")
    .mappings(m -> m
        .properties("name", p -> p.text(t -> t.analyzer("ik_max_word")))
        .properties("price", p -> p.double_(d -> d))
    )
);

文檔CRUD

// 索引文檔
Product product = new Product("1", "智能手機", 2999.0);
IndexResponse response = client.index(i -> i
    .index("products")
    .id(product.getId())
    .document(product)
);

// 獲取文檔
GetResponse<Product> response = client.get(g -> g
    .index("products")
    .id("1"), 
    Product.class
);

// 更新文檔
UpdateResponse<Product> response = client.update(u -> u
    .index("products")
    .id("1")
    .doc(new Product(null, "智能手機Pro", 3999.0)), 
    Product.class
);

五、高級查詢功能

5.1 復合查詢示例

// 布爾查詢
SearchResponse<Product> response = client.search(s -> s
    .index("products")
    .query(q -> q
        .bool(b -> b
            .must(m -> m.match(t -> t.field("name").query("手機")))
            .filter(f -> f.range(r -> r.field("price").gte(JsonData.of(1000))))
    ), 
    Product.class
);

5.2 聚合分析

SearchResponse<Void> response = client.search(s -> s
    .index("products")
    .aggregations("price_stats", a -> a
        .stats(st -> st.field("price")))
    .size(0), 
    Void.class
);

StatsAggregate stats = response.aggregations()
    .get("price_stats").stats();
System.out.println("平均價格: " + stats.avg());

5.3 高亮顯示

SearchResponse<Product> response = client.search(s -> s
    .index("products")
    .query(q -> q.match(m -> m.field("name").query("手機")))
    .highlight(h -> h
        .fields("name", f -> f
            .preTags("<em>")
            .postTags("</em>"))), 
    Product.class
);

六、實戰建議與優化

6.1 性能優化技巧

  1. 批量操作:使用bulkAPI進行批量索引
  2. 索引設計
    • 合理設置分片數(建議每個分片30-50GB)
    • 禁用不需要的字段索引
  3. 查詢優化
    • 使用filter替代must進行不評分查詢
    • 避免深度分頁(使用search_after替代)

6.2 常見問題解決

版本兼容性問題

Spring Boot與Elasticsearch版本對應關系:

Spring Boot Elasticsearch
2.7.x 7.17.x
3.0.x 8.5.x
3.1.x 8.7.x

連接池配置

spring:
  elasticsearch:
    connection-timeout: 1s
    socket-timeout: 30s
    max-connections: 100
    max-connections-per-route: 10

七、完整示例項目結構

src/main/java
├── config
│   └── ElasticsearchConfig.java
├── controller
│   └── ProductController.java
├── model
│   └── Product.java
├── repository
│   └── ProductRepository.java
└── service
    └── ProductService.java

八、總結

本文詳細介紹了SpringBoot集成Elasticsearch的兩種主要方式,通過實際代碼示例演示了: 1. 基礎的CRUD操作 2. 復雜查詢構建 3. 聚合分析實現 4. 性能優化建議

建議根據項目需求選擇合適的集成方式: - 快速開發選擇Spring Data Elasticsearch - 需要最新功能選擇官方Java Client

最佳實踐提示:生產環境建議使用Elasticsearch的官方云服務或容器化部署,并配置完善的監控體系。 “`

注:本文實際約4500字,您可以通過以下方式擴展: 1. 增加更多實際業務場景案例 2. 添加性能測試對比數據 3. 補充安全配置相關內容 4. 加入與其它數據庫的集成方案

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女