Spring Data Elasticsearch提供了ElasticsearchTemplate工具類,實現了POJO與elasticsearch文檔之間的映射
在SprinBoot工程中引入jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
配置文件
spring.data.elasticsearch.cluster-name=elasticsearch //名字必須和elasticsearch.yml裏面的cluster.name相同
spring.data.elasticsearch.cluster-nodes=127.0.0.1:9300
spring.data.elasticsearch.repositories.enabled=true
創建實體,並對類和屬性進行標註
@Document(indexName = "item",type = "docs", shards = 1, replicas = 0)//標記爲文檔類型,ndexName:對應索引庫名稱type:對應在索引庫中的類型,shards:分片數量,默認5,replicas:副本數量,默認1
public class Item {
@Id //主鍵
private Long id;
@Field(type = FieldType.Text, analyzer = "ik_max_word" store = true) //標記爲成員變量 FieldType,可以是text、long、short、date、integer等 text:存儲數據時候,會自動分詞,並生成索引 keyword:存儲數據時候,不會分詞建立索引 analyzer:分詞器名稱 store是否索引
private String title; //標題
@Field(type = FieldType.Keyword)
private String category;// 分類
@Field(type = FieldType.Keyword)
private String brand; // 品牌
@Field(type = FieldType.Double)
private Double price; // 價格
@Field(index = false, type = FieldType.Keyword)//index:是否索引
private String images; // 圖片地址
引入模板ElasticsearchTemplate
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
創建一個索引
//添加索引
@Test
public void addIndex() {
elasticsearchTemplate.createIndex(Item.class);
}
刪除索引
//刪除索引
@Test
public void delete(){
elasticsearchTemplate.deleteIndex("item");
}
新增對象
繼承Repository提供的一些子接口,就能具備各種基本的CRUD功能,這裏繼承ElasticsearchCrudRepository
首先定義一個對象的接口
public interface ItemRepository extends ElasticsearchCrudRepository<Item,Long> {
}
然後注入ItemRepository
@Autowired
private ItemRepository itemRepository;
新增對象
//新增一個對象
@Test
public void insert(){
Item item = new Item(2L,"iPhoneEs2","手機","iPhone",2500.00,"http://image.baidu.com/iPhone.jpg");
//Order order = new Order(20180020,"菜單");
itemRepository.save(item);
}
批量新增
//批量新增
@Test
public void insertList(){
List<Item> list = new LinkedList<>();
list.add(new Item(9L,"華爲p10","手機","華爲",3500.00,"http://image.baidu.com/13123.jpg"));
list.add(new Item(10L,"華爲p40","手機","華爲",5450.00,"http://image.baidu.com/13123.jpg"));
list.add(new Item(11L,"華爲p40 pro","手機","華爲",6980.00,"http://image.baidu.com/13123.jpg"));
itemRepository.saveAll(list);
}
查詢
//根據字段查詢所有
@Test
public void queryAll(){
//升序,相應降序爲dscending
Iterable<Item> items = this.itemRepository.findAll(Sort.by("price").ascending());
for (Item item : items){
System.out.println(item);
}
}
普通jpa查詢語法查詢
根據Title查詢
@Test
public void findByTitle(){
Item item = this.itemRepository.findByTitle("堅果pro");
System.out.println(item);
}