简介
使用Java api操作elasticsearch
创建maven项目
pom.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>elasticsearchTest</artifactId>
<version>1.0-SNAPSHOT</version>
<name>elasticsearchTest</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.8.0</version>
</dependency>
<!-- elasticsearch 的客户端 -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.8.0</version>
</dependency>
<!-- elasticsearch 依赖 2.x 的 log4j -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.8.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.8.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.9</version>
</dependency>
<!-- junit 单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
</project>
创建索引
package org.christ.es;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import java.io.IOException;
public class elasticSearchTest {
public static void main(String[] args) throws IOException {
//es客户端
RestHighLevelClient restHighLevelClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//创建索引
CreateIndexRequest request = new CreateIndexRequest("user");
CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
//响应状态
boolean acknowledged = createIndexResponse.isAcknowledged();
System.out.println("操作是否成功:"+ acknowledged);
//关闭es客户端
restHighLevelClient.close();
}
}
验证
使用postman发送get请求:http://localhost:9200/_cat/indices?v
查询索引
GetIndexRequest request = new GetIndexRequest("user");
GetIndexResponse getIndexResponse = restHighLevelClient.indices().get(request, RequestOptions.DEFAULT);
System.out.println(getIndexResponse.getMappings());
System.out.println(getIndexResponse.getAliases());
System.out.println(getIndexResponse.getSettings());
删除索引
DeleteIndexRequest request = new DeleteIndexRequest("user");
AcknowledgedResponse delete = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
System.out.println(delete.isAcknowledged());
添加数据
创建user类
```java
package org.christ.pojo;
public class user {
private String name;
private String sex;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
插入数据
//插入数据
IndexRequest indexRequest = new IndexRequest();
indexRequest.index("user").id("1");
user user = new user();
user.setName("christ");
user.setSex("man");
user.setAge(20);
//转换成json
ObjectMapper objectMapper = new ObjectMapper();
String s = objectMapper.writeValueAsString(user);
indexRequest.source(s, XContentType.JSON);
IndexResponse index = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
System.out.println(index.getResult());
验证
postman发送get请求:http://localhost:9200/user/_doc/1
修改数据
UpdateRequest updateRequest = new UpdateRequest();
updateRequest.index("user").id("1");
updateRequest.doc(XContentType.JSON,"sex","superman");
UpdateResponse update = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
System.out.println(update.getResult());
验证
postman发送get请求:http://localhost:9200/user/_doc/1
查询数据
GetRequest getRequest = new GetRequest();
getRequest.index("user").id("1");
GetResponse documentFields = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
System.out.println(documentFields.getSourceAsString());
删除数据
DeleteRequest deleteRequest = new DeleteRequest();
deleteRequest.index("user").id("1");
DeleteResponse delete = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
System.out.println(delete.status());
批量插入数据
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.add(new IndexRequest().index("user").id("2").source(XContentType.JSON,"name","jack"));
bulkRequest.add(new IndexRequest().index("user").id("3").source(XContentType.JSON,"name","john"));
BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
System.out.println(bulk.getItems());
批量删除数据
//批量删除数据
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.add(new DeleteRequest().index("user").id("2"));
bulkRequest.add(new DeleteRequest().index("user").id("3"));
BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
System.out.println(bulk);
验证
postman发送get请求:http://localhost:9200/user/_search
全量查询
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices("user");
searchRequest.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()));
SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = search.getHits();
System.out.println(hits);
for (SearchHit h:hits) {
System.out.println(h.getSourceAsString());
}
条件查询
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices("user");
searchRequest.source(new SearchSourceBuilder().query(QueryBuilders.termQuery("sex","girl")));
SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = search.getHits();
for (SearchHit h:hits) {
System.out.println(h.getSourceAsString());
}
和全量查询的区别是:
searchRequest.source(new SearchSourceBuilder().query(QueryBuilders.termQuery("sex","girl")));
QueryBuilders.matchAllQuery()换成了有条件的QueryBuilders.termQuery(“sex”,“girl”)
分页查询
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices("user");
//SearchSourceBuilder提取出来
SearchSourceBuilder query = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
//第1页,展示两条数据
query.from(0);
query.size(2);
searchRequest.source(query);
SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = search.getHits();
System.out.println(hits);
for (SearchHit h:hits) {
System.out.println(h.getSourceAsString());
}
把全量查询中的searchRequest.source()括号中的条件提取出来,设置from和size属性。
排序查询
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices("user");
SearchSourceBuilder query = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
query.sort("age", SortOrder.DESC);
searchRequest.source(query);
SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = search.getHits();
System.out.println(hits);
for (SearchHit h:hits) {
System.out.println(h.getSourceAsString());
}
把全量查询中的searchRequest.source()括号中的条件提取出来,设置sort属性。
查询过滤字段
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices("user");
SearchSourceBuilder query = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
String[] excludes={};
String[] includes={"name"};
query.fetchSource(includes,excludes);
searchRequest.source(query);
SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = search.getHits();
System.out.println(hits);
for (SearchHit h:hits) {
System.out.println(h.getSourceAsString());
}
SearchSourceBuilder 构建条件的时候,有一个fetchSource()方法,第一个参数就是包含哪些字段,第二个参数就是排除哪些字段。
条件查询
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices("user");
SearchSourceBuilder query = new SearchSourceBuilder();
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
// boolQueryBuilder.should(QueryBuilders.matchQuery("age","23"));
// boolQueryBuilder.should(QueryBuilders.matchQuery("age","18"));
boolQueryBuilder.must(QueryBuilders.matchQuery("name","christ"));
query.query(boolQueryBuilder);
searchRequest.source(query);
SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = search.getHits();
System.out.println(hits);
for (SearchHit h:hits) {
System.out.println(h.getSourceAsString());
}
范围查询
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices("user");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
RangeQueryBuilder age = QueryBuilders.rangeQuery("age");
age.gt(20);
searchSourceBuilder.query(age);
searchRequest.source(searchSourceBuilder);
SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = search.getHits();
System.out.println(hits);
for (SearchHit h:hits) {
System.out.println(h.getSourceAsString());
}
模糊查询
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices("user");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//name字符有一个不同也可以查出来
searchSourceBuilder.query(QueryBuilders.fuzzyQuery("name","chris").fuzziness(Fuzziness.ONE));
searchRequest.source(searchSourceBuilder);
SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = search.getHits();
System.out.println(hits);
for (SearchHit h:hits) {
System.out.println(h.getSourceAsString());
}
聚合查询
查询最大值
//聚合查询
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices("user");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
MaxAggregationBuilder field = AggregationBuilders.max("maxAge").field("age");
searchSourceBuilder.aggregation(field);
searchRequest.source(searchSourceBuilder);
SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(search);
分组查询
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices("user");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
TermsAggregationBuilder field = AggregationBuilders.terms("groupAge").field("age");
searchSourceBuilder.aggregation(field);
searchRequest.source(searchSourceBuilder);
SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(search);