Java API操作ES
Java API操作ES
Elastic Search软件是由Java语言开发的,所以也可以通过Java API的方法对Elastic Search服务进行访问。
1. 引入POM文件
<properties>
<elasticsearch.version>7.6.2</elasticsearch.version>
</properties>
<dependencies>
<!-- elasticsearch-rest-high-level-client -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>${elasticsearch.version}</version>
</dependency>
<!--fast json-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.69</version>
</dependency>
<!--引入spring-boot-test-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
注:Elastic Search官方已经给出早期版本的客户端对象已经不在推荐使用,而且在未来版本中会被删除。因此在引入pom文件中直接使用高级REST客户端对象。
https://www.elastic.co/guide/en/elasticsearch/reference/current/api-java.html
2. 编写ES配置类
@Configuration
public class ElasticsearchConfiguration {
@Value("${elasticsearch.host}")
private String host;
@Value("${elasticsearch.port}")
private int port;
@Bean
public RestHighLevelClient initRestClient() {
RestClientBuilder builder= null;
builder = RestClient.builder(new HttpHost(host, port));
return new RestHighLevelClient(builder);
}
}
可以将es的host和port信息通过外部配置文件方式引入
elasticsearch:
host: 127.0.0.1
port: 9200
3.索引的基本操作
使用SpringBootTest创建测试类,并通过Junit的@After注解完成客户端关闭操作。
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class ESIndexTest {
@Autowired
private RestHighLevelClient esClient;
private final static String ES_INDEX="foodie_shop";
//关闭连接
@After
public void closeClient(){
try {
esClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
3.1 创建索引
@Test
public void testCreateIndex(){
CreateIndexRequest request = new CreateIndexRequest(ES_INDEX);
try {
CreateIndexResponse response = esClient.indices().create(request, RequestOptions.DEFAULT);
//响应状态
boolean acknowledged = response.isAcknowledged();
log.info("索引创建状态:{}",acknowledged);
} catch (IOException e) {
e.printStackTrace();
}
}
后台打印日志
2021-11-02 15:46:08.180 INFO 4751 --- [ main] c.h.s.c.ESIndexTest : 索引创建状态:true
3.2 查询索引
@Test
public void searchIndex() throws IOException {
// 查询索引
GetIndexRequest request = new GetIndexRequest(ES_INDEX);
GetIndexResponse response = esClient.indices().get(request, RequestOptions.DEFAULT);
log.info("aliases {}",response.getAliases());
log.info("mappings {}",response.getMappings());
log.info("settings {}",response.getSettings());
}
2021-11-02 15:48:04.972 INFO 4770 --- [ main] c.h.s.c.ESIndexTest : aliases {user=[]}
2021-11-02 15:48:04.973 INFO 4770 --- [ main] c.h.s.c.ESIndexTest : mappings {user=org.elasticsearch.cluster.metadata.MappingMetaData@8ce87599}
2021-11-02 15:48:04.973 INFO 4770 --- [ main] c.h.s.c.ESIndexTest : settings {user={"index.creation_date":"1635839167732","index.number_of_replicas":"1","index.number_of_shards":"1","index.provided_name":"user","index.uuid":"Ew4nD6V6Q7uKr-BCAUTiKA","index.version.created":"7100299"}}
3.3 删除索引
@Test
public void deleteIndex() throws IOException {
//删除索引 - 请求对象
DeleteIndexRequest request =new DeleteIndexRequest(ES_INDEX);
//发送请求
AcknowledgedResponse response = esClient.indices().delete(request, RequestOptions.DEFAULT);
//操作结果
log.info("操作结果:{}",response.isAcknowledged());
}
后台打印日志信息
2021-11-02 15:49:51.578 INFO 4788 --- [ main] c.h.s.c.ESIndexTest : 操作结果:true
4. 文档的基本操作
在创建文档之前,需要先创建文档对象实体类对象模型
@Data
@TableName("t_user")
public class User {
/**
* erpId
*/
@TableId(type = IdType.AUTO)
private Long erpId;
/**
* 用户名
*/
private String erpName;
/**
* 真实姓名
*/
private String realName;
/**
* 性别。0表示男,1表示女,2代表未知
*/
private Integer gender;
/**
* 头像
*/
private String avatar;
/**
* 电话
*/
private String phone;
/**
* 邮箱
*/
private String email;
/**
* 密码
*/
private String password;
/**
* 是否删除 0表示未删除,1表示已删除
*/
private Integer isDeleted;
/**
* 0代表超管,1代表普通用户
*/
private Integer priorityLevel;
/**
* 创建时间
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
/**
* 更新时间
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date updateTime;
4.1 新增文档
创建数据,添加到对应的文档中
@Test
public void testInsert() throws IOException {
IndexRequest request = new IndexRequest();
request.index("user").id("1001");
User user = new User();
user.setErpName("zhangsansan");
user.setRealName("张三三");
user.setPhone("12345654");
user.setEmail("45456222333@qq.com");
user.setPassword("13221");
user.setIsDeleted(0);
user.setCreateTime(new Date());
user.setUpdateTime(new Date());
//向ES插入数,必须转为JSON
ObjectMapper mapper = new ObjectMapper();
String userJson = mapper.writeValueAsString(user);
request.source(userJson,XContentType.JSON);
IndexResponse response = esClient.index(request, RequestOptions.DEFAULT);
log.info("插入数据结果:{}", JSON.toJSONString(response));
}
执行成功后日志输出信息
2021-11-02 15:54:49.037 INFO 4837 --- [ main] c.h.s.c.ESDocTest : 插入数据结果:{"fragment":false,"id":"1001","index":"user","primaryTerm":1,"result":"CREATED","seqNo":0,"shardId":{"fragment":true,"id":-1,"index":{"fragment":false,"name":"user","uUID":"_na_"},"indexName":"user"},"shardInfo":{"failed":0,"failures":[],"fragment":false,"successful":1,"total":2},"type":"_doc","version":1}
4.2 修改文档
@Test
public void testUpdate() throws IOException {
UpdateRequest request = new UpdateRequest();
request.index("user").id("1001");
request.doc(XContentType.JSON,"realName","李思思");
UpdateResponse response = esClient.update(request, RequestOptions.DEFAULT);
log.info("插入数据结果:{}", JSON.toJSONString(response));
}
执行成功后日志输出信息
2021-11-02 15:58:09.136 INFO 4868 --- [ main] c.h.s.c.ESDocTest : 插入数据结果:{"fragment":false,"id":"1001","index":"user","primaryTerm":1,"result":"UPDATED","seqNo":1,"shardId":{"fragment":true,"id":-1,"index":{"fragment":false,"name":"user","uUID":"_na_"},"indexName":"user"},"shardInfo":{"failed":0,"failures":[],"fragment":false,"successful":1,"total":2},"type":"_doc","version":2}
4.3 查询文档
@Test
public void testSearch() throws IOException {
GetRequest request = new GetRequest();
request.index("user").id("1001");
GetResponse response = esClient.get(request, RequestOptions.DEFAULT);
String jsonString = response.getSourceAsString();
log.info("查询结果:{}",jsonString);
}
执行成功后日志输出信息
2021-11-02 16:00:47.092 INFO 4906 --- [ main] c.h.s.c.ESDocTest : 查询结果:{"erpId":null,"erpName":"zhangsansan","realName":"李思思","gender":null,"avatar":null,"phone":"12345654","email":"45456222333@qq.com","password":"13221","isDeleted":0,"priorityLevel":null,"createTime":"2021-11-02 07:54:48","updateTime":"2021-11-02 07:54:48"}
4.4 删除文档
@Test
public void testDelete() throws IOException {
DeleteRequest request = new DeleteRequest();
request.index("user").id("1001");
DeleteResponse response = esClient.delete(request, RequestOptions.DEFAULT);
log.info("删除结果:{}",JSON.toJSONString(response));
}
执行成功后日志输出信息
2021-11-02 16:01:53.527 INFO 4920 --- [ main] c.h.s.c.ESDocTest : 删除结果:{"fragment":false,"id":"1001","index":"user","primaryTerm":1,"result":"DELETED","seqNo":2,"shardId":{"fragment":true,"id":-1,"index":{"fragment":false,"name":"user","uUID":"_na_"},"indexName":"user"},"shardInfo":{"failed":0,"failures":[],"fragment":false,"successful":1,"total":2},"type":"_doc","version":3}
4.5 批量操作(新增)
@Test
public void testBatchInsert() throws IOException {
BulkRequest request =new BulkRequest();
request.add(new IndexRequest().index("user").id("1001").source(XContentType.JSON, "name", "zhangsan", "age", "10", "sex","女","birthday","2021-10-23"));
request.add(new IndexRequest().index("user").id("1002").source(XContentType.JSON, "name", "lisi", "age", "30", "sex","女","birthday","2021-10-22"));
request.add(new IndexRequest().index("user").id("1003").source(XContentType.JSON, "name", "wangwu1", "age", "40", "sex","男","birthday","2021-10-21"));
request.add(new IndexRequest().index("user").id("1004").source(XContentType.JSON, "name", "wangwu2", "age", "20", "sex","女","birthday","2021-10-20"));
request.add(new IndexRequest().index("user").id("1005").source(XContentType.JSON, "name", "wangwu3", "age", "50", "sex","男","birthday","2022-10-23"));
request.add(new IndexRequest().index("user").id("1006").source(XContentType.JSON, "name", "wangwu4", "age", "20", "sex","男","birthday","2021-10-19"));
BulkResponse response = esClient.bulk(request, RequestOptions.DEFAULT);
log.info("批处理消耗的时间{},处理结果:{}",response.getTook(),response.getItems());
}
执行成功后输出的日志信息
2021-11-02 16:16:07.391 INFO 5078 --- [ main] c.h.s.c.ESBatchTest : 批处理消耗的时间534ms,处理结果:[org.elasticsearch.action.bulk.BulkItemResponse@1d06f16f, org.elasticsearch.action.bulk.BulkItemResponse@4fa4f485, org.elasticsearch.action.bulk.BulkItemResponse@68dd39d2, org.elasticsearch.action.bulk.BulkItemResponse@4a44cfc0, org.elasticsearch.action.bulk.BulkItemResponse@60e3c26e, org.elasticsearch.action.bulk.BulkItemResponse@80b122b]
4.6 批量操作(删除)
@Test
public void testBatchDelete() throws IOException {
BulkRequest request =new BulkRequest();
request.add(new DeleteRequest().index("user").id("1001"));
request.add(new DeleteRequest().index("user").id("1002"));
request.add(new DeleteRequest().index("user").id("1003"));
BulkResponse response = esClient.bulk(request, RequestOptions.DEFAULT);
log.info("批处理消耗的时间 {}",response.getTook());
}
执行成功后输出的日志信息
2021-11-02 16:17:33.395 INFO 5095 --- [ main] c.h.s.c.ESBatchTest : 批处理消耗的时间 35ms
5. 高级查询
使用批量新增操作,插入测试数据。
@Test
public void testBatchInsert() throws IOException {
BulkRequest request =new BulkRequest();
request.add(new IndexRequest().index("user").id("1001").source(XContentType.JSON, "name", "zhangsan", "age", 10, "sex","女","birthday","2021-10-23"));
request.add(new IndexRequest().index("user").id("1002").source(XContentType.JSON, "name", "lisi", "age", 30, "sex","女","birthday","2021-10-22"));
request.add(new IndexRequest().index("user").id("1003").source(XContentType.JSON, "name", "wangwu1", "age", 40, "sex","男","birthday","2021-10-21"));
request.add(new IndexRequest().index("user").id("1004").source(XContentType.JSON, "name", "wangwu2", "age", 20, "sex","女","birthday","2021-10-20"));
request.add(new IndexRequest().index("user").id("1005").source(XContentType.JSON, "name", "wangwu3", "age", 50, "sex","男","birthday","2022-10-23"));
request.add(new IndexRequest().index("user").id("1006").source(XContentType.JSON, "name", "wangwu4", "age", 20, "sex","男","birthday","2021-10-19"));
BulkResponse response = esClient.bulk(request, RequestOptions.DEFAULT);
log.info("批处理消耗的时间{},处理结果:{}",response.getTook(),response.getItems());
}
5.1 查询所有索引数据
@Test
public void testSearchQuery() throws IOException {
SearchRequest request =new SearchRequest();
request.indices("user");
//全量查询
SearchSourceBuilder query = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
request.source(query);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
log.info("全量查询返回的结果数量:{}",hits.getTotalHits());
//循环打印匹配到的数据
for(SearchHit hit:hits){
System.out.println(hit.getSourceAsString());
}
}
执行成功后返回的结果信息
2021-11-02 16:21:02.266 INFO 5140 --- [ main] c.h.s.c.ESQueryTest : 全量查询返回的结果数量:6 hits
{"name":"wangwu2","age":"20","sex":"女","birthday":"2021-10-20"}
{"name":"wangwu3","age":"50","sex":"男","birthday":"2022-10-23"}
{"name":"wangwu4","age":"20","sex":"男","birthday":"2021-10-19"}
{"name":"zhangsan","age":"10","sex":"女","birthday":"2021-10-23"}
{"name":"lisi","age":"30","sex":"女","birthday":"2021-10-22"}
{"name":"wangwu1","age":"40","sex":"男","birthday":"2021-10-21"}
5.2 条件查询
term:查询条件为关键字
@Test
public void testSearchConditionQuery() throws IOException {
SearchRequest request =new SearchRequest();
request.indices("user");
request.source(new SearchSourceBuilder().query(QueryBuilders.termQuery("age","30")));
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
log.info("全量查询返回的结果数量:{}",hits.getTotalHits());
for(SearchHit hit:hits){
System.out.println(hit.getSourceAsString());
}
}
执行成功后返回的结果信息
2021-11-02 16:22:59.586 INFO 5162 --- [ main] c.h.s.c.ESQueryTest : 全量查询返回的结果数量:1 hits
{"name":"lisi","age":"30","sex":"女","birthday":"2021-10-22"}
5.3 分页查询
@Test
public void testLimitPageQuery() throws IOException {
SearchRequest request =new SearchRequest();
request.indices("user");
//全量查询
SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
builder.from(0);
builder.size(2);
request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
log.info("全量查询返回的结果数量:{}",hits.getTotalHits());
for(SearchHit hit:hits){
System.out.println(hit.getSourceAsString());
}
}
执行成功后返回的结果信息
2021-11-02 16:24:41.702 INFO 5177 --- [ main] c.h.s.c.ESQueryTest : 全量查询返回的结果数量:6 hits
{"name":"wangwu2","age":"20","sex":"女","birthday":"2021-10-20"}
{"name":"wangwu3","age":"50","sex":"男","birthday":"2022-10-23"}
5.4 排序
@Test
public void testOrder() throws IOException {
SearchRequest request =new SearchRequest();
request.indices("user");
//全量查询
SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
//排序
builder.sort("age", SortOrder.DESC);
request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
log.info("全量查询返回的结果数量:{}",hits.getTotalHits());
for(SearchHit hit:hits){
System.out.println(hit.getSourceAsString());
}
}
执行成功后返回的结果信息
2021-11-02 16:33:18.814 INFO 5283 --- [ main] c.h.s.c.ESQueryTest : 全量查询返回的结果数量:6 hits
{"name":"wangwu3","age":50,"sex":"男","birthday":"2022-10-23"}
{"name":"wangwu1","age":40,"sex":"男","birthday":"2021-10-21"}
{"name":"lisi","age":30,"sex":"女","birthday":"2021-10-22"}
{"name":"wangwu2","age":20,"sex":"女","birthday":"2021-10-20"}
{"name":"wangwu4","age":20,"sex":"男","birthday":"2021-10-19"}
{"name":"zhangsan","age":10,"sex":"女","birthday":"2021-10-23"}
5.5 过滤字段
@Test
public void testFilterFields() throws IOException {
SearchRequest request =new SearchRequest();
request.indices("user");
//全量查询
SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
String[] exclude = {"birthday"};
String[] includes = {"name","age"};
builder.fetchSource(includes,exclude);
request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
log.info("全量查询返回的结果数量:{}",hits.getTotalHits());
for(SearchHit hit:hits){
System.out.println(hit.getSourceAsString());
}
}
执行成功后返回的结果信息
2021-11-02 16:35:36.099 INFO 5313 --- [ main] c.h.s.c.ESQueryTest : 全量查询返回的结果数量:6 hits
{"name":"zhangsan","age":10}
{"name":"lisi","age":30}
{"name":"wangwu1","age":40}
{"name":"wangwu2","age":20}
{"name":"wangwu3","age":50}
{"name":"wangwu4","age":20}
5.6 Bool查询
@Test
public void testCombinationQuery() throws IOException {
SearchRequest request =new SearchRequest();
request.indices("user");
SearchSourceBuilder builder = new SearchSourceBuilder();
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
// 必须包含
boolQueryBuilder.must(QueryBuilders.termQuery("age", "30"));
// 一定不含
// boolQueryBuilder.mustNot(QueryBuilders.matchQuery("name", "zhangsan"));
// 可能包含
// boolQueryBuilder.should(QueryBuilders.matchQuery("sex", "男"));
builder.query(boolQueryBuilder);
request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
log.info("全量查询返回的结果数量:{}",hits.getTotalHits());
for(SearchHit hit:hits){
System.out.println(hit.getSourceAsString());
}
}
执行成功后返回的结果信息
2021-11-02 16:55:53.075 INFO 5529 --- [ main] c.h.s.c.ESQueryTest : 全量查询返回的结果数量:1 hits
{"name":"lisi","age":30,"sex":"女","birthday":"2021-10-22"}
5.7 范围查找
@Test
public void testRangeQuery() throws IOException {
SearchRequest request =new SearchRequest();
request.indices("user");
SearchSourceBuilder builder = new SearchSourceBuilder();
RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("age");
//大于等于
rangeQuery.gte(20);
//小于等于
rangeQuery.lte(40);
builder.query(rangeQuery);
request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
log.info("全量查询返回的结果数量:{}",hits.getTotalHits());
for(SearchHit hit:hits){
System.out.println(hit.getSourceAsString());
}
}
执行成功后返回的结果信息
2021-11-02 17:00:28.992 INFO 5596 --- [ main] c.h.s.c.ESQueryTest : 全量查询返回的结果数量:4 hits
{"name":"lisi","age":30,"sex":"女","birthday":"2021-10-22"}
{"name":"wangwu1","age":40,"sex":"男","birthday":"2021-10-21"}
{"name":"wangwu2","age":20,"sex":"女","birthday":"2021-10-20"}
{"name":"wangwu4","age":20,"sex":"男","birthday":"2021-10-19"}
5.8 模糊搜索
@Test
public void testFuzzyQuery() throws IOException {
SearchRequest request =new SearchRequest();
request.indices("user");
SearchSourceBuilder builder = new SearchSourceBuilder();
//Fuzziness.TWO 偏差wangwu的距离
builder.query( QueryBuilders.fuzzyQuery("name","wangwu").fuzziness(Fuzziness.ONE));
request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
log.info("查询返回的结果数量:{}",hits.getTotalHits());
for(SearchHit hit:hits){
System.out.println(hit.getSourceAsString());
}
}
执行成功后返回的结果信息
2021-11-02 17:03:12.249 INFO 5628 --- [ main] c.h.s.c.ESQueryTest : 查询返回的结果数量:4 hits
{"name":"wangwu1","age":40,"sex":"男","birthday":"2021-10-21"}
{"name":"wangwu2","age":20,"sex":"女","birthday":"2021-10-20"}
{"name":"wangwu3","age":50,"sex":"男","birthday":"2022-10-23"}
{"name":"wangwu4","age":20,"sex":"男","birthday":"2021-10-19"}
5.9 高亮查询
@Test
public void testQuery() throws IOException {
SearchRequest request =new SearchRequest();
request.indices("user");
SearchSourceBuilder builder = new SearchSourceBuilder();
//构建查询方式:高亮查询
TermsQueryBuilder termsQueryBuilder =
QueryBuilders.termsQuery("name","zhangsan");
//设置查询方式
builder.query(termsQueryBuilder);
//构建高亮字段
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.preTags("<font color='red'>");//设置标签前缀
highlightBuilder.postTags("</font>");//设置标签后缀
highlightBuilder.field("name");//设置高亮字段
//设置高亮构建对象
builder.highlighter(highlightBuilder);
//设置请求体
request.source(builder);
//3.客户端发送请求,获取响应对象
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
//4.打印响应结果
SearchHits hits = response.getHits();
System.out.println("took::"+response.getTook());
System.out.println("time_out::"+response.isTimedOut());
System.out.println("total::"+hits.getTotalHits());
System.out.println("max_score::"+hits.getMaxScore());
System.out.println("hits::::>>");
for (SearchHit hit : hits) {
String sourceAsString = hit.getSourceAsString();
System.out.println(sourceAsString);
//打印高亮结果
Map<String, HighlightField> highlightFields = hit.getHighlightFields();
System.out.println(highlightFields);
}
System.out.println("<<::::");
}
took::3ms
time_out::false
total::1 hits
max_score::1.0
hits::::>>
{"name":"zhangsan","age":10,"sex":"女","birthday":"2021-10-23"}
{name=[name], fragments[[<font color='red'>zhangsan</font>]]}
<<::::
5.10 聚合查询
- max
@Test
public void testAggregateQuery() throws IOException {
SearchRequest request = new SearchRequest().indices("user");
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.aggregation(AggregationBuilders.max("maxAge").field("age"));
//设置请求体
request.source(sourceBuilder);
//3.客户端发送请求,获取响应对象
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
//4.打印响应结果
SearchHits hits = response.getHits();
log.info("查询返回的结果数量:{}",hits.getTotalHits());
for(SearchHit hit:hits){
System.out.println(hit.getSourceAsString());
}
}
执行成功返回的结果
{"took":1,"timed_out":false,"_shards":{"total":1,"successful":1,"skipped":0,"failed":0},"hits":{"total":{"value":6,"relation":"eq"},"max_score":1.0,"hits":[{"_index":"user","_type":"_doc","_id":"1001","_score":1.0,"_source":{"name":"zhangsan","age":10,"sex":"女","birthday":"2021-10-23"}},{"_index":"user","_type":"_doc","_id":"1002","_score":1.0,"_source":{"name":"lisi","age":30,"sex":"女","birthday":"2021-10-22"}},{"_index":"user","_type":"_doc","_id":"1003","_score":1.0,"_source":{"name":"wangwu1","age":40,"sex":"男","birthday":"2021-10-21"}},{"_index":"user","_type":"_doc","_id":"1004","_score":1.0,"_source":{"name":"wangwu2","age":20,"sex":"女","birthday":"2021-10-20"}},{"_index":"user","_type":"_doc","_id":"1005","_score":1.0,"_source":{"name":"wangwu3","age":50,"sex":"男","birthday":"2022-10-23"}},{"_index":"user","_type":"_doc","_id":"1006","_score":1.0,"_source":{"name":"wangwu4","age":20,"sex":"男","birthday":"2021-10-19"}}]},"aggregations":{"max#maxAge":{"value":50.0}}}
可以看到"aggregations":{"max#maxAge":{"value":50.0}}
-
条件分组
@Test public void testGroupSearch() throws IOException { SearchRequest request = new SearchRequest("user"); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.aggregation(AggregationBuilders.terms("age_groupby").field("age")); //设置请求体 request.source(sourceBuilder); //3.客户端发送请求,获取响应对象 SearchResponse response = esClient.search(request, RequestOptions.DEFAULT); log.info("查询返回的结果{}", JSON.toJSONString(response)); }
执行成功返回的结果
2021-11-02 17:14:35.396 INFO 5771 --- [ main] c.h.s.c.ESQueryTest : 查询返回的结果{"aggregations":{"asMap":{"age_groupby":{"buckets":[{"aggregations":{"asMap":{},"fragment":true},"docCount":2,"docCountError":0,"fragment":true,"key":20,"keyAsNumber":20,"keyAsString":"20"},{"aggregations":{"asMap":{},"fragment":true},"docCount":1,"docCountError":0,"fragment":true,"key":10,"keyAsNumber":10,"keyAsString":"10"},{"aggregations":{"asMap":{},"fragment":true},"docCount":1,"docCountError":0,"fragment":true,"key":30,"keyAsNumber":30,"keyAsString":"30"},{"aggregations":{"asMap":{},"fragment":true},"docCount":1,"docCountError":0,"fragment":true,"key":40,"keyAsNumber":40,"keyAsString":"40"},{"aggregations":{"asMap":{},"fragment":true},"docCount":1,"docCountError":0,"fragment":true,"key":50,"keyAsNumber":50,"keyAsString":"50"}],"docCountError":0,"fragment":true,"name":"age_groupby","sumOfOtherDocCounts":0,"type":"lterms"}},"fragment":true},"clusters":{"fragment":true,"skipped":0,"successful":0,"total":0},"failedShards":0,"fragment":false,"hits":{"fragment":true,"hits":[{"fields":{},"fragment":false,"highlightFields":{},"id":"1001","matchedQueries":[],"primaryTerm":0,"rawSortValues":[],"score":1.0,"seqNo":-2,"sortValues":[],"sourceAsMap":{"birthday":"2021-10-23","sex":"女","name":"zhangsan","age":10},"sourceAsString":"{\"name\":\"zhangsan\",\"age\":10,\"sex\":\"女\",\"birthday\":\"2021-10-23\"}","sourceRef":{"fragment":true},"type":"_doc","version":-1},{"fields":{},"fragment":false,"highlightFields":{},"id":"1002","matchedQueries":[],"primaryTerm":0,"rawSortValues":[],"score":1.0,"seqNo":-2,"sortValues":[],"sourceAsMap":{"birthday":"2021-10-22","sex":"女","name":"lisi","age":30},"sourceAsString":"{\"name\":\"lisi\",\"age\":30,\"sex\":\"女\",\"birthday\":\"2021-10-22\"}","sourceRef":{"fragment":true},"type":"_doc","version":-1},{"fields":{},"fragment":false,"highlightFields":{},"id":"1003","matchedQueries":[],"primaryTerm":0,"rawSortValues":[],"score":1.0,"seqNo":-2,"sortValues":[],"sourceAsMap":{"birthday":"2021-10-21","sex":"男","name":"wangwu1","age":40},"sourceAsString":"{\"name\":\"wangwu1\",\"age\":40,\"sex\":\"男\",\"birthday\":\"2021-10-21\"}","sourceRef":{"fragment":true},"type":"_doc","version":-1},{"fields":{},"fragment":false,"highlightFields":{},"id":"1004","matchedQueries":[],"primaryTerm":0,"rawSortValues":[],"score":1.0,"seqNo":-2,"sortValues":[],"sourceAsMap":{"birthday":"2021-10-20","sex":"女","name":"wangwu2","age":20},"sourceAsString":"{\"name\":\"wangwu2\",\"age\":20,\"sex\":\"女\",\"birthday\":\"2021-10-20\"}","sourceRef":{"fragment":true},"type":"_doc","version":-1},{"fields":{},"fragment":false,"highlightFields":{},"id":"1005","matchedQueries":[],"primaryTerm":0,"rawSortValues":[],"score":1.0,"seqNo":-2,"sortValues":[],"sourceAsMap":{"birthday":"2022-10-23","sex":"男","name":"wangwu3","age":50},"sourceAsString":"{\"name\":\"wangwu3\",\"age\":50,\"sex\":\"男\",\"birthday\":\"2022-10-23\"}","sourceRef":{"fragment":true},"type":"_doc","version":-1},{"fields":{},"fragment":false,"highlightFields":{},"id":"1006","matchedQueries":[],"primaryTerm":0,"rawSortValues":[],"score":1.0,"seqNo":-2,"sortValues":[],"sourceAsMap":{"birthday":"2021-10-19","sex":"男","name":"wangwu4","age":20},"sourceAsString":"{\"name\":\"wangwu4\",\"age\":20,\"sex\":\"男\",\"birthday\":\"2021-10-19\"}","sourceRef":{"fragment":true},"type":"_doc","version":-1}],"maxScore":1.0,"totalHits":{"relation":"EQUAL_TO","value":6}},"numReducePhases":1,"profileResults":{},"shardFailures":[],"skippedShards":0,"successfulShards":1,"timedOut":false,"took":{"days":0,"daysFrac":9.259259259259259E-8,"hours":0,"hoursFrac":2.222222222222222E-6,"micros":8000,"microsFrac":8000.0,"millis":8,"millisFrac":8.0,"minutes":0,"minutesFrac":1.3333333333333334E-4,"nanos":8000000,"seconds":0,"secondsFrac":0.008,"stringRep":"8ms"},"totalShards":1
将查询到的信息格式化后可以看到group_by之后的信息