前言
社区中,关于ES的概念讲解和操作资料都很多,各位需要的小伙伴可以自己搜索,这个只记录了JAVA实际应用中关于ES的一些基本操作。
JAVA索引操作
1、引入maven依赖
我这里用的是7.x版本,之前的版本中关于"类型(type)"这个概念会废弃,具体的各位自己了解
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
</dependency>
2、配置ES连接,干一个配置类,通过bean注入的方式即可
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 类描述:
*
* @author LiLiDong
* @date 2022/11/24 22:05
*/
@Configuration
public class ElasticSearchClientConfig {
@Bean
public RestHighLevelClient restHighLevelClient() {
RestHighLevelClient restHighLevelClient = new RestHighLevelClient(
RestClient.builder(
new HttpHost("127.0.0.1", 9200)));
return restHighLevelClient;
}
}
备注:注意IP和端口换成你自己的,铁子们。
3、创建索引以及需要的字段(field)
解释:相当于创建一个数据库,库中的表是默认的,再创建表字段
// 测试索引的创建
@Test
void testCreateIndex() throws IOException {
// 1.创建索引请求
CreateIndexRequest request = new CreateIndexRequest("test_create_index");
request.settings(this.getSettings()).mapping(this.getMappings());
// 2.执行创建请求,请求后获得响应createIndexResponse
CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
System.out.println(createIndexResponse);
}
/**
* 指定默认的索引分片和副本分片数量
*/
public Settings.Builder getSettings(){
return Settings.builder().put("number_of_shards",5).put("number_of_replicas",1);
}
/**
* 指定字段名称以及对于的数据类型
*/
public XContentBuilder getMappings() throws IOException {
return JsonXContent.contentBuilder().
startObject().
startObject("properties").
startObject("name").
field("type", "text").field("analyzer", "ik_max_word").
endObject().
startObject("author").
field("type", "keyword").
endObject().
startObject("price").
field("type", "long").
endObject().
startObject("pubdate").
field("type", "date").field("format", "yyyy-MM-dd HH:mm:ss").
endObject().
endObject().
endObject();
}
4、判断索引是否存在,存在的话,会返回true
// 测试获取索引,只能判断其是否存在
@Test
void testExistIndex() throws IOException {
// 1.创建索引请求
GetIndexRequest request = new GetIndexRequest("test_create_index");
// 2.获取索引,是否存在
boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
System.out.println(exists);
}
5、删除索引
// 测试删除索引
@Test
void testDeleteIndex() throws IOException {
String indexName = "test_create_index";
// 1.创建删除索引请求
DeleteIndexRequest request = new DeleteIndexRequest("test_create_index");
// 2.获取删除状态
AcknowledgedResponse response = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
System.out.println(response.isAcknowledged() ? indexName + "删除成功!" : indexName + "删除失败!");
}
JAVA操作文档
请见下一篇,掘金好像不允许超长,需要改进一下...