ElasticsearchRestTemplate常用示例

ElasticsearchRestTemplate常用示例

一、基础操作

1.1 索引操作

1.1.1 创建索引及映射

   public Boolean createIndexAndMapping() {
        IndexOperations indexOperations = restTemplate.indexOps(EsAccounts.class);
        //创建索引
        boolean result = indexOperations.create();
        if (result){
            //生成映射
            Document mapping = indexOperations.createMapping();
            //推送映射
            return indexOperations.putMapping(mapping);
        }else {
            return result;
        }
    }

1.1.2 删除索引

	public boolean deleteIndex() {
    	IndexOperations indexOperations = elasticsearchRestTemplate.indexOps(EsAccounts.class);
    	return indexOperations.delete();
	}

1.2 添加文档

1.2.1 添加文档

	public EsAccounts save(EsAccounts entities) {
        return restTemplate.save(entities);
    }

1.2.2 查询文档(id查询)

	public EsAccounts getById(String id) {
        return restTemplate.get(id,EsAccounts.class);
    }

1.2.3 修改文档

	public UpdateResponse update(String id, EsAccounts entities) {
        UpdateQuery.Builder builder = UpdateQuery.builder(id)
                .withDocument(Document.from(BeanUtil.beanToMap(entities)));
        return restTemplate.update(builder.build(), IndexCoordinates.of("accounts"));
    }

1.2.4 删除文档

	 public String delete(EsAccounts entities) {
         return restTemplate.delete(entities);
    }

二、查询

2.1 高亮查询

    public SearchHits<EsAccounts> search(String keyword) {
        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("firstname", keyword);
        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("firstname");
        highlightBuilder.requireFieldMatch(false);//多个高亮关闭
        highlightBuilder.preTags("");
        highlightBuilder.postTags("");

        NativeSearchQuery query = new NativeSearchQueryBuilder()
                .withQuery(matchQueryBuilder)
                .build();
        query.setHighlightQuery(new HighlightQuery(highlightBuilder));

        SearchHits<EsAccounts> search = restTemplate.search(query, EsAccounts.class);
        return search;
    }

2.2 分页查询

 	public SearchHits<EsAccounts> selectByPage(int page, int size) {
        NativeSearchQuery query = new NativeSearchQueryBuilder()
                .withPageable(PageRequest.of(page - 1, size))
                .build();
        SearchHits<EsAccounts> search = restTemplate.search(query, EsAccounts.class);
        return search;
    }

2.3 排序

	 public  SearchHits<EsAccounts> selectByAgeDesc() {
        NativeSearchQuery query = new NativeSearchQueryBuilder()
                .withSort(SortBuilders.fieldSort("age").order(SortOrder.DESC))
                .build();

        SearchHits<EsAccounts> search = restTemplate.search(query, EsAccounts.class);
        return search;
    }

2.4 时间范围

 	public SearchHits<EsAccounts> selectByRangeTime(String begin, String end) {
        NativeSearchQuery query = new NativeSearchQueryBuilder()
                .withSort(SortBuilders.fieldSort("createTime")
                        .order(SortOrder.DESC))
                .withFilter(QueryBuilders.rangeQuery("createTime")
                        .timeZone("+08:00")
                        .format("yyyy-MM-dd HH:mm:ss")
                        .gt(begin)
                        .lt(end))
                .build();

        SearchHits<EsAccounts> search = restTemplate.search(query, EsAccounts.class);

        return search;
    }

2.5 同字段多条件匹配查询(or)

  	public SearchHits<EsAccounts> searchAll() {

        TermsQueryBuilder termsQueryBuilder = QueryBuilders.termsQuery("age", "21", "31");
        Query query = new NativeSearchQueryBuilder().withQuery(termsQueryBuilder).build();

        SearchHits<EsAccounts> search = restTemplate.search(query, EsAccounts.class);
        return search;
    }

2.6 boostingQuery

	public SearchHits<EsAccounts> boostingQuery() {
        NativeSearchQuery query = new NativeSearchQueryBuilder()
                .withQuery(
                        QueryBuilders.boostingQuery(
                            QueryBuilders.termQuery("age", "31"),           //希望包含的
                            QueryBuilders.termQuery("account_number", "51") //包含降低得分
                        ).negativeBoost(0.2f)//设置满足negativeQuery精度
                ).build();
        SearchHits<EsAccounts> search = restTemplate.search(query, EsAccounts.class);
        return search;
    }

2.7 constantScoreQuery

public SearchHits<EsAccounts> constantScoreQuery() {
        NativeSearchQuery query = new NativeSearchQueryBuilder()
                .withQuery(
                        QueryBuilders.constantScoreQuery(
                            QueryBuilders.termQuery("account_number", "51")
                        ).boost(1.2f)
                ).build();
        SearchHits<EsAccounts> search = restTemplate.search(query, EsAccounts.class);
        return search;
    }

三、聚合查询

3.1 基本指标聚合

	public SearchHits<EsAccounts> getStats(){
        QueryBuilder queryBuilder = QueryBuilders.termQuery("age", "23");
        MaxAggregationBuilder maxBalance = AggregationBuilders.max("maxBalance").field("balance");  //最大值
        MinAggregationBuilder minBalance = AggregationBuilders.min("minBalance").field("balance");  //最小值
        AvgAggregationBuilder avgBalance = AggregationBuilders.avg("avgBalance").field("balance");  //平均值
        SumAggregationBuilder sumBalance = AggregationBuilders.sum("sumBalance").field("balance");  //总和
        ValueCountAggregationBuilder count = AggregationBuilders.count("countBalance").field("balance"); // 总条数 
        //  总数,最大值,最小值,平均值,总和
        StatsAggregationBuilder stats = AggregationBuilders.stats("stats").field("balance"); 
        Query query = new NativeSearchQueryBuilder()
                .withQuery(queryBuilder)
                .addAggregation(maxBalance)
                .addAggregation(minBalance)
                .addAggregation(avgBalance)
                .addAggregation(sumBalance)
                .addAggregation(count)
                .addAggregation(stats)
                .build();
        SearchHits<EsAccounts> search = restTemplate.search(query, EsAccounts.class);

        if (search.hasAggregations()) {
            Aggregations aggregations = search.getAggregations();
            if (Objects.nonNull(aggregations)) {
                Max maxValue = aggregations.get("maxBalance"); //最大值
            }
        }
        return search;
    }
    

3.2 桶聚合

3.2.1 range范围分桶聚合查询

	public SearchHits<EsAccounts> range(){
        //制定检索条件
        RangeAggregationBuilder rangeAggregationBuilder = AggregationBuilders.range("age_range")
                .field("age")
                .addRange(0,30)
                .addRange(30,35)
                .addRange(35,100);

        Query query = new NativeSearchQueryBuilder().addAggregation(rangeAggregationBuilder).build();
        SearchHits<EsAccounts> search = restTemplate.search(query, EsAccounts.class);
        return search;
    }
  {
    "size": 0, 
    "aggs": {
      "rang_age": {
        "range": {
          "field": "age",
          "ranges": [
            {
              "from": 0,
              "to": 30
            },
            {
              "from": 30,
              "to": 35
            },
            {
              "from": 35,
              "to": 100
            }
          ]
        }
      }
    }
  }

3.2.2 term自定义分组桶聚合查询

  	public SearchHits<EsAccounts> termAgg(){
        TermsAggregationBuilder termsAggregationBuilder = AggregationBuilders
                .terms("age_group").field("age")
                .subAggregation(AggregationBuilders.sum("sum_balance").field("balance"))
                .subAggregation(AggregationBuilders.avg("avg_balance").field("balance"));

        Query query = new NativeSearchQueryBuilder().addAggregation(termsAggregationBuilder).build();

        SearchHits<EsAccounts> search = restTemplate.search(query, EsAccounts.class);
        return search;
    }
 {
  "size": 0, 
  "aggs": {
    "age_group": {
      "terms": {
        "field": "age"
      },
      "aggs": {
        "sum_balance": {
          "sum": {
            "field": "balance"
          }
        },
        "avg_balance":{
          "avg": {
            "field": "balance"
          }
        }
      }
    }
  }
}

3.2.3 Filter Aggregation 过滤器聚合

 public SearchHits<EsAccounts> filterAgg(){
        FilterAggregationBuilder filter= AggregationBuilders
                .filter("agg", QueryBuilders.termQuery("age", "31"))
                .subAggregation(AggregationBuilders.avg("avg_balance").field("balance"));

        Query query = new NativeSearchQueryBuilder().addAggregation(filter).build();

        SearchHits<EsAccounts> search = restTemplate.search(query, EsAccounts.class);
        return search;
    }
{
  "aggs": {
    "age_count": {
      "filter": {
        "term": {
          "age": 31
        }
      },
      "aggs": {
        "avg_balance": {
          "avg": {
            "field": "balance"
          }
        }
      }
    }
  }
}

你可能感兴趣的:(Elasticsearch,spring,boot,搜索引擎,elasticsearch)