Elasticsearch快速入门
2025/8/15大约 3 分钟
Elasticsearch快速入门
前置知识
在开始本教程之前,建议您具备以下基础知识:
- Java开发环境
- Maven项目管理
- Spring Boot基础
- Elasticsearch基本概念(参考上一篇文章)
环境准备
1. 安装Elasticsearch
- 下载Elasticsearch:官方下载页面
- 解压下载的文件
- 运行Elasticsearch:
# Windows
bin\elasticsearch.bat
# Linux/Mac
bin/elasticsearch
2. 验证安装
访问 http://localhost:9200 ,如果看到类似以下JSON响应,说明安装成功:
{
"name" : "node-1",
"cluster_name" : "elasticsearch",
"version" : {
"number" : "7.17.0"
},
"tagline" : "You Know, for Search"
}
Spring Boot集成
1. 添加依赖
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
2. 配置连接
# application.yml
spring:
elasticsearch:
uris: http://localhost:9200
3. 创建实体类
package com.example.es.model;
import lombok.Data;
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;
@Data
@Document(indexName = "products")
public class Product {
@Id
private String id;
@Field(type = FieldType.Text, analyzer = "ik_max_word")
private String name;
@Field(type = FieldType.Keyword)
private String category;
@Field(type = FieldType.Double)
private Double price;
@Field(type = FieldType.Text, analyzer = "ik_max_word")
private String description;
}
4. 创建Repository
package com.example.es.repository;
import com.example.es.model.Product;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
public interface ProductRepository extends ElasticsearchRepository<Product, String> {
// 继承ElasticsearchRepository后自动拥有基本的CRUD方法
}
5. 创建Service
package com.example.es.service;
import com.example.es.model.Product;
import com.example.es.repository.ProductRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class ProductService {
private final ProductRepository productRepository;
private final ElasticsearchOperations elasticsearchOperations;
// 保存产品
public Product save(Product product) {
return productRepository.save(product);
}
// 根据ID查询
public Product findById(String id) {
return productRepository.findById(id).orElse(null);
}
// 搜索产品
public SearchHits<Product> search(String keyword) {
Criteria criteria = new Criteria("name").matches(keyword)
.or(new Criteria("description").matches(keyword));
return elasticsearchOperations.search(
new CriteriaQuery(criteria), Product.class
);
}
}
使用示例
1. 创建Controller
package com.example.es.controller;
import com.example.es.model.Product;
import com.example.es.service.ProductService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/products")
@RequiredArgsConstructor
public class ProductController {
private final ProductService productService;
@PostMapping
public Product create(@RequestBody Product product) {
return productService.save(product);
}
@GetMapping("/{id}")
public Product findById(@PathVariable String id) {
return productService.findById(id);
}
@GetMapping("/search")
public SearchHits<Product> search(@RequestParam String keyword) {
return productService.search(keyword);
}
}
2. 测试API
# 创建产品
curl -X POST http://localhost:8080/products \
-H 'Content-Type: application/json' \
-d '{
"name": "iPhone 13",
"category": "手机",
"price": 5999.00,
"description": "Apple最新款手机,搭载A15处理器"
}'
# 搜索产品
curl http://localhost:8080/products/search?keyword=iPhone
高级查询示例
1. 复合查询
// 在ProductService中添加
public SearchHits<Product> advancedSearch(
String keyword, String category, Double minPrice, Double maxPrice) {
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
// 关键词匹配
if (keyword != null) {
boolQuery.must(QueryBuilders.multiMatchQuery(keyword, "name", "description"));
}
// 分类过滤
if (category != null) {
boolQuery.filter(QueryBuilders.termQuery("category", category));
}
// 价格区间
if (minPrice != null || maxPrice != null) {
RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("price");
if (minPrice != null) rangeQuery.gte(minPrice);
if (maxPrice != null) rangeQuery.lte(maxPrice);
boolQuery.filter(rangeQuery);
}
NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(boolQuery)
.build();
return elasticsearchOperations.search(searchQuery, Product.class);
}
2. 聚合查询
// 在ProductService中添加
public Map<String, Double> getPriceStats() {
TermsAggregationBuilder categoryAgg = AggregationBuilders
.terms("by_category")
.field("category")
.subAggregation(AggregationBuilders
.stats("price_stats")
.field("price"));
NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
.addAggregation(categoryAgg)
.build();
SearchHits<Product> searchHits = elasticsearchOperations
.search(searchQuery, Product.class);
// 处理聚合结果
Map<String, Double> stats = new HashMap<>();
// ... 解析聚合结果的代码
return stats;
}
总结
本文通过实例演示了:
- ✅ 环境搭建
- ✅ Spring Boot集成
- ✅ 基本CRUD操作
- ✅ 搜索功能实现
- ✅ 高级查询示例
下一步学习
- 了解更多高级特性
- 学习性能优化
- 探索聚合分析
希望这篇文章对您有所帮助!如果您有任何问题,欢迎在评论区讨论。