<!-- elasticsearch -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
spring:
data:
elasticsearch:
cluster-nodes: ip:9300
cluster-name: elasticsearch
## 默认cluster-name的是elasticsearch
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
@SpringBootApplication
@EnableElasticsearchRepositories("com.zhanhao.springbootelasticsearch.dao")
public class SpringbootElasticsearchApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootElasticsearchApplication.class, args);
}
}
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
//添加索引名及文档类型
@Document( indexName = "myindex", type = "user")
public class UserEntity {
@Id
private String id;
private String name;
private String sex;
private Integer age;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
import com.zhanhao.springbootelasticsearch.entity.UserEntity;
import org.springframework.data.repository.CrudRepository;
//对应的实体和id类型
public interface UserDao extends ElasticsearchRepository<UserEntity, String> {
}
import com.zhanhao.springbootelasticsearch.dao.UserDao;
import com.zhanhao.springbootelasticsearch.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Optional;
@RestController
public class TestController {
@Autowired
private UserDao userDao
//添加文档
@RequestMapping("/addUser")
public UserEntity addUser(@RequestBody UserEntity userEntity){
return userDao.save(userEntity);
}
//查询文档
@RequestMapping("/findById")
public Optional<UserEntity> findById(@RequestParam("id") String id){
return userDao.findById(id);
}
}