我看到希望,哪怕只有微小的一束光,我也会拼尽全力去寻找.
上一章简单介绍了 ES 聚合查询(四) , 如果没有看过,请观看上一章
我们之前都是使用 Postman 请求来操作索引,操作文档,查询数据的, 这一章节,老蝴蝶使用 Java Api 进行处理.
一. 简单的 Java API ES 环境搭建
一.一 添加 pom.xml 依赖
org.elasticsearch
elasticsearch
7.8.0
org.elasticsearch.client
elasticsearch-rest-high-level-client
7.8.0
junit
junit
一.二 application.yml 配置文件
server:
port: 8081
servlet:
context-path: /ES
一.三 客户端对象 **RestHighLevelClient ** 构建
public static final String ES_HOST = "127.0.0.1";
public static final int ES_PORT = 9200;
public static final String ES_SCHEMA = "http";
private RestHighLevelClient restHighLevelClient;
@Before
public void initClient() {
restHighLevelClient = new RestHighLevelClient(RestClient.builder(new HttpHost(ES_HOST, ES_PORT, ES_SCHEMA)));
}
一.四 创建连接 简单测试
/**
* 创建连接
*/
@Test
public void createClient() throws IOException {
// 创建restClient 连接
RestClientBuilder httpClient = RestClient.builder(new HttpHost(ES_HOST, ES_PORT, ES_SCHEMA));
//引用
RestHighLevelClient restHighLevelClient = new RestHighLevelClient(httpClient);
// 成功
log.info(">>>创建连接 成功,{}", restHighLevelClient);
restHighLevelClient.close();
}
测试运行:
10:13:43.171 [main] INFO top.yueshushu.IndexTest - >>>创建连接 成功,org.elasticsearch.client.RestHighLevelClient@55fe41ea
10:13:43.174 [main] DEBUG org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager - Connection manager is shutting down
10:13:43.195 [main] DEBUG org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager - Connection manager shut down
二. 索引操作
二.一 创建索引
创建 user 索引, 使用 CreateIndexRequest
@Test
public void createIndexTest() throws Exception {
//创建索引
CreateIndexRequest createIndexRequest = new CreateIndexRequest("user");
//发送请求,获取响应
CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
//获取响应信息
log.info("创建索引响应数据 :{}", createIndexResponse.toString());
boolean acknowledged = createIndexResponse.isAcknowledged();
log.info(">>> 操作是否成功 :{}", acknowledged ? "成功" : "失败");
}
索引创建成功
10:16:04.341 [main] INFO top.yueshushu.IndexTest - 创建索引响应数据 :org.elasticsearch.client.indices.CreateIndexResponse@4a7a6a
10:16:04.342 [main] INFO top.yueshushu.IndexTest - >>> 操作是否成功 :成功
二.二 查询索引
使用 GetIndexRequest
/**
* 查询索引
*/
@Test
public void showIndexTest() throws Exception {
GetIndexRequest getIndexRequest = new GetIndexRequest("user");
// 进行请求
GetIndexResponse getIndexResponse = restHighLevelClient.indices().get(getIndexRequest, RequestOptions.DEFAULT);
// 获取请求响应
log.info("获取索引别名:{}", getIndexResponse.getAliases());
log.info("获取索引的设置:{}", getIndexResponse.getSettings());
log.info("获取索引的映射:{}", getIndexResponse.getMappings());
// 查询之前的 student 索引
GetIndexRequest getIndexRequest2 = new GetIndexRequest("student");
// 进行请求
GetIndexResponse getIndexResponse2 = restHighLevelClient.indices().get(getIndexRequest2, RequestOptions.DEFAULT);
// 获取请求响应
log.info("获取索引别名:{}", getIndexResponse2.getAliases());
log.info("获取索引的设置:{}", getIndexResponse2.getSettings());
log.info("获取索引的映射:{}", getIndexResponse2.getMappings());
}
测试:
10:17:10.819 [main] INFO top.yueshushu.IndexTest - 获取索引别名:{user=[]}
10:17:10.820 [main] INFO top.yueshushu.IndexTest - 获取索引的设置:{user={"index.creation_date":"1681092964180","index.number_of_replicas":"1","index.number_of_shards":"1","index.provided_name":"user","index.uuid":"w67Cvzf6SSepW0WZDdfQ5A","index.version.created":"7080099"}}
10:17:10.821 [main] INFO top.yueshushu.IndexTest - 获取索引的映射:{user=org.elasticsearch.cluster.metadata.MappingMetadata@e5d4e968}
10:17:10.826 [main] INFO top.yueshushu.IndexTest - 获取索引别名:{student=[]}
10:17:10.826 [main] INFO top.yueshushu.IndexTest - 获取索引的设置:{student={"index.creation_date":"1680782306132","index.number_of_replicas":"1","index.number_of_shards":"1","index.provided_name":"student","index.uuid":"RlGnGZsCRkGReDhMUx7gDA","index.version.created":"7080099"}}
10:17:10.826 [main] INFO top.yueshushu.IndexTest - 获取索引的映射:{student=org.elasticsearch.cluster.metadata.MappingMetadata@73fad4a4}
二.三 删除索引
使用 DeleteIndexRequest
/**
* 删除索引
*/
@Test
public void deleteIndexTest() throws Exception {
DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("user");
AcknowledgedResponse acknowledgedResponse = restHighLevelClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
boolean acknowledged = acknowledgedResponse.isAcknowledged();
log.info("删除索引 {}", acknowledged ? "成功" : "失败");
}
成功删除了索引 user
10:20:17.047 [main] INFO top.yueshushu.IndexTest - 删除索引 成功
三. 文档操作
先创建一下 user 索引, 再进行文档操作
使用到的 对象 User
@Data
public class User implements Serializable {
private Integer id;
private String name;
private String nickName;
private Integer age;
private String sex;
private String description;
}
三.一 创建文档
private RestHighLevelClient restHighLevelClient;
@Before
public void initClient() {
RestClientBuilder restClientBuilder = RestClient.builder(new HttpHost("127.0.0.1", 9200, "http"));
restHighLevelClient = new RestHighLevelClient(restClientBuilder);
}
/**
* 添加文档
*/
@Test
public void createDocumentTest() throws Exception {
//1. 创建索引请求
IndexRequest indexRequest = new IndexRequest();
// 进行绑定,并指定 id
indexRequest.index("user").id("1");
// 构建数据,序列化成 json
User user = generateUser();
ObjectMapper objectMapper = new ObjectMapper();
String userJson = objectMapper.writeValueAsString(user);
// 请求中写入 source
indexRequest.source(userJson, XContentType.JSON);
IndexResponse indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
log.info("获取信息:{}", indexResponse.toString());
log.info("获取 _index:{}", indexResponse.getIndex());
log.info("获取 _id:{}", indexResponse.getId());
log.info("获取结果:{}", indexResponse.getResult().toString());
}
private User generateUser() {
User user = new User();
user.setId(1);
user.setName("岳泽霖");
user.setNickName("岳泽霖");
user.setAge(28);
user.setSex("男");
user.setDescription("一个快乐的程序员呀呀");
return user;
}
10:24:45.353 [main] INFO top.yueshushu.DocumentTest - 获取信息:IndexResponse[index=user,type=_doc,id=1,version=1,result=created,seqNo=0,primaryTerm=1,shards={"total":2,"successful":1,"failed":0}]
10:24:45.354 [main] INFO top.yueshushu.DocumentTest - 获取 _index:user
10:24:45.354 [main] INFO top.yueshushu.DocumentTest - 获取 _id:1
10:24:45.354 [main] INFO top.yueshushu.DocumentTest - 获取结果:CREATED
三.二 更新文档
使用 UpdateRequest
/**
* 更新文档操作
*/
@Test
public void updateDocumentTest() throws Exception {
UpdateRequest updateRequest = new UpdateRequest();
// .id 为指定文档的 id
updateRequest.index("user").id("1");
updateRequest.doc(XContentType.JSON, "name", "两个蝴蝶飞", "age", 29);
// 进行更新操作
UpdateResponse updateResponse = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
log.info("获取信息:{}", updateResponse.toString());
log.info("获取 _index:{}", updateResponse.getIndex());
log.info("获取 _id:{}", updateResponse.getId());
log.info("获取结果:{}", updateResponse.getResult().toString());
}
10:26:39.524 [main] INFO top.yueshushu.DocumentTest - 获取信息:UpdateResponse[index=user,type=_doc,id=1,version=2,seqNo=1,primaryTerm=1,result=updated,shards=ShardInfo{total=2, successful=1, failures=[]}]
10:26:39.524 [main] INFO top.yueshushu.DocumentTest - 获取 _index:user
10:26:39.524 [main] INFO top.yueshushu.DocumentTest - 获取 _id:1
10:26:39.524 [main] INFO top.yueshushu.DocumentTest - 获取结果:UPDATED
再次查询时:
三.三 查询文档
使用 GetRequest
@Test
public void getDocumentTest() throws Exception {
GetRequest getRequest = new GetRequest();
getRequest.index("user").id("1");
//获取请求信息
GetResponse getResponse = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
// 获取信息
log.info(">>获取响应信息:{}", getResponse);
log.info(">> 获取 _id:{}", getResponse.getId());
log.info(">>>获取 _index:{}", getResponse.getIndex());
log.info(">>>获取类型 :{}", getResponse.getType());
log.info(">>>获取资源信息:{}", getResponse.getSourceAsString());
}
10:28:19.281 [main] INFO top.yueshushu.DocumentTest - >>获取响应信息:{"_index":"user","_type":"_doc","_id":"1","_version":2,"_seq_no":1,"_primary_term":1,"found":true,"_source":{"id":1,"name":"两个蝴蝶飞","nickName":"岳泽霖","age":29,"sex":"男","description":"一个快乐的程序员呀呀"}}
10:28:19.297 [main] INFO top.yueshushu.DocumentTest - >> 获取 _id:1
10:28:19.297 [main] INFO top.yueshushu.DocumentTest - >>>获取 _index:user
10:28:19.297 [main] INFO top.yueshushu.DocumentTest - >>>获取类型 :_doc
10:28:19.297 [main] INFO top.yueshushu.DocumentTest - >>>获取资源信息:{"id":1,"name":"两个蝴蝶飞","nickName":"岳泽霖","age":29,"sex":"男","description":"一个快乐的程序员呀呀"}
三.四 删除文档
/**
* 删除文档
*/
@Test
public void deleteDocumentTest() throws Exception {
DeleteRequest deleteRequest = new DeleteRequest();
deleteRequest.index("user").id("1");
DeleteResponse deleteResponse = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
log.info(">>> 删除响应结果:{}", deleteResponse.toString());
}
10:29:03.775 [main] INFO top.yueshushu.DocumentTest - >>> 删除响应结果:DeleteResponse[index=user,type=_doc,id=1,version=3,result=deleted,shards=ShardInfo{total=2, successful=1, failures=[]}]
再次查询时:
三.五 批量添加文档
使用 BulkRequest , 将多个请求 合并在一起
@Test
public void batchAddTest() throws Exception {
//1. 定义 BulkRequest 用于封装
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.add(
new IndexRequest().index("user").id("3")
.source(XContentType.JSON, "name", "岳建立")
);
bulkRequest.add(
new IndexRequest()
.index("user").id("4")
.source(XContentType.JSON, "name", "泽霖")
);
bulkRequest.add(
new IndexRequest()
.index("user").id("5")
.source(XContentType.JSON, "name", "建立")
);
// 响应信息
BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
log.info(">>> 获取响应:{}", bulkResponse);
log.info("获取 took 花费时长:{}", bulkResponse.getTook());
Arrays.stream(bulkResponse.getItems()).forEach(
n -> log.info(">>>>> {}", n)
);
}
10:30:29.769 [main] INFO top.yueshushu.DocumentTest - >>> 获取响应:org.elasticsearch.action.bulk.BulkResponse@480d3575
10:30:29.770 [main] INFO top.yueshushu.DocumentTest - 获取 took 花费时长:21ms
10:30:29.770 [main] INFO top.yueshushu.DocumentTest - >>>>> org.elasticsearch.action.bulk.BulkItemResponse@72c8e7b
10:30:29.770 [main] INFO top.yueshushu.DocumentTest - >>>>> org.elasticsearch.action.bulk.BulkItemResponse@65f8f5ae
10:30:29.770 [main] INFO top.yueshushu.DocumentTest - >>>>> org.elasticsearch.action.bulk.BulkItemResponse@431cd9b2
查询:
三.六 批量删除操作
@Test
public void batchDeleteTest() throws Exception {
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.add(new DeleteRequest().index("user").id("3"));
bulkRequest.add(new DeleteRequest().index("user").id("4"));
bulkRequest.add(new DeleteRequest().index("user").id("5"));
BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
log.info(">>> 花费时长:{}", bulkResponse.getTook());
//设置信息:
Arrays.stream(bulkResponse.getItems()).forEach(
n -> log.info(">>>>> {}", n.getResponse())
);
}
10:32:47.118 [main] INFO top.yueshushu.DocumentTest - >>> 花费时长:23ms
10:32:47.119 [main] INFO top.yueshushu.DocumentTest - >>>>> DeleteResponse[index=user,type=_doc,id=3,version=2,result=deleted,shards=ShardInfo{total=2, successful=1, failures=[]}]
10:32:47.119 [main] INFO top.yueshushu.DocumentTest - >>>>> DeleteResponse[index=user,type=_doc,id=4,version=2,result=deleted,shards=ShardInfo{total=2, successful=1, failures=[]}]
10:32:47.119 [main] INFO top.yueshushu.DocumentTest - >>>>> DeleteResponse[index=user,type=_doc,id=5,version=2,result=deleted,shards=ShardInfo{total=2, successful=1, failures=[]}]
再次查询:
四. 复杂查询处理
批量添加数据, 与 第三章节的数据是一致的, 只是索引由 student 换成了 user
@Test
public void batchAddTest() throws Exception {
//1. 定义 BulkRequest 用于封装
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.add(
new IndexRequest().index("user").id("1")
.source(XContentType.JSON, "name", "岳泽霖","nickname", "小泽霖","sex","男","age",28)
);
bulkRequest.add(
new IndexRequest().index("user").id("2")
.source(XContentType.JSON, "name", "岳建立","nickname", "小建立","sex","男","age",26)
);
bulkRequest.add(
new IndexRequest().index("user").id("3")
.source(XContentType.JSON, "name", "张三","nickname", "张三","sex","男","age",24)
);
bulkRequest.add(
new IndexRequest().index("user").id("4")
.source(XContentType.JSON, "name", "李四","nickname", "李四","sex","女","age",24)
);
bulkRequest.add(
new IndexRequest().index("user").id("5")
.source(XContentType.JSON, "name", "王二","nickname", "王二","sex","女","age",16)
);
// 响应信息
BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
log.info(">>> 获取响应:{}", bulkResponse);
}
查询使用的是 SearchRequest , 可以通过 SearchSourceBuilder 构造查询条件
四.一 全部查询
/**
* 全部查询
*
* findAll
*/
@Test
public void findAllTest() throws Exception {
SearchRequest searchRequest = new SearchRequest();
// 设置索引
searchRequest.indices("user");
/**
构建条件
*/
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
searchRequest.source(searchSourceBuilder);
// 进行请求
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHits result = searchResponse.getHits();
log.info(">>> 花费的时间:{}", searchResponse.getTook());
log.info(">>>是否超时:{}", searchResponse.isTimedOut());
log.info(">>>> 总的数量:{}", result.getTotalHits());
log.info(">>>>最大的匹配分数值:{}", result.getMaxScore());
log.info(">>>>查询结果输出开始");
Arrays.stream(result.getHits()).forEach(
n -> log.info(">>>获取内容:{}", n.getSourceAsString())
);
log.info(">>>> 查询结果输出结束");
}
四.二 单条件查询
/**
* 单条件查询, 类似于 age =
* term 为 =
*/
@Test
public void getByAgeTest() throws Exception {
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices("user");
// 构建条件
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.termQuery("age", 28));
searchRequest.source(searchSourceBuilder);
// 进行查询
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
// 查询查询的内容
SearchHits result = searchResponse.getHits();
log.info(">>>> 花费的时间:{}", searchResponse.getTook());
log.info(">>> 是否超时:{}", searchResponse.isTimedOut());
log.info(">>>>总的数量:{}", result.getTotalHits());
log.info(">>>>最大匹配值:{}", result.getMaxScore());
log.info(">>>>查询结果输出开始");
Arrays.stream(result.getHits()).forEach(
n -> {
log.info(">>>> 内容:{}", n.getSourceAsString());
log.info(">>>> 内容:{}", n.getSourceAsMap());
}
);
log.info(">>>>查询结果输出结束");
}
四.三 分页查询
/**
* 分页处理
*
* 分页, limit startIndex, length
*/
@Test
public void pageTest() throws Exception {
SearchRequest searchRequest = new SearchRequest();
// 设置索引
searchRequest.indices("user");
/**
构建条件
*/
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
// 进行分页
searchSourceBuilder.from((2 - 1) * 2);
searchSourceBuilder.size(2);
searchRequest.source(searchSourceBuilder);
// 进行请求
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHits result = searchResponse.getHits();
log.info(">>> 花费的时间:{}", searchResponse.getTook());
log.info(">>>是否超时:{}", searchResponse.isTimedOut());
log.info(">>>> 总的数量:{}", result.getTotalHits());
log.info(">>>>最大的匹配分数值:{}", result.getMaxScore());
log.info(">>>>查询结果输出开始");
Arrays.stream(result.getHits()).forEach(
n -> {
log.info(">>>获取内容:{}", n.getSourceAsString());
}
);
log.info(">>>> 查询结果输出结束");
}
四.四 排序
/**
* 排序处理
*
* 排序, order by ...
*/
@Test
public void orderByTest() throws Exception {
SearchRequest searchRequest = new SearchRequest();
// 设置索引
searchRequest.indices("user");
/**
构建条件
*/
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
// 按照年龄降序
searchSourceBuilder.sort("age", SortOrder.DESC);
// 进行分页
// searchSourceBuilder.from((2-1)*2);
// searchSourceBuilder.size(2);
searchRequest.source(searchSourceBuilder);
// 进行请求
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHits result = searchResponse.getHits();
log.info(">>> 花费的时间:{}", searchResponse.getTook());
log.info(">>>是否超时:{}", searchResponse.isTimedOut());
log.info(">>>> 总的数量:{}", result.getTotalHits());
log.info(">>>>最大的匹配分数值:{}", result.getMaxScore());
log.info(">>>>查询结果输出开始");
Arrays.stream(result.getHits()).forEach(
n -> {
log.info(">>>获取内容:{}", n.getSourceAsString());
}
);
log.info(">>>> 查询结果输出结束");
}
四.五 只展示 或者排除部分字段
/**
* 只展示,或者排除某些字段
*
* select 字段1,字段2 from 表名
*/
@Test
public void includeTest() throws Exception {
SearchRequest searchRequest = new SearchRequest();
// 设置索引
searchRequest.indices("user");
/**
构建条件
*/
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
String[] includes = {"id", "name"};
String[] excludes = {};
searchSourceBuilder.fetchSource(includes, excludes);
// 按照年龄降序
searchSourceBuilder.sort("age", SortOrder.DESC);
searchRequest.source(searchSourceBuilder);
// 进行请求
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHits result = searchResponse.getHits();
log.info(">>> 花费的时间:{}", searchResponse.getTook());
log.info(">>>是否超时:{}", searchResponse.isTimedOut());
log.info(">>>> 总的数量:{}", result.getTotalHits());
log.info(">>>>最大的匹配分数值:{}", result.getMaxScore());
log.info(">>>>查询结果输出开始");
Arrays.stream(result.getHits()).forEach(
n -> {
log.info(">>>获取内容:{}", n.getSourceAsString());
}
);
log.info(">>>> 查询结果输出结束");
}
四.六 bool 组合查询
/**
* bool 查询
*/
@Test
public void boolTest() throws Exception {
SearchRequest searchRequest = new SearchRequest();
// 设置索引
searchRequest.indices("user");
/**
构建条件
*/
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
// 必须是
boolQueryBuilder.must(QueryBuilders.matchQuery("age", 24));
// 一定不能是
boolQueryBuilder.mustNot(QueryBuilders.matchQuery("sex", "女"));
//可能是
boolQueryBuilder.should(QueryBuilders.matchQuery("name", "岳泽霖"));
searchSourceBuilder.query(boolQueryBuilder);
// 按照年龄降序
searchSourceBuilder.sort("age", SortOrder.DESC);
// 进行分页
// searchSourceBuilder.from((2-1)*2);
// searchSourceBuilder.size(2);
searchRequest.source(searchSourceBuilder);
// 进行请求
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHits result = searchResponse.getHits();
log.info(">>> 花费的时间:{}", searchResponse.getTook());
log.info(">>>是否超时:{}", searchResponse.isTimedOut());
log.info(">>>> 总的数量:{}", result.getTotalHits());
log.info(">>>>最大的匹配分数值:{}", result.getMaxScore());
log.info(">>>>查询结果输出开始");
Arrays.stream(result.getHits()).forEach(
n -> {
log.info(">>>获取内容:{}", n.getSourceAsString());
}
);
log.info(">>>> 查询结果输出结束");
}
四.七 range 范围查询
/**
* range 范围查询, between and
*/
@Test
public void rangeTest() throws Exception {
SearchRequest searchRequest = new SearchRequest();
// 设置索引
searchRequest.indices("user");
/**
构建条件
*/
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("age");
rangeQueryBuilder.gte(24);
rangeQueryBuilder.lte(30);
searchSourceBuilder.query(rangeQueryBuilder);
// 按照年龄降序
searchSourceBuilder.sort("age", SortOrder.DESC);
// 进行分页
// searchSourceBuilder.from((2-1)*2);
// searchSourceBuilder.size(2);
searchRequest.source(searchSourceBuilder);
// 进行请求
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHits result = searchResponse.getHits();
log.info(">>> 花费的时间:{}", searchResponse.getTook());
log.info(">>>是否超时:{}", searchResponse.isTimedOut());
log.info(">>>> 总的数量:{}", result.getTotalHits());
log.info(">>>>最大的匹配分数值:{}", result.getMaxScore());
log.info(">>>>查询结果输出开始");
Arrays.stream(result.getHits()).forEach(
n -> {
log.info(">>>获取内容:{}", n.getSourceAsString());
}
);
log.info(">>>> 查询结果输出结束");
}
四.八 like 模糊查询
/**
* like 模糊查询
*/
@Test
public void likeTest() throws Exception {
SearchRequest searchRequest = new SearchRequest();
// 设置索引
searchRequest.indices("user");
/**
构建条件
*/
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// 模糊几个 ,一个.
FuzzyQueryBuilder fuzzyQueryBuilder = QueryBuilders.fuzzyQuery("name", "岳泽");
fuzzyQueryBuilder.fuzziness(Fuzziness.ONE);
searchSourceBuilder.query(fuzzyQueryBuilder);
// 按照年龄降序
searchSourceBuilder.sort("age", SortOrder.DESC);
// 进行分页
// searchSourceBuilder.from((2-1)*2);
// searchSourceBuilder.size(2);
searchRequest.source(searchSourceBuilder);
// 进行请求
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHits result = searchResponse.getHits();
log.info(">>> 花费的时间:{}", searchResponse.getTook());
log.info(">>>是否超时:{}", searchResponse.isTimedOut());
log.info(">>>> 总的数量:{}", result.getTotalHits());
log.info(">>>>最大的匹配分数值:{}", result.getMaxScore());
log.info(">>>>查询结果输出开始");
Arrays.stream(result.getHits()).forEach(
n -> {
log.info(">>>获取内容:{}", n.getSourceAsString());
}
);
log.info(">>>> 查询结果输出结束");
}
四.九 高亮展示
/**
* hight 高亮展示
*/
@Test
public void hightTest() throws Exception {
SearchRequest searchRequest = new SearchRequest();
// 设置索引
searchRequest.indices("user");
/**
构建条件
*/
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// 模糊几个 ,一个.
// 模糊几个 ,一个.
FuzzyQueryBuilder fuzzyQueryBuilder = QueryBuilders.fuzzyQuery("name", "岳泽");
fuzzyQueryBuilder.fuzziness(Fuzziness.ONE);
searchSourceBuilder.query(fuzzyQueryBuilder);
// 按照年龄降序
searchSourceBuilder.sort("age", SortOrder.DESC);
// 进行分页
// searchSourceBuilder.from((2-1)*2);
// searchSourceBuilder.size(2);
// 构建 hight
HighlightBuilder highlightBuilder = new HighlightBuilder();
// 前缀
highlightBuilder.preTags("");
//后缀
highlightBuilder.postTags("");
//高亮字段
highlightBuilder.field("name");
searchSourceBuilder.highlighter(highlightBuilder);
searchRequest.source(searchSourceBuilder);
// 进行请求
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHits result = searchResponse.getHits();
log.info(">>> 花费的时间:{}", searchResponse.getTook());
log.info(">>>是否超时:{}", searchResponse.isTimedOut());
log.info(">>>> 总的数量:{}", result.getTotalHits());
log.info(">>>>最大的匹配分数值:{}", result.getMaxScore());
log.info(">>>>查询结果输出开始");
Arrays.stream(result.getHits()).forEach(
n -> {
log.info(">>>获取内容:{}", n.getSourceAsString());
Map highlightFields = n.getHighlightFields();
highlightFields.entrySet().forEach(
hn -> {
System.out.println(hn.getKey() + "," + hn.getValue().getName());
}
);
}
);
log.info(">>>> 查询结果输出结束");
log.info(searchResponse.toString());
}
四.十 聚合处理
/**
* 聚合处理
*/
@Test
public void aggreTest() throws Exception {
SearchRequest searchRequest = new SearchRequest();
// 设置索引
searchRequest.indices("user");
/**
构建条件
*/
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
searchSourceBuilder.aggregation(AggregationBuilders.max("maxAge").field("age"));
searchSourceBuilder.aggregation(AggregationBuilders.min("minAge").field("age"));
searchSourceBuilder.aggregation(AggregationBuilders.sum("sumAge").field("age"));
searchSourceBuilder.aggregation(AggregationBuilders.avg("avgAge").field("age"));
// 按照年龄降序
searchSourceBuilder.sort("age", SortOrder.DESC);
searchRequest.source(searchSourceBuilder);
// 进行请求
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHits result = searchResponse.getHits();
log.info(">>> 花费的时间:{}", searchResponse.getTook());
log.info(">>>是否超时:{}", searchResponse.isTimedOut());
log.info(">>>> 总的数量:{}", result.getTotalHits());
log.info(">>>>最大的匹配分数值:{}", result.getMaxScore());
log.info(">>>>查询结果输出开始");
Arrays.stream(result.getHits()).forEach(
n -> {
log.info(">>>获取内容:{}", n.getSourceAsString());
}
);
log.info(">>>> 查询结果输出结束");
log.info(searchResponse.toString());
}
四.十一 分组统计
/**
* 分组统计 select age,count(1) from user group by age
*
*/
@Test
public void groupTest() throws Exception {
SearchRequest searchRequest = new SearchRequest();
// 设置索引
searchRequest.indices("user");
/**
构建条件
*/
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
searchSourceBuilder.aggregation(AggregationBuilders.terms("age_groupby").field("age"));
// 按照年龄降序
searchSourceBuilder.sort("age", SortOrder.DESC);
searchRequest.source(searchSourceBuilder);
// 进行请求
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHits result = searchResponse.getHits();
log.info(">>> 花费的时间:{}", searchResponse.getTook());
log.info(">>>是否超时:{}", searchResponse.isTimedOut());
log.info(">>>> 总的数量:{}", result.getTotalHits());
log.info(">>>>最大的匹配分数值:{}", result.getMaxScore());
log.info(">>>>查询结果输出开始");
Arrays.stream(result.getHits()).forEach(
n -> {
log.info(">>>获取内容:{}", n.getSourceAsString());
}
);
log.info(">>>> 查询结果输出结束");
log.info(searchResponse.toString());
}
Java API 关于 ES 的基本操作就这些, 大家会发现, 处理起来很麻烦, 下一章节 引入 data-es 就会发现, 会简单很多.
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net
机房租用,北京机房租用,IDC机房托管, http://www.e1idc.net