环境:
springboot2.*
elasticsearch6.*
1)在pom.xml中添加对es的依赖
<!--elasticsearch pom-->
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
</dependency>
2)在yml文件中添加配置
spring: data: elasticsearch: cluster-name: elasticsearch(一般是这个名字) cluster-nodes: 127.0.0.1:9300(你自己的节点) repositories: enabled: true
3)开始配置
1添加一个实体类
@Document(indexName = "fo_daboluo", type = "doc")
public class ElasticSerachEntity {
@JsonProperty("id")
private Long id;
@JsonProperty("code")
private String code;
@JsonProperty("userName")
private String userName;
@JsonProperty("password")
private String password;
@JsonProperty("mail")
private String mail;
@JsonProperty("phone")
private String phone;
@Document 引用的是 import org.springframework.data.elasticsearch.annotations.Document; 两个参数一个是索引名一 个是类型,其他是对内容的映射
2配置业务
@Component
public interface SysElasticSerach extends ElasticsearchRepository<ElasticSerachEntity,Long> {
}
3在controller中使用,保存到es再索引
@Api(tags = "ESController")
@RestController
public class ElasticSearchConytroller {
Logger logger = LogManager.getLogger(ElasticSearchConytroller.class);
@Autowired
SysElasticSerach elasticsearchRepository;
@ApiOperation(value = "将数据保存到ES内")
@GetMapping("/search/all")
public String loadAllUser() {
ElasticSerachEntity en = new ElasticSerachEntity();
//简单的引用
en.setUserName("zhang");
en.setMail("57148400@qq.com");
logger.info("es");
elasticsearchRepository.save(en);
return "111";
}
@ApiOperation(value = "查询")
@ResponseBody
@GetMapping("/search/{name}")
public ResponseEntity getByName(@PathVariable("name") String name, Pageable pageable) {
//按name进行搜索
MatchQueryBuilder builder = QueryBuilders.matchQuery("userName", name);
//如果实体和数据的名称对应就会自动封装,pageable分页参数
Page<ElasticSerachEntity> users = elasticsearchRepository.search(builder, pageable);
logger.info("搜索成功");
//迭代器转list
ArrayList<ElasticSerachEntity> list = Lists.newArrayList(users);
return ResponseEntity.ok(list);
}
}
坑
/** * Springboot整合Elasticsearch 在项目启动前设置一下的属性,防止报错 * 解决netty冲突后初始化client时还会抛出异常 * java.lang.IllegalStateException: availableProcessors is already set to [4], rejecting [4] */
在启动类main下配置:System.setProperty("es.set.netty.runtime.available.processors", "false");