- setp1 POM文件
- step2 yaml配置
- step3 注入工具类
- step4 使用
版本约定:springboot2.1.6.RELEASE + es7.6.2
step2 yaml配置4.0.0 org.springframework.boot spring-boot-starter-parent 2.1.6.RELEASE org.example esLearn 1.0-SNAPSHOT 8 8 7.6.2 org.springframework.boot spring-boot-starter-web org.projectlombok lombok 1.18.20 provided org.springframework.data spring-data-elasticsearch 3.2.5.RELEASE com.alibaba fastjson 2.0.2
es:
host: {your es host}
port: {your es port}
step3 注入工具类
@Configuration
public class EsConfig {
@Value("${es.host}")
private String esHost;
@Value("${es.port}")
private int esPort;
@Bean
public RestHighLevelClient restHighLevelClient() {
return new RestHighLevelClient(RestClient.builder(new HttpHost(esHost, esPort, "http")));
}
}
step4 使用
@Service
public class EsService {
@Resource
private RestHighLevelClient restHighLevelClient;
public void es() throws IOException {
// 创建索引(不恰当的类似于mysql的table)
CreateIndexRequest create = new CreateIndexRequest("x_index");
CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(create, RequestOptions.DEFAULT);
System.out.println(createIndexResponse.toString());
// 获取索引(只能判读是否存在)
GetIndexRequest getIndexRequest = new GetIndexRequest("x_index");
boolean exists = restHighLevelClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
System.out.println(exists);
// 删除索引
DeleteIndexRequest xu_index = new DeleteIndexRequest("x_index");
AcknowledgedResponse delete = restHighLevelClient.indices().delete(xu_index, RequestOptions.DEFAULT);
System.out.println(delete.isAcknowledged());
// 文档添加数据
User user = new User(1, "xiaohong", 12);
IndexRequest docAdd = new IndexRequest("x_index");
docAdd.id("1");
docAdd.timeout(TimeValue.timeValueSeconds(1));
docAdd.source(JSON.toJSONString(user), XContentType.JSON);
IndexResponse response = restHighLevelClient.index(docAdd, RequestOptions.DEFAULT);
System.out.println(response.toString());
System.out.println(response.status());
// 文档查询数据
GetRequest getReq = new GetRequest("x_index", "1");
boolean exists = restHighLevelClient.exists(getReq, RequestOptions.DEFAULT);
if(exists) {
GetResponse documentFields = restHighLevelClient.get(getReq, RequestOptions.DEFAULT);
}
System.out.println(documentFields.getSourceAsString());
}
}



