SpringDataElasticsearch在SpringBoot项目中的简单使用
1.引入Maven
在 Maven 中添加 Spring Data Elasticsearch 依赖:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
2.配置Elasticsearch连接
配置 Elasticsearch 服务器地址和端口
spring:elasticsearch:uris: http://xx.xx.xx.xx:9200
3.创建JavaBean
创建一个代表 Elasticsearch 文档的 Java 类,并使用 Spring Data Elasticsearch 注解进行标注。
@Data
@Document(indexName = "blog")
public class Blog{@Idprivate Long blogId;@Field(type = FieldType.Text)private String title;@Field(type = FieldType.Text)private String content;@Field(type = FieldType.Text)private String author;//博客所属分类。@Field(type = FieldType.Keyword)private String category;//0: 未发布(草稿) 1:已发布 2:已删除@Field(type = FieldType.Integer)private int status;//序列号,用于给外部展示的id@Field(type = FieldType.Keyword)private String serialNum;@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS")@Field(type= FieldType.Date, format= DateFormat.date_hour_minute_second_fraction, pattern="yyyy-MM-dd HH:mm:ss.SSS")private Date createTime;@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS")@Field(type=FieldType.Date, format=DateFormat.date_hour_minute_second_fraction, pattern="yyyy-MM-dd HH:mm:ss.SSS")private Date updateTime;
}
4.创建 Repository 接口
创建一个继承自 ElasticsearchRepository 的接口,用于执行 CRUD 操作。例如,创建 BlogRepository:
public interface BlogRepository extends ElasticsearchRepository<Blog,String> {List<Blog> findByTitleIn(List<String> title);Page<Blog> findByTitleContaining(String title, Pageable pageable);
}
5. 使用 Repository 进行操作
在 Service 或 Controller 中注入 BlogRepository 并使用它执行查询、保存、删除等操作:
@Service
public class EsServiceImpl implements EsService {@Autowiredprivate BlogRepository blogRepository;@Overridepublic void getDetails(String title) throws Exception {List<String> list = new ArrayList<>();list.add(title);List<Blog> blog = blogRepository.findByTitleIn(list);}
}
6. 自定义查询方法
如果需要执行更复杂的查询,可以使用 @Query 注解在 Repository 方法上定义原生 Elasticsearch 查询 DSL:
@Repository
public interface BlogRepository extends ElasticsearchRepository<Blog,String> {List<Blog> findByTitleIn(List<String> title);@Query("{\"bool\":{\"must\":[{\"match\":{\"title\":\"?0\"}}]}}")List<Blog> findByTitle(String title);
}