环境:springboot2.4
elasticsearch有自己api,但是用起来比较繁琐,而且springboot 和elasticsearch的版本匹配容易冲突,网上有对应的版本
而spring中有个Spring Data Elasticsearch,包含了elasticsearch,所以我们就使用Spring Data Elasticsearch就好了,
整合配置如下:
1.maven中加入
不要加版本号,springboot会自动识别 相匹配的版本
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
2.yml配置
spring:
#配置Spring Data Elasticsearch
elasticsearch:
rest:
uris: 127.0.0.1:9200 # elastic search默认tcp端口9300,http端口9200
read-timeout: 30s
connection-timeout: 5s
3.增加配置类 ElasticsearchConfig
@Configuration
public class ElasticsearchConfig extends AbstractElasticsearchConfiguration {
@Value("${spring.elasticsearch.rest.uris}")
private String uris ;
//重写父类方法,获取客户端连接
@Override
@Bean
public RestHighLevelClient elasticsearchClient() {
final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
.connectedTo(uris)
.build();
return RestClients.create(clientConfiguration).rest();
}
}
4.配置实体类
@Data
//索引名称必须全部小写,不能有大写字母,配置下面的映射后项目启动会自动创建索引productbean,不需要手动创建
@Document(indexName = "productbean", shards = 3, replicas = 1)
public class ProductBean {
@Id
private String productId;//产品id
@Field(type = FieldType.Text)
private String productCode;//产品编码
@Field(type = FieldType.Keyword)
private String productName;//产品名称
private String productProcessId;//工艺id
private String productProcessCode;//工艺编号
}
5.增加实体类的映射,加了项目启动后,会自动创建索引
public interface ProductMapper extends ElasticsearchRepository<ProductBean,Long> {
}
6.新建测试类 进行测试
/**
* @description: ElasticSearch测试类
* 如果你的项目配置了websocket,@SpringBootTest必须加上webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
* 不然websocket的配置类 serverEndpointExporter无法创建bean对象
* @author: lxp
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ElasticSearchTest {
@Autowired
private ElasticsearchRestTemplate elasticsearchRestTemplate;
@Test
public void testEs(){
System.out.println("创建索引");
}
@Test
public void deleteIndex(){
boolean b=elasticsearchRestTemplate.deleteIndex(ProductBean.class);
System.out.println(""+b);
}
}