1.在pom.xml中引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
<version>2.6.7</version>
</dependency>
2.在application.yml进行配置
为了方便对常量的管理
elasticsearch.host=47.114.114.78:9200
3.编写Config类
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.RestClients;
import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;
@Configuration
public class RestClientConfig extends AbstractElasticsearchConfiguration {
@Value("${elasticsearch.host}")//体现出yml文件的作用
private String host;
@Override
@Bean
public RestHighLevelClient elasticsearchClient() {
final ClientConfiguration clientConfiguration=ClientConfiguration.builder().connectedTo(host).build();
return RestClients.create(clientConfiguration).rest();
}
}
4.编写测试类
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.xcontent.XContentType;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.IOException;
@SpringBootTest
public class TestIndex {
private final RestHighLevelClient restHighLevelClient;
@Autowired
public TestIndex(RestHighLevelClient restHighLevelClient){
this.restHighLevelClient=restHighLevelClient;
}
//创建索引和映射
@Test
public void testIndexAndMapping() throws IOException{
CreateIndexRequest createIndexRequest = new CreateIndexRequest("products");
createIndexRequest.mapping("{\n" +
" \"properties\": {\n" +
" \"id\":{\n" +
" \"type\": \"integer\"\n" +
" },\n" +
" \"title\":{\n" +
" \"type\": \"keyword\"\n" +
" },\n" +
" \"desc\":{\n" +
" \"type\":\"text\",\n" +
" \"analyzer\": \"ik_max_word\"\n" +
" }\n" +
" }\n" +
" } ", XContentType.JSON);
CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
System.out.println("创建状态"+createIndexResponse.isAcknowledged());
restHighLevelClient.close();
}
//删除索引
@Test
public void testDeleteIndex() throws IOException {
AcknowledgedResponse acknowledgedResponse = restHighLevelClient.indices().delete(new DeleteIndexRequest("products"), RequestOptions.DEFAULT);
System.out.println(acknowledgedResponse.isAcknowledged());
}
}