java 连接操作Elasticsearch(三)
- 单个id在单个index中查询数据prepareGet
/** * 单个id在单个index中查询数据prepareGet * * @param indexName * 索引,类似数据库名 * @param typeName * 类型,类似表名 * @param id * @return */ public static SearchHits queryId(String indexName, String typeName, String id) { SearchHits hits = null; try { QueryBuilder builder = QueryBuilders.idsQuery().addIds(id); //采用折叠去重复,对id字段 CollapseBuilder collapseBuilder = new CollapseBuilder("id"); SearchResponse response = getSingleClient() .prepareSearch(indexName) .setTypes(typeName) .setCollapse(collapseBuilder) .addSort("release_time", SortOrder.DESC) .setQuery(builder) .get(); hits = response.getHits(); } catch (ElasticsearchParseException e) { throw new RuntimeException(e.getMessage()); } return hits; }
- 多个id在单个index中查询数据prepareGet
/** * 多个id在单个index中查询数据prepareGet * * @param indexName * 索引,类似数据库名 * @param typeName * 类型,类似表名 * @param id * @return */ public static SearchHits queryIds(String indexName, String typeName, String[] idArray) { SearchHits hits = null; try { QueryBuilder builder = QueryBuilders.idsQuery().addIds(idArray); //采用折叠去重复,对id字段 /*CollapseBuilder collapseBuilder = new CollapseBuilder("id");*/ SearchResponse response = getSingleClient() .prepareSearch(indexName) .setTypes(typeName) //.setCollapse(collapseBuilder) //Ids 数组查询时允许记录重复 .addSort("release_time", SortOrder.DESC) .setQuery(builder) .get(); hits = response.getHits(); } catch (ElasticsearchParseException e) { throw new RuntimeException(e.getMessage()); } return hits; }
- 条件涉及多字段查询
/** * 条件涉及多字段查询 * * @param indexName * 索引,类似数据库名 * @param query * 查询条件涉及字段值 * @param field1 * 查询条件涉及字段1 * @param field2 * 查询条件涉及字段2 */ public static void multiMatchQuery(String indexName, String query, String field1, String field2) { try { QueryBuilder qb = QueryBuilders.multiMatchQuery(query, field1, field2); SearchResponse response = getSingleClient().prepareSearch(indexName).setQuery(qb).setSize(3).get(); SearchHits hits = response.getHits(); for (SearchHit hit : hits) { // System.out.println("文档内容: " + hit.getSourceAsString()); Map<String, Object> map = hit.getSourceAsMap(); for (String key : map.keySet()) { System.out.println(key + "=" + map.get(key)); } } } catch (Exception e) { throw new RuntimeException(e.getMessage()); } }
- 常用统计查询
/** * 聚合Max查询 * * @param indexName * @param field */ public static void aggMax(String indexName, String field) { try { AggregationBuilder agg = AggregationBuilders.max("aggMax").field("age"); SearchResponse response = getSingleClient().prepareSearch("lib3").addAggregation(agg).get(); Max max = response.getAggregations().get("aggMax"); double agg_max = (double) max.getValue(); System.out.println(agg_max); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } } /** * 聚合Min查询 * * @param indexName * @param field */ public static void aggMin(String indexName, String field) { try { AggregationBuilder agg = AggregationBuilders.min("aggMin").field("age"); SearchResponse response = getSingleClient().prepareSearch("lib3").addAggregation(agg).get(); Min min = response.getAggregations().get("aggMin"); double agg_min = (double) min.getValue(); System.out.println(agg_min); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } } /** * 聚合Avg求平均查询 * * @param indexName * @param field */ public static void aggAvg(String indexName, String field) { try { AggregationBuilder agg = AggregationBuilders.avg("aggMin").field("age"); SearchResponse response = getSingleClient().prepareSearch("lib3").addAggregation(agg).get(); Avg avg = response.getAggregations().get("aggMin"); double agg_avg = (double) avg.getValue(); System.out.println(agg_avg); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } } /** * 聚合Sum求和 * * @param indexName * @param field */ public static void aggSum(String indexName, String field) { try { AggregationBuilder agg = AggregationBuilders.sum("aggSum").field("age"); SearchResponse response = getSingleClient().prepareSearch("lib3").addAggregation(agg).get(); Sum sum = response.getAggregations().get("aggSum"); double agg_sum = (double) sum.getValue(); System.out.println(agg_sum); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } } /** * 求基数 * * @param indexName * @param field */ public static void aggCardinality(String indexName, String field) { try { AggregationBuilder agg = AggregationBuilders.cardinality("aggCardinality").field("age"); SearchResponse response = getSingleClient().prepareSearch("lib3").addAggregation(agg).get(); Cardinality cardinality = response.getAggregations().get("aggCardinality"); double agg_cardinality = (double) cardinality.getValue(); System.out.println(agg_cardinality); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } }
- 按字段分组查询
/** * 按字段分组查询 * * @param indexName * @param boolQueryBuilder * @param field * @return */ public static Map<Object, Long> aggGroupBy(String indexName, BoolQueryBuilder boolQueryBuilder, String field) { Map<Object, Long> map = new HashMap<Object, Long>(); Long num = (long) 0; try { AggregationBuilder agg = AggregationBuilders.terms("source_type_count").field(field).size(50); SearchResponse response = getSingleClient().prepareSearch(indexName).setQuery(boolQueryBuilder) .addAggregation(agg).execute().actionGet(); // System.out.println(response.getHits().getTotalHits()); num = response.getHits().getTotalHits(); Terms terms = response.getAggregations().get("source_type_count"); for (Terms.Bucket entry : terms.getBuckets()) { // System.out.println(entry.getKey() + ":" + // entry.getDocCount()); map.put(entry.getKey(), entry.getDocCount()); } } catch (Exception e) { throw new RuntimeException(e.getMessage()); } map.put("全部", num); return map; }
- 多个索引index表查询返回结果集SearchHits
public static SearchHits getResponseMultiResult(String[] indexsName, String type, TransportClient client, BoolQueryBuilder boolQueryBuilder, String sortStr, int pageNum, int recordNum, String field1, String field2) { SearchHits hits = null; if (indexsName.length > 0) { try { // 设置高亮属性 HighlightBuilder highlightBuilder = new HighlightBuilder(); highlightBuilder.preTags("<span style=\"color:red\">").postTags("</span>").field(field1).field(field2); // 设置ES查询属性 SearchResponse response = null; if (sortStr != null && !"".equals(sortStr)) { String[] sortArray = sortStr.split("###"); // 判断排序方式 SortOrder sortFlag = null; if ("+".equals(sortArray[1])) { sortFlag = SortOrder.ASC; } else { sortFlag = SortOrder.DESC; } // 执行ES查询 if ("articlesSort".equals(sortArray[0])) { // 按ES库中的_score得分排序 response = client.prepareSearch(indexsName).setTypes(type).setQuery(boolQueryBuilder) .highlighter(highlightBuilder).addSort(SortBuilders.scoreSort().order(sortFlag)) .setFrom(pageNum).setSize(recordNum).setExplain(true).execute().actionGet(); } else { // 按排序字段进行排序 response = client.prepareSearch(indexsName).setTypes(type).setQuery(boolQueryBuilder) .highlighter(highlightBuilder).addSort(sortArray[0], sortFlag).setFrom(pageNum) .setSize(recordNum).setExplain(true).execute().actionGet(); } } else { // 无排序 response = client.prepareSearch(indexsName).setTypes(type).setQuery(boolQueryBuilder) .highlighter(highlightBuilder).setFrom(pageNum).setSize(recordNum).setExplain(true) .execute().actionGet(); } hits = response.getHits(); } catch (Exception e) { e.printStackTrace(); } } return hits; }
小白技术分享