springboot 整合elasticsearch 的两种实现方式
先引入es的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
<version>2.3.0.RELEASE</version>
</dependency>
java 操作es 的两种方式
一种是方便用于操作对象的,需要一个接口继承ElasticsearchRepository<bean,String>
另一种主要用于高亮查询,灵活度更高,但操作对象需要格式转换,需要一个类继承AbstractElasticsearchConfiguration类,重写elasticsearchClient方法。
继承ElasticsearchRepository<bean,String>
public interface NewsRepository extends ElasticsearchRepository<News,Integer> {
}
News 为实体类,Integer 为id类型
继承AbstractElasticsearchConfiguration
@Configuration
public class RestClientConfig extends AbstractElasticsearchConfiguration {
@Override
@Bean
public RestHighLevelClient elasticsearchClient() {
ClientConfiguration build = ClientConfiguration.builder()
.connectedTo("localhost:9200")
.build();
return RestClients.create(build).rest();
}
}
代码中只需要通过@Autowired注入即可
ElasticsearchRepository示例
@Autowired
private StuRepository stuRepository;
// 新增和修改 有id就是修改
@Test
public void testSave(){
Stu stu = new Stu();
stu.setId(UUID.randomUUID().toString());
stu.setName("吴离");
stu.setAge("24");
stu.setBir(new Date());
stu.setContent("springboot 整合 elasticsearch");
Stu save = stuRepository.save(stu);
System.out.println(save);
}
// 根据id删除
@Test
public void testDelete(){
stuRepository.deleteById("c3cc7b71-8df2-4c25-a8cc-fcfe0c74348c");
}
// 删除所有
@Test
public void testDeleteAll(){
stuRepository.deleteAll();
}
// 检索一条文档
@Test
public void testSearch(){
Optional<Stu> byId = stuRepository.findById("59aebdad-3a5f-4bec-b95b-d20043d0e59d");
System.out.println(byId.get());
}
继承AbstractElasticsearchConfiguration
public CommonResult findOrEs(String name) throws IOException {
SearchRequest searchRequest = new SearchRequest("news");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// 对输入的关键字进行多字段查询
searchSourceBuilder.query(QueryBuilders.multiMatchQuery(name,"content","title"));
// 设置高亮查询
searchSourceBuilder.highlighter(new HighlightBuilder().field("*").requireFieldMatch(false)
.preTags("<span style='color:red'>")
.postTags("</span>"));
// 设置查询条件
SearchRequest source = searchRequest.source(searchSourceBuilder);
// 执行查询
SearchResponse searchResponse = restHighLevelClient.search(source, RequestOptions.DEFAULT);
List<News> list = new ArrayList<>();
// 封装数据
if (searchResponse.getHits().getTotalHits().value>0){
SearchHit[] hits = searchResponse.getHits().getHits();
for (SearchHit hit : hits){
// 原始数据
Map<String, Object> sourceAsMap = hit.getSourceAsMap();
Map<String, HighlightField> highlightFields = hit.getHighlightFields();
News news = new News();
// id
news.setId(Integer.parseInt(hit.getId()));
// title
news.setTitle(sourceAsMap.get("title").toString());
if (highlightFields.containsKey("title")){
news.setTitle(highlightFields.get("title").fragments()[0].toString());
}
// content
news.setContent(sourceAsMap.get("content").toString());
if (highlightFields.containsKey("content")){
news.setContent(highlightFields.get("content").fragments()[0].toString());
}
// type
news.setType(sourceAsMap.get("type").toString());
// time
news.setTime(sourceAsMap.get("time").toString());
// status
news.setStatus(Integer.parseInt(sourceAsMap.get("status").toString()));
list.add(news);
}
}
return CommonResult.success(list);
}
实体类示例
@Document(indexName = "news")
public class News {
@Id
@ApiModelProperty(value = "新闻id")
private Integer id;
@Field(type = FieldType.Text,analyzer = "ik_max_word")
@ApiModelProperty(value = "新闻标题")
private String title;
@Field(type = FieldType.Keyword)
@ApiModelProperty(value = "新闻类型")
private String type;
@Field(type = FieldType.Text,analyzer = "ik_max_word")
@ApiModelProperty(value = "新闻内容")
private String content;
// @Field(type = FieldType.Date,format = DateFormat.date_time)
@ApiModelProperty(value = "新闻时间")
private String time;
@Field(type = FieldType.Keyword)
@ApiModelProperty(value = "新闻状态")
private Integer status;
@Field(type = FieldType.Keyword)
@ApiModelProperty(value = "新闻图片")
private String img;
}