SpringBoot整合SpringDataElasticsearch(ES7.x),内附完整代码
前⾔
本⽂讲述了SpringBoot整合Spring Data Elasticsearch的详细过程,主要使⽤了ElasticsearchRestTemplate、ElasticsearchRepository等类来实现Index、Document CRUD操作的Java Api。
在开始之前,我们⾸先需要选择Es对应版本的jar包,本⽂所使⽤的Es版本为7.9.3,查看spring官⽹可知,对应的springboot版本为2.4.x。
整合
创建⼀个maven项⽬,就可以操作起来了。
配置
引⼊以下jar包:
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.0</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.71</version>
</dependency>
</dependencies>
application.properties
spring.abled = true
st.uris=localhost:9200
ElasticsearchRestTemplate配置
@Configuration
public class ElasticsearchRestTemplateConfig extends AbstractElasticsearchConfiguration {
@Value("${st.uris}")
private String uris;
@Override
public RestHighLevelClient elasticsearchClient() {
ClientConfiguration configuration = ClientConfiguration.builder()
.connectedTo(uris)
.build();
ate(configuration).rest();
}
}
代码
Model
Model类似于数据库实体,不过此处所映射的是Index和Document的字段。注解含义可查看。
@Document(indexName = "order", shards = 1, replicas = 1)
public class Order implements Serializable {
@Id
private Integer id;
springboot中文@Field(type = FieldType.Keyword)
private Long orderNo;
@Field(type = FieldType.Integer)
private Integer orderType;
@Field(type = FieldType.Long)
private Long orderAmount;
@Field(type = FieldType.Text, analyzer = "ik_smart", searchAnalyzer = "ik_max_word")
private String orderDesc;
@Field(type = FieldType.Keyword, analyzer = "ik_smart", searchAnalyzer = "ik_max_word")
private String username;
@Field(type = FieldType.Keyword, analyzer = "ik_smart", searchAnalyzer = "ik_max_word")
private String userPhone;
private Map<String, List<String>> highlights;
}
Repository
ElasticsearchRepository接⼝封装了Document的CRUD操作,我们直接定义接⼝继承它即可。
public interface OrderRepository extends ElasticsearchRepository<Order, Integer> {
}
Service
public interface OrderService {
void saveAll(List<Order> orders);
Order findById(Integer id);
void deleteById(Integer id);
void updateById(Order order);
PageResponse<Order> findList(Order order, Integer pageIndex, Integer pageSize);
PageResponse<Order> findAll(Integer pageIndex, Integer pageSize);
PageResponse<Order> findHighlight(Order order, Integer pageIndex, Integer pageSize);
}
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
@Autowired
OrderRepository orderRepository;
@Autowired
ElasticsearchRestTemplate elasticsearchRestTemplate;
@Override
public void saveAll(List<Order> orders) {
orderRepository.saveAll(orders);
}
@Override
public void deleteById(Integer id) {
orderRepository.deleteById(id);
}
@Override
public void updateById(Order order) {
orderRepository.save(order);
}
@Override
public PageResponse<Order> findList(Order order, Integer pageIndex, Integer pageSize) {
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria()
.and(new Criteria("orderDesc").OrderDesc()))
.and(new Criteria("orderNo").OrderNo())))
.setPageable(PageRequest.of(pageIndex, pageSize));
SearchHits<Order> searchHits = elasticsearchRestTemplate.search(criteriaQuery, Order.class); List<Order> result = ().map(SearchHit::getContent).List());
PageResponse<Order> pageResponse = new PageResponse<Order>();
pageResponse.TotalHits());
pageResponse.setResult(result);
return pageResponse;
}
@Override
public PageResponse<Order> findAll(Integer pageIndex, Integer pageSize) {
Page<Order> page = orderRepository.findAll(PageRequest.of(pageIndex, pageSize));
PageResponse<Order> pageResponse = new PageResponse<Order>();
pageResponse.TotalElements());
pageResponse.Content());
return pageResponse;
}
@Override
public PageResponse<Order> findHighlight(Order order, Integer pageIndex, Integer pageSize) { if (order == null) {
PageResponse<Order> pageResponse = new PageResponse<Order>();
pageResponse.setTotal(0L);
pageResponse.setResult(new ArrayList<>());
return pageResponse;
}
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria()
.and(new Criteria("orderNo").OrderNo()))
.and(new Criteria("orderDesc").OrderDesc())))
.setPageable(PageRequest.of(pageIndex, pageSize));
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.field("orderNo").field("orderDesc");
highlightBuilder.preTags("<h3 >");
highlightBuilder.postTags("</h3>");
HighlightQuery highlightQuery = new HighlightQuery(highlightBuilder);
criteriaQuery.setHighlightQuery(highlightQuery);
SearchHits<Order> searchHits = elasticsearchRestTemplate.search(criteriaQuery, Order.class);
List<Order> result = ().map(e -> {
Order element = e.getContent();
element.HighlightFields());
return element;
}).List());
PageResponse<Order> pageResponse = new PageResponse<Order>();
pageResponse.TotalHits());
pageResponse.setResult(result);
return pageResponse;
}
@Override
public Order findById(Integer id) {
return orderRepository.findById(id).orElse(null);
}
Controller
Index操作
使⽤ElasticsearchRestTemplate直接就可以创建和删除索引。
@RequestMapping("/index/")
@RestController
public class IndexController {
@Autowired
private ElasticsearchRestTemplate elasticsearchRestTemplate;
/**
* 创建索引
*/
@GetMapping("create")
public String create(@RequestParam String indexName) {
IndexOperations indexOperations = elasticsearchRestTemplate.indexOps(IndexCoordinates.of(indexName)); if (ists()) {
return "索引已存在";
}
return "索引创建成功";
}
/**
* 删除索引
*/
@GetMapping("delete")
public String delete(@RequestParam String indexName) {
IndexOperations indexOperations = elasticsearchRestTemplate.indexOps(IndexCoordinates.of(indexName)); indexOperations.delete();
return "索引删除成功";
}
}
Document操作
主要包括简单查询、增删改、分页查询、⾼亮搜索。
@RequestMapping("/doc/")
@RestController
public class DocController {
@Autowired
OrderService orderService;
/**
* 批量创建
*/
@PostMapping("saveBatch")
public String saveBatch(@RequestBody List<Order> orders) {
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论