Elasticsearch RestHighLevelClient
注:6.x版本API,若是最新7.x版本,可以适当修改
1,创建索引
CreateIndexRequest request = new CreateIndexRequest(indexName);
// 添加分片和备份参数
if (indexSetting != null) {
request.settings(Settings.builder()
.put(“index.number_of_shards”, indexSetting.get(“index.number_of_shards”))
.put(“index.number_of_replicas”, indexSetting.get(“index.number_of_replicas”))
);
}
// 设置mapping属性
if (indexSetting != null) {
request.mapping("_doc", mappingSetting);
}
// 添加别名
if (alias != null) {
request.alias(new Alias(alias));
}
//创建索引
CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(request);
//判断索引是否创建成功
createIndexResponse.isAcknowledged();
2,删除索引
DeleteIndexRequest request = new DeleteIndexRequest(indexName);
DeleteIndexResponse response = restHighLevelClient.indices().delete(request);
boolean deleteSuccess = response.isAcknowledged();
3,判断索引是否存在
GetIndexRequest request = new GetIndexRequest();
request.indices(indexName);
boolean exists = restHighLevelClient.indices().exists(request);
4,新增文档
IndexRequest request = new IndexRequest(indexName, type, docId);
request.source(jsonMap)
.timeout(TimeValue.timeValueMinutes(1L))
.opType(“create”);
IndexResponse response = restHighLevelClient.index(request);
5,根据 _id 更新文档
UpdateRequest request = new UpdateRequest(indexName, type, docId);
request.doc(jsonMap);
UpdateResponse response = restHighLevelClient.update(request);
6,根据docId更新/插入字段内容
// 更新插入
UpdateRequest request = new UpdateRequest(indexName, type, docId)
.doc(jsonMap)
.upsert(jsonMap);
UpdateResponse response = restHighLevelClient.update(request);
7,判断文档是否存在
GetRequest request = new GetRequest(indexName, type, docId);
request.fetchSourceContext(FetchSourceContext.DO_NOT_FETCH_SOURCE);
request.storedFields(“none”);
boolean exists = restHighLevelClient.exists(request);
8,删除doc文档
DeleteRequest deleteRequest = new DeleteRequest(indexName,type,docId);
restHighLevelClient.delete(deleteRequest);
9,根据 _id 查询doc文档
GetRequest request = new GetRequest(indexName, type, docId);
// 是否返回全部字段,如是,则 fetchFields 参数无效
if (!fetchAllFields) {
request.fetchSourceContext(new FetchSourceContext(true, fetchFields, Strings.EMPTY_ARRAY));
}
GetResponse response = restHighLevelClient.get(request);
if (response.isExists()) {
return response.getSourceAsMap();
} else {
return new HashMap<String, Object>();
}
10,数据查询,设置高亮,排序,以分页形式返回,
//指定索引
SearchRequest searchRequest = new SearchRequest(indexName);
searchRequest.types(type);
//指定查询条件对象
SearchSourceBuilder builder = new SearchSourceBuilder();
builder.timeout(TimeValue.timeValueMinutes(3));
//指定具体查询条件【参考 ES Query DSL】
BoolQueryBuilder query = QueryBuilders.boolQuery();
for (String field : filterMap.keySet()) {
query.filter(QueryBuilders.matchQuery(field, filterMap.get(field)));
}
query.must(QueryBuilders.multiMatchQuery(searchContent, searchFields));
// 设置查询条件
builder.query(query);
// 设置分页
builder.from((pageNum - 1) * pageSize);
builder.size(pageSize);
// 设置返回的结果字段
if (returnFields != null) {
builder.fetchSource(returnFields, null);
}
// 排序
if (sortMap != null) {
for (String sortField : sortMap.keySet()) {
builder.sort(sortField, “asc”.equals(sortMap.get(sortField)) ? SortOrder.ASC : SortOrder.DESC);
}
}
// 设置高亮字段
if (highlightFields != null) {
HighlightBuilder highlightBuilder = new HighlightBuilder();
for (String hf : highlightFields) {
highlightBuilder.field(hf);
}
builder.highlighter(highlightBuilder);
}
// 记录查询语句,方便测试
log.info("## Query index [{}] with DSL {}", indexName, builder);
// 完成查询条件设置
searchRequest.source(builder);
List<Map<String, Object>> list = new ArrayList<>();
// 获取查询结果
try {
SearchResponse searchResponse = restHighLevelClient.search(searchRequest);
// 判断查询结果是否超时
boolean timedOut = searchResponse.isTimedOut();
if (timedOut) {
log.error("## Search result from [{}] is timeout!", indexName);
}
// 获取查询结果
if (searchResponse.status().getStatus() == 200) {
SearchHits hits = searchResponse.getHits();
// 记录查询结果条数
long totalHits = hits.totalHits;
log.info("## Search result total have [{}]", totalHits);
// 遍历结果集,封装
SearchHit[] searchHits = hits.getHits();
for (SearchHit hit : searchHits) {
list.add(hit.getSourceAsMap());
}
}
11,过滤查询 query filter
12,聚合查询
注:聚合:Aggregation Aggs,是ES除搜索功能外提供的针对es数据做统计分析的功能。
聚合有助于根据搜索查询提供聚合数据。聚合查询是数据库中重要的功能特性,ES作为搜索引擎兼数据库,同样提供了强大的聚合分析能力。类似于 SQL中的 group by 函数。
注:text 类型是不支持聚合。
12.1,分组查询
SearchRequest searchRequest = new SearchRequest(indexName);
searchRequest.types(type);
SearchSourceBuilder builder = new SearchSourceBuilder();
builder.timeout(TimeValue.timeValueMinutes(3));
// 设置查询条件
builder.query(query);
TermsAggregationBuilder termsAggregationBuilder = AggregationBuilders
.terms(“terms”) //自定义聚合返回结果key
.field(termField); //设置聚合的字段
builder.aggregation(termsAggregationBuilder);
// 完成查询条件设置
searchRequest.source(builder);
//封装结果集
List<Map<String, String>> list = new ArrayList<>();
SearchResponse searchResponse = restHighLevelClient.search(searchRequest);
Terms terms = searchResponse.getAggregations().get(“terms”);
// 获取查询结果
if (searchResponse.status().getStatus() == 200) {
Terms terms = searchResponse.getAggregations().get(“terms”);
for (Terms.Bucket entry : terms.getBuckets()) {
Map<String, String> map = new HashMap<>();
map.put(keyFieldName, entry.getKey().toString());
map.put(countFieldName, Long.toString(entry.getDocCount()));
list.add(map);
}
}
12.2,求最大值
注:max (ParsedMax),min(ParsedMin)sum(ParsedSum) avg(ParsedAvg)
SearchRequest searchRequest = new SearchRequest(indexName);
searchRequest.types(type);
SearchSourceBuilder builder = new SearchSourceBuilder();
builder.timeout(TimeValue.timeValueMinutes(3));
// 设置查询条件
builder.query(query);
//设置聚合条件
TermsAggregationBuilder termsAggregationBuilder = AggregationBuilders
.max(“terms”) //自定义聚合返回结果key
.field(termField); //设置聚合的字段
builder.aggregation(termsAggregationBuilder);
// 完成查询条件设置
searchRequest.source(builder);
SearchResponse searchResponse = restHighLevelClient.search(searchRequest);
ParsedMax max = response.getAggregations().get(countName);
double value = max.getValue();