ElasticSearch之Java Api操作
Java Api操作
参考官方文档地址:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.10/index.html
添加依赖
<dependencies>
<!-- elasticsearch -->
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.10.0</version>
</dependency>
<!-- rest-high-level-client,官方RestClient,封装ES操作-->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.10.0</version>
</dependency>
<!-- jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.9</version>
</dependency>
</dependencies>
客户端
public static void main(String[] args) throws Exception {
// 创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
// 9200端口为Elasticsearch的Web通信端口,localhost为启动ES服务的主机名,http为通信协议
RestClient.builder(new HttpHost("localhost", 9200, "http"))
);
// 关闭ES客户端
esClient.close();
}
开发中通常配置成一个Bean对象使用
@Bean
public RestHighLevelClient client(){
RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http"));
return new RestHighLevelClient(builder);
}
索引操作
创建索引
public static void main(String[] args) throws Exception {
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
// 创建索引
CreateIndexRequest createIndexRequest = new CreateIndexRequest("user");
CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
// 响应状态
boolean acknowledged = createIndexResponse.isAcknowledged();
System.out.println("创建索引状态 :" + acknowledged);
// 关闭客户端
client.close();
}
查询索引
public static void main(String[] args) throws Exception {
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
// 查询索引
GetIndexRequest getIndexRequest = new GetIndexRequest("user");
GetIndexResponse getIndexResponse = client.indices().get(getIndexRequest, RequestOptions.DEFAULT);
// 响应状态
System.out.println("查询索引之Aliases :" + getIndexResponse.getAliases());
System.out.println("查询索引之Mappings :" + getIndexResponse.getMappings());
System.out.println("查询索引之Settings :" + getIndexResponse.getSettings());
// 关闭客户端
client.close();
}
删除索引
public static void main(String[] args) throws Exception {
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
// 删除索引
DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("user");
AcknowledgedResponse response = client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
// 响应状态
System.out.println("删除索引 :" + response.isAcknowledged());
// 关闭客户端
client.close();
}
文档操作
创建User对象
@Data
public class User {
private String name;
private String sex;
private Integer age;
}
新增文档
public static void main(String[] args) throws Exception {
// 创建ES客户端
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
//新增文档,创建请求对象
IndexRequest indexRequest = new IndexRequest();
// 设置索引及唯一性标识
indexRequest.index("user").id("01");
//设置索引及唯一性标识
User user = new User();
user.setName("小白白");
user.setAge(22);
user.setSex("男");
// 向ES插入数据,必须将数据转换位JSON格式
ObjectMapper mapper = new ObjectMapper();
String userJson = mapper.writeValueAsString(user);
indexRequest.source(userJson, XContentType.JSON);
//发送请求,获取响应对象
IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
System.out.println("新增文档的状态:" + indexResponse.getResult());
// 关闭ES客户端
client.close();
}
批量新增文档
public static void main(String[] args) throws Exception {
// 创建ES客户端
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
// 创建批量新增请求对象
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.add(new IndexRequest().index("user").id("02").source(XContentType.JSON, "name", "name2", "age", 2, "sex", "男"));
bulkRequest.add(new IndexRequest().index("user").id("03").source(XContentType.JSON, "name", "name3", "age", 3, "sex", "女"));
bulkRequest.add(new IndexRequest().index("user").id("04").source(XContentType.JSON, "name", "name4", "age", 4, "sex", "男"));
bulkRequest.add(new IndexRequest().index("user").id("05").source(XContentType.JSON, "name", "name5", "age", 5, "sex", "女"));
BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
System.out.println("批量插,Took: " + bulkResponse.getTook());
System.out.println("批量插入,Items: " + bulkResponse.getItems());
// 关闭ES客户端
client.close();
}
修改文档
public static void main(String[] args) throws Exception {
// 创建ES客户端
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
// 修改文档
UpdateRequest updateRequest = new UpdateRequest();
//配置修改参数
updateRequest.index("user").id("01");
//设置请求体,对数据进行修改
updateRequest.doc(XContentType.JSON, "name", "大白白");
//发送请求,获取响应对象
UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);
System.out.println("index:" + updateResponse.getIndex());
System.out.println("id:" + updateResponse.getId());
System.out.println("result:" + updateResponse.getResult());
// 关闭ES客户端
client.close();
}
查询文档
public static void main(String[] args) throws Exception {
// 创建ES客户端
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
//创建请求对象
GetRequest request = new GetRequest().index("user").id("01");
//客户端发送请求,获取响应对象
GetResponse response = client.get(request, RequestOptions.DEFAULT);
System.out.println("index:" + response.getIndex());
System.out.println("type:" + response.getType());
System.out.println("id:" + response.getId());
System.out.println("source:" + response.getSourceAsString());
// 关闭ES客户端
client.close();
}
删除文档
public static void main(String[] args) throws Exception {
// 创建ES客户端
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
DeleteRequest request = new DeleteRequest();
request.index("user").id("02");
DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
System.out.println(response.toString());
// 关闭ES客户端
client.close();
}
批量删除
public static void main(String[] args) throws Exception {
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
// 批量删除数据
BulkRequest request = new BulkRequest();
request.add(new DeleteRequest().index("user").id("02"));
request.add(new DeleteRequest().index("user").id("03"));
request.add(new DeleteRequest().index("user").id("04"));
BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
System.out.println(response.getTook());
System.out.println(response.getItems());
// 关闭ES客户端
client.close();
}
高级查询
查询所有索引数据
public static void main(String[] args) throws Exception {
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
// 创建搜索请求对象
SearchRequest request = new SearchRequest();
request.indices("user");
// 构建查询的请求体
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
request.source(searchSourceBuilder);
// 查询匹配
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println("耗时:" + response.getTook());
System.out.println("命中条数:" + hits.getTotalHits());
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
// 关闭ES客户端
client.close();
}
term条件查询
public static void main(String[] args) throws Exception {
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
SearchRequest request = new SearchRequest();
request.indices("user");
request.source(new SearchSourceBuilder().query(QueryBuilders.termQuery("age", 22)));
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println("耗时:" + response.getTook());
System.out.println("命中条数:" + hits.getTotalHits());
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
// 关闭ES客户端
client.close();
}
分页查询
public static void main(String[] args) throws Exception {
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
SearchRequest request = new SearchRequest();
request.indices("user");
SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
// (当前页码-1)*每页显示数据条数
builder.from(0);
builder.size(2);
request.source(builder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println("耗时:" + response.getTook());
System.out.println("命中条数:" + hits.getTotalHits());
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
// 关闭ES客户端
client.close();
}
排序查询
public static void main(String[] args) throws Exception {
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
SearchRequest request = new SearchRequest();
request.indices("user");
SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
// 排序
builder.sort("age", SortOrder.DESC);
request.source(builder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println("耗时:" + response.getTook());
System.out.println("命中条数:" + hits.getTotalHits());
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
// 关闭ES客户端
client.close();
}
文档字段过滤
public static void main(String[] args) throws Exception {
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
SearchRequest request = new SearchRequest();
request.indices("user");
SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
// 排除字段
String[] excludes = {};
// 包含字段
String[] includes = {"name"};
builder.fetchSource(includes, excludes);
request.source(builder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println("耗时:" + response.getTook());
System.out.println("命中条数:" + hits.getTotalHits());
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
// 关闭ES客户端
client.close();
}
Bool组合查询
public static void main(String[] args) throws Exception {
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
SearchRequest request = new SearchRequest();
request.indices("user");
SearchSourceBuilder builder = new SearchSourceBuilder();
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
// 必须包含
boolQueryBuilder.must(QueryBuilders.matchQuery("name", "小白"));
// 一定不含
boolQueryBuilder.mustNot(QueryBuilders.matchQuery("sex", "男"));
// 可能包含
boolQueryBuilder.should(QueryBuilders.matchQuery("age", 20));
boolQueryBuilder.should(QueryBuilders.matchQuery("age", 22));
builder.query(boolQueryBuilder);
request.source(builder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println("耗时:" + response.getTook());
System.out.println("命中条数:" + hits.getTotalHits());
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
// 关闭ES客户端
client.close();
}
范围查询
public static void main(String[] args) throws Exception {
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
SearchRequest request = new SearchRequest();
request.indices("user");
SearchSourceBuilder builder = new SearchSourceBuilder();
RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("age");
rangeQuery.gte(15);
rangeQuery.lt(30);
builder.query(rangeQuery);
request.source(builder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println("耗时:" + response.getTook());
System.out.println("命中条数:" + hits.getTotalHits());
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
// 关闭ES客户端
client.close();
}
模糊查询
public static void main(String[] args) throws Exception {
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
SearchRequest request = new SearchRequest();
request.indices("user");
SearchSourceBuilder builder = new SearchSourceBuilder();
builder.query(QueryBuilders.fuzzyQuery("name", "白").fuzziness(Fuzziness.TWO));
request.source(builder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println("耗时:" + response.getTook());
System.out.println("命中条数:" + hits.getTotalHits());
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
// 关闭ES客户端
client.close();
}
高亮查询
public static void main(String[] args) throws Exception {
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
SearchRequest request = new SearchRequest();
request.indices("user");
SearchSourceBuilder builder = new SearchSourceBuilder();
TermsQueryBuilder termsQueryBuilder = QueryBuilders.termsQuery("name", "小白");
// 构建高亮字段
HighlightBuilder highlightBuilder = new HighlightBuilder();
// 前置标签
highlightBuilder.preTags("<font color='red'>");
// 后置标签
highlightBuilder.postTags("</font>");
// 高亮字段
highlightBuilder.field("name");
//设置高亮构建对象
builder.highlighter(highlightBuilder);
builder.query(termsQueryBuilder);
request.source(builder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println("耗时:" + response.getTook());
System.out.println("命中条数:" + hits.getTotalHits());
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
// 关闭ES客户端
client.close();
}
聚合查询
public static void main(String[] args) throws Exception {
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
SearchRequest request = new SearchRequest();
request.indices("user");
SearchSourceBuilder builder = new SearchSourceBuilder();
AggregationBuilder aggregationBuilder1 = AggregationBuilders.max("maxAge").field("age");
builder.aggregation(aggregationBuilder1);
AggregationBuilder aggregationBuilder2 = AggregationBuilders.avg("avgAge").field("age");
builder.aggregation(aggregationBuilder2);
request.source(builder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
System.out.println(response);
SearchHits hits = response.getHits();
System.out.println("耗时:" + response.getTook());
System.out.println("命中条数:" + hits.getTotalHits());
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
// 关闭ES客户端
client.close();
}
分组查询
public static void main(String[] args) throws Exception {
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
SearchRequest request = new SearchRequest();
request.indices("user");
SearchSourceBuilder builder = new SearchSourceBuilder();
AggregationBuilder aggregationBuilder = AggregationBuilders.terms("ageGroup").field("age");
builder.aggregation(aggregationBuilder);
request.source(builder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println("耗时:" + response.getTook());
System.out.println("命中条数:" + hits.getTotalHits());
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
// 关闭ES客户端
client.close();
}