集成依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.5</version>
<relativePath/>
</parent>
<dependencies>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
</dependencies>
配置参数
spring:
elasticsearch:
uris: http://XXXX:9200
username: elastic
password: 'XXXX'
定义Entity
@Data
@Document(indexName = "resource_index")
public class ResourceEntity {
@Id
private String id;
@Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_max_word")
private String title;
public ResourceEntity() {
}
public ResourceEntity(String id, String title) {
this.id = id;
this.title = title;
}
}
定义Repository
public interface ResourceEntityRepository extends ElasticsearchRepository<ResourceEntity, String> {
@Highlight(
fields = {@HighlightField(name = "title")},
parameters = @HighlightParameters(preTags = {"<span style='color:red'>"}, postTags = {"</span>"}, numberOfFragments = 0)
)
List<SearchHit<ResourceEntity>> findByTitle(String title);
}
测试
@Test
public void findByTitleTest(){
List<SearchHit<ResourceEntity>> testEntityList = repository.findByTitle("文档");
testEntityList.forEach(testEntity -> {
log.info("testEntity:{}",testEntity);
});
}