Elasticsearch系列(二)SpringBoot整合Spring-Data-Elasticsearch
阿新 • • 發佈:2019-02-05
一、新增依賴
SpringBoot版本需2.0x以上:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.5.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency>
二、Document物件
@Data
@Document(indexName = "rate_routing",type = "rate_routing")
public class RateRoutingDoc {
private Long rateId;
private Long itemId;
private Long accountId;
private String text;
private Long createTime;
}
三、操作
@Autowired private ElasticsearchTemplate elasticsearchTemplate; @Test public void add(){ RateRoutingDoc rateRoutingDoc = new RateRoutingDoc(); rateRoutingDoc.setRateId(100L); rateRoutingDoc.setAccountId(101L); rateRoutingDoc.setItemId(10002L); rateRoutingDoc.setCreateTime(System.currentTimeMillis()); rateRoutingDoc.setText("評論"); HashMap<String, Object> map = new HashMap<>(); map.put("rateId",rateRoutingDoc.getRateId()); map.put("accountId",rateRoutingDoc.getAccountId()); map.put("itemId",rateRoutingDoc.getItemId()); map.put("createTime",rateRoutingDoc.getCreateTime()); map.put("text",rateRoutingDoc.getText()); IndexRequest indexRequest = new IndexRequest() .index("rate_routing") .type("rate_routing") .routing(String.valueOf(rateRoutingDoc.getItemId())) .source(map); elasticsearchTemplate.getClient().index(indexRequest); } @Test public void getByRoute(){ NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withRoute("10002").build(); List<RateRoutingDoc> routingDocs = elasticsearchTemplate.queryForList(searchQuery, RateRoutingDoc.class); routingDocs.forEach(routingDoc -> System.out.println(routingDoc.toString()) ); }
更多檢視官方文件: