1、在搜索上创建索引库:
2、添加依赖
《dependency》
《groupId》org.springframework.boot《/groupId》
《artifactId》spring-boot-starter-data-elasticsearch《/artifactId》
《/dependency》
3、在application.properties中配置连接信息
spring.data.elasticsearch.cluster-name=elasticsearch
spring.data.elasticsearch.cluster-nodes=192.168.100.25:9300
’
4、防止报错,配置组件
@Configuration
public class EleaticsearchConfig {
@PostConstruct
void init() {
System.setProperty("es.set.netty.runtime.available.processors", "false");
}
}
5、编写实体类
@Document(indexName = “coreqi”, type = “user”)
public class EsUser implements Serializable {
@Id //主键
private String id; //ES中id不能定义为Long
private String username;
private String password;
private Integer enabled;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getEnabled() {
return enabled;
}
public void setEnabled(Integer enabled) {
this.enabled = enabled;
}
public EsUser(String id, String username, String password, Integer enabled) {
this.id = id;
this.username = username;
this.password = password;
this.enabled = enabled;
}
@Override
public String toString() {
return "EsUser{" +
"id='" + id + '\'' +
", username='" + username + '\'' +
", password='" + password + '\'' +
", enabled=" + enabled +
'}';
}
}
6、配置Repository类
/**
Page findEsUsersByUsername(String username, Pageable pageable);
List findByUsernameLike(String username);
}
7、测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class ElaticsearchTest {
@Autowired
private EsUserRepository esUserRepository;
@Test
public void initRepositoryData() {
//清除ES中数据以免影响测试结果
esUserRepository.deleteAll();
//插入数据
esUserRepository.save(new EsUser("1", "张三", "admin", 1));
esUserRepository.save(new EsUser("2", "李四", "root", 1));
esUserRepository.save(new EsUser("3", "王五", "sa", 1));
}
//查询
@Test
public void contextLoads(){
// Pageable pageable = PageRequest.of(0,20);
// Page result = esUserRepository.findEsUsersByUsername("fanqi",pageable);
List result = esUserRepository.findByUsernameLike("张");
for(EsUser user:result){
System.out.println(user);
}
}
//查询
@Test
public void searchlike(){
/* List result =
esUserRepository.findByUsernameLike("fan");
for(EsUser user:result){
System.out.println(user.toString());
}*/
List result = bookRepository.findByBookNameLike("西");
for (BookTest book : result){
System.out.println(book);
}
}
}