目录
一、使用spring-data方式进行操作elasticsearch
1.添加依赖
<!-- 添加 elasticsearch 客户端 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
2.添加ES配置
#使用模板方式
spring:
elasticsearch:
rest:
uris:
- http://localhost:9200
3.添加实体类
package com.tianya.springboot.es.entity;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Document(indexName = "people_index", type = "people")
public class PeopleBean {
/**
* 主键
*/
@Id
private Long uid ;
/**
* 姓名
*/
@Field
private String name ;
/**
* 年龄
*/
@Field
private int age ;
/**
* 地址
*/
@Field
private String addr ;
/**
* 生日
*/
@Field
private String birthDay ;
/**
* 职业
*/
@Field
private String professional ;
/**
* 兴趣
*/
@Field
private String interest ;
}
4.添加repository
package com.tianya.springboot.es.dao;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;
import com.tianya.springboot.es.entity.PeopleBean;
@Repository
public interface PeopleEsDao extends ElasticsearchRepository<PeopleBean, Long>{
}
准备操作都做完了,开始进行对elasticsearch操作了,新增一些测试模拟数据
1.1 新增
@SpringBootTest
public class PeopleTest {
@Autowired
private PeopleEsDao peopleEsDao ;
@Test
public void insert() {
List<PeopleBean> peopleBeanList = new ArrayList<>();
peopleBeanList.add(PeopleBean.builder().uid(1L).name("吴彦祖").age(45).birthDay("1977-01-01").addr("香港").professional("演员").interest("赛车").build());
peopleBeanList.add(PeopleBean.builder().uid(2L).name("吴奇隆").age(55).birthDay("1967-01-01").addr("大陆").professional("演员").interest("唱歌").build());
peopleBeanList.add(PeopleBean.builder().uid(3L).name("吴京").age(45).birthDay("1977-01-01").addr("大陆").professional("演员").interest("武术").build());
peopleBeanList.add(PeopleBean.builder().uid(4L).name("古天乐").age(55).birthDay("1967-01-01").addr("香港").professional("演员").interest("唱歌").build());
peopleBeanList.add(PeopleBean.builder().uid(5L).name("苏炳添").age