【spring】springboot使用jpa集成elasticsearch7.0
背景
springboot的data jpa是支持elasticsearch的。在springboot2.3之前,连接es的端口是9300,但实测下来各种版本之间对应关系很复杂,springboot2.3【注:具体哪个版本没有实测】之后可以配置rest接口方式连接es,理论上可以适配所有版本的es了
过程
依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>2.3.1.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency>
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency>
yml配置:
spring:
elasticsearch:
rest:
uris: localhost:9200
接口编写:
package com.jsfactory.back.api.search.repository; import com.jsfactory.back.api.search.entity.WorkshopSearch; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import java.util.List; public interface WorkshopRepository extends ElasticsearchRepository<WorkshopSearch,String> { List<WorkshopSearch> findByDescription(String desc); List<WorkshopSearch> findByTownNameOrNameOrDistrictNameOrDescriptionOrCustomerNameOrCityNameOrTags(String townName, String name, String districtName, String description, String customerName, String cityName, String tag); void deleteByWorkshopId(Long workshopId); }
测试:
@Autowired private WorkshopRepository workshopRepository; @Test @Ignore public void searchEsTest() { String value = "风景"; List<WorkshopSearch> workshopSearches = workshopRepository.findByTownNameOrNameOrDistrictNameOrDescriptionOrCustomerNameOrCityNameOrTags(value, value, value, value, value, value, value); Assert.assertEquals(10, workshopSearches.size()); }
以上