spring-boot.version : 2.5.15
1.引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
2.配置application.properties
spring.elasticsearch.rest.uris=http://127.0.0.1:9200
spring.data.elasticsearch.repositories.enabled=true
spring.data.elasticsearch.client.reactive.endpoints=127.0.0.1:9200
3.启动类添加注解:@EnableElasticsearchRepositories(basePackages = {"com.xxx.dao"})
4.编写文档对象实体类
@Data
@Document(indexName = "products", createIndex = true)
public class Product implements Serializable {
private static final long serialVersionUID = -7509473661142683567L;
@Id
private Long id;
@Field(type = FieldType.Keyword)
private String title;
@Field(type = FieldType.Float)
private Double price;
@Field(type = FieldType.Text)
private String desc;
}
5.编写 Repository 接口 - @EnableElasticsearchRepositories 注解要去扫描的接口
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;
import com.sky.biz.doc.Product;
@Repository -- 该注解一般可以省略
public interface ProductRepository extends ElasticsearchRepository<Product, Long> {
Page<Product> findByTitle(String word, Pageable pageable);
}
6.CRUD - 业务操作
@Autowired
private ProductRepository productRepository;
@Test
public void testSave() {
Product product = new Product();
product.setId(1L);
product.setTitle("Java虚拟机调优实战");
product.setPrice(36.00);
product.setDesc("图灵奖获奖图书");
Product result = productRepository.save(product);
System.out.println("保存成功:" + JSONObject.toJSONString(result));
}
@Test
public void testQuery() {
Optional<Product> productOptional = productRepository.findById(1L);
if(productOptional.isPresent()) {
Product product = productOptional.get();
System.out.println("ES查询结果:" + JSONObject.toJSONString(product));
}
}
7.重要说明:
spring-data-elasticsearch 一般主要用于简单对象的CRUD操作,
对于业务比较复杂的操作建议还是需要使用其他的java client来补充操作了,比如HighLevelRestClient,
不过大家要了解的是es官方已经不推荐使用Rest Client和Transport Client了,并且会在es8.x时废除。
从7.15版本开始更加推荐使用Java Client,但是因为学习成本、使用习惯以及很多公司仍然在使用6.x或更早版本的es,
所以在es7.x版本或更早,HighLevelRestClient 还是不错的选择