springboot+elasticsearch基本使用
阿新 • • 發佈:2018-11-19
-
匯入maven座標
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency>
-
application.properties配置檔案中配置
#elasticsearch配置 spring.data.elasticsearch.cluster-name = elasticsearch spring.data.elasticsearch.cluster-nodes = 127.0.0.1:9300
-
建立dao
public interface ProductResiporty extends ElasticsearchRepository<Productpojo,Integer> { }
-
建立pojo類
package com.czxy.web.repertory; import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.FieldType; import org.springframework.format.annotation.DateTimeFormat; import javax.persistence.Column; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import java.util.Date; @Document(indexName = "promition",type = "tt") public class Productpojo { @Id private Integer id; @Field(type = FieldType.Auto ) private String titleImg; // 宣傳圖片 @Field(type = FieldType.Keyword ) private String activeScope;// 活動範圍 @Field(type = FieldType.Date ) private Date endDate; // 失效時間 @Field(type = FieldType.Text ) private String updateUser;// 更新人 後續與後臺使用者關聯 @Field(type = FieldType.Integer ) private String status = "1"; // 狀態 可取值:0 未開始 1.進行中 2. 已結束 //省略setter個getter方法
-
controller層同步資料庫中的資料到elasticsearch中
package com.czxy.web.repertory; import com.czxy.dao.text_delivery.PromotionMapper; import com.czxy.domain.teke_delivery.Promotion; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.List; @RestController @RequestMapping("/estest") public class SpringTaskController { @Autowired private PromotionMapper productMapper; @Autowired private ProductResiporty productResiporty; @GetMapping("/dj") public void DjTask() { List<Promotion> products = productMapper.selectAll(); List<Productpojo> list = new ArrayList<>(); for (Promotion product : products) { Productpojo productpojo = new Productpojo(); BeanUtils.copyProperties(product, productpojo); list.add(productpojo); } productResiporty.saveAll(list); } }