elasticSearch java api接口
程序员文章站
2024-01-03 21:21:04
...
引入pom依赖
这个是包装了方法的es客户端
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.7.0</version>
</dependency>
我们也可以用springboot封装的依赖
<!-- 导入依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
编写代码
先得到一个客户端
@Bean
public RestHighLevelClient getClient(){
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 9200, "http")));
return client;
}
在操作一个客户端
操作索引 indices
创建一个索引
public void initEs() throws IOException {
CreateIndexRequest createIndexRequest = new CreateIndexRequest("java");
client.indices().create(createIndexRequest,RequestOptions.DEFAULT);
}
查看所以是否存在
public void isExist() throws IOException {
// 查看索引是否存在
GetIndexRequest getIndexRequest = new GetIndexRequest("java");
boolean exists = client.indices().exists(getIndexRequest,RequestOptions.DEFAULT);
System.out.println(exists);
}
这里我们看到GetIndexRequest底层在构造器里需要可以加入索引的名称
public GetIndexRequest(String... indices) {
this.features = DEFAULT_FEATURES;
this.humanReadable = false;
this.includeDefaults = false;
this.indicesOptions = IndicesOptions.fromOptions(false, false, true, true);
this.local = false;
this.indices = indices;
}
删除索引
@Test
public void deleteIndex() throws IOException {
// 删除索引
DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("java");
AcknowledgedResponse delete = client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
System.out.println(delete);
}
同样是在源码里面我们看到了构造是偶传入相关的参数
public DeleteIndexRequest(String index) {
this.indices = new String[]{index};
}
public DeleteIndexRequest(String... indices) {
this.indices = indices;
}
小结:对索引操作都是通过客户端.indices(),也就对于一个操作索引的方法可以看作是:客户端.索引().操作(),这个操可以可以事索引的增删改查。
拓展,对于其他的操作如对类型的操作以及对文档的操作应该都和对索引操作差不多,即只要找到对应操作的位置,后面就会存在一系类的增删改查方法。
操作文档 index
插入文档(数据)
@Test
public void insertFile() throws IOException {
// 产生数据 这里数据来来源可以是数据库等等
User user = new User("1","ubw");
IndexRequest indexRequest = new IndexRequest("java");
// indexRequest.id("2"); 如果是制定id就用你的id,如果不制定就产生默认id
indexRequest.timeout(TimeValue.timeValueSeconds(2));
// 数据传输的时候用json字符串记性对象封装
indexRequest.source(JSON.toJSONString(user),XContentType.JSON);
IndexResponse index = client.index(indexRequest,RequestOptions.DEFAULT);
System.out.println(index);
}
// 这里的默认产生的id是lEYFWXIB-NPGY4hFuqZu
查看数据是否存在
public void getFileById() throws IOException {
GetRequest getRequest = new GetRequest("java");
// fetchSourceContext 是对数据源的规定,可以进去看源码 里面有final型,故这个是可以直接写结果的。
getRequest.fetchSourceContext(FetchSourceContext.DO_NOT_FETCH_SOURCE);
// 查询id为1 的文档
getRequest.id("1");
// 这里是查找就exist
boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);
System.out.println(exists);
}
删除数据
public void deleteById() throws IOException {
DeleteRequest deleteRequest = new DeleteRequest("java");
deleteRequest.id("1");
DeleteResponse delete = client.delete(deleteRequest, RequestOptions.DEFAULT);
System.out.println(delete);
}
-------------------------------
结果为:
DeleteResponse[index=java,type=_doc,id=1,version=6,result=deleted,shards=ShardInfo{total=2, successful=1, failures=[]}]
通过id查询文档
public void getById() throws IOException {
GetRequest getRequest = new GetRequest("java");
// 通过id记性查询
getRequest.id("2");
GetResponse documentFields = client.get(getRequest, RequestOptions.DEFAULT);
System.out.println(documentFields);
}
结果为:
{"_index":"java","_type":"_doc","_id":"2","_version":1,"_seq_no":5,"_primary_term":1,"found":true,"_source":{"age":"1","username":"ubw"}}
修改数据
update之后看到这些东西
这里回想起用kibana练习的时候的doc文档。doc文档里面是应该更新的数据
@Test
public void updateById() throws IOException {
// 数据
User user = new User("12", "coding");
UpdateRequest updateRequest = new UpdateRequest("java","2");
updateRequest.doc(JSON.toJSONString(user),XContentType.JSON);
updateRequest.timeout(TimeValue.timeValueSeconds(2));
UpdateResponse update = client.update(updateRequest, RequestOptions.DEFAULT);
System.out.println(update);
}
复杂查询
public void queryFile() throws IOException {
SearchRequest searchRequest = new SearchRequest("ubw");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchRequest.source(searchSourceBuilder);
SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(search);
}
这里查到了所有的记录,会想es的查找风格我们可以构件查找的条件或者用过滤器进行过滤。
public void queryFile() throws IOException {
SearchRequest searchRequest = new SearchRequest("ubw");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// MatchQueryBuilder
MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("name", "二");
searchSourceBuilder.query(matchQueryBuilder);
searchRequest.source(searchSourceBuilder);
SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(search);
}
--------------------------------------------------------
结果为:
{"took":14,"timed_out":false,"_shards":{"total":1,"successful":1,"skipped":0,"failed":0},"hits":{"total":{"value":2,"relation":"eq"},"max_score":1.5282801,"hits":[{"_index":"ubw","_type":"_doc","_id":"test2","_score":1.5282801,"_source":{"name":"二狗子","age":12}},{"_index":"ubw","_type":"_doc","_id":"3","_score":1.5282801,"_source":{"name":"李二狗","age":12,"tag":["程序员","小白","牲口"],"doc":"求老婆,盼大佬"}}]}}
通过过滤器进行数据过滤
public void filterForData() throws IOException {
SearchRequest searchRequest = new SearchRequest("ubw");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// 添加条件
QueryBuilder queryBuilder = QueryBuilders.matchPhrasePrefixQuery("name","二");
// 过滤器
searchSourceBuilder.postFilter(queryBuilder);
searchRequest.source(searchSourceBuilder);
SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(search);
}
-----------------------------------------------------------
结果为:
{"took":24,"timed_out":false,"_shards":{"total":1,"successful":1,"skipped":0,"failed":0},"hits":{"total":{"value":2,"relation":"eq"},"max_score":1.0,"hits":[{"_index":"ubw","_type":"_doc","_id":"test2","_score":1.0,"_source":{"name":"二狗子","age":12}},{"_index":"ubw","_type":"_doc","_id":"3","_score":1.0,"_source":{"name":"李二狗","age":12,"tag":["程序员","小白","牲口"],"doc":"求老婆,盼大佬"}}]}}
正好应证了测试时候的 ----- 条件和过滤器都能得到我们想要的结果。 这个结论
end