1.从官网下载文件,解压 我的版本7.3.1
2.进入bin目录下,运行elasticsearch.bat,启动服务
http://localhost:9200 打印信息则服务启动成功
3.springboot项目引入pom依赖
(注意springboot版本和ES版本兼容问题)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
这里我碰到了一个问题springboot版本和ES版本存在兼容问题
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
之前我的版本2.1.8,启动项目后,ES日志中显示
Received message from unsupported version: [6.4.3] minimal compatible version [6.8.0]
意思是当前ES版本7.3.1处理不了来自6.4.3版本的信息,[6.4.3]最低兼容版本[6.8.0]
所以学习时我升级了springboot版本,升级完了发现ES配置过期了,见鬼
没办法,从官网找原因吧,springboot2.0以后推荐使用Bean注入方式来配置项目,文档地址:
Spring Data Elasticsearch - Reference Documentation
/**
* @author z
* @version v1.0.0
* @date 2020/5/11 14:37
*/
@Component
public class ESConfig {
@Bean
Client client() throws UnknownHostException {
Settings settings = Settings.builder()
.put("cluster.name", "elasticsearch")
.build();
TransportClient client = new PreBuiltTransportClient(settings);
client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1")
, 9300));
return client;
}
}
如此可以启动了
4.创建实体类,添加实体类注解@Document
@Data
@Document(indexName="foo")
public class UserEntity {
@Id
private Long id;
private String name;
private Integer age;
private String mail;
private List<String> bankCards;
}
5.选择使用方式
1.CrudRepository语法和Spring Data JPA一样,这里由于我之前使用过JPA,不做解释
@Repository
public interface UserDAO extends CrudRepository<UserEntity,Long> {
}
2.注解方式使用API,很熟悉吧(redis,mq使用类型)
@Autowired
private ElasticsearchTemplate es;
demo来一波
/**
* @author z
* @version v1.0.0
* @date 2020/5/9 14:49
*/
@RequestMapping("/test")
@RestController
public class UserController {
@Autowired
private ElasticsearchTemplate es;
@Autowired
private UserDAO userDAO;
@PostMapping
public UserEntity save(){
return userDAO.save(getBean());
}
@GetMapping
public Iterable<UserEntity> get(){
return userDAO.findAll();
}
private UserEntity getBean(){
Long id = System.currentTimeMillis();
UserEntity user = new UserEntity();
user.setId(id);
user.setAge(11);
user.setName(UUID.randomUUID().toString());
user.setMail(id+"@qq.com");
List<String> list = new ArrayList<>();
list.add(UUID.randomUUID().toString());
list.add(UUID.randomUUID().toString());
list.add(UUID.randomUUID().toString());
user.setBankCards(list);
return user;
}
}
@Document实体注解内容比较多,想要详细了解的可以看看这两篇不错的博客
ElasticsearchTemplate的详细使用,完成多条件查询、匹配度查询等_tianyaleixiaowu的专栏-CSDN博客_elasticsearchtemplate