首页 > 其他分享 >Elasticsearch SpringBoot 整合 复杂检索

Elasticsearch SpringBoot 整合 复杂检索

时间:2022-10-23 15:33:26浏览次数:93  
标签:检索 search SpringBoot aggregations private elasticsearch org import Elasticsearch

官方文档:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high-search.html

一、例子

package com.atguigu.gulimall.search;

import com.alibaba.fastjson.JSON;
import com.atguigu.gulimall.search.config.SearchConfig;
import lombok.Data;
import lombok.ToString;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.Avg;
import org.elasticsearch.search.aggregations.metrics.AvgAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.IOException;


@RunWith(SpringRunner.class)
@SpringBootTest
public class GulimallSearchApplicationTests {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Test
   public void contextLoads() {
        System.out.println(restHighLevelClient);
    }


    /**
     *
     * @throws IOException
     */
    @Test
    public void searchData() throws IOException {
        //1、创建一个检索请求
        SearchRequest searchRequest = new SearchRequest();
        //从哪开始检索,检索条件是什么
        searchRequest.indices("bank");
        //指定DSL,检索条件
        //SearchSourceBuilder source()
        //searchSourceBuilder 封装的条件
        SearchSourceBuilder searchSourceBuilder =   new  SearchSourceBuilder();
        //1.1 构造检索条件
//        searchSourceBuilder.query();
//        searchSourceBuilder.from();
//        searchSourceBuilder.size();
//        searchSourceBuilder.aggregation();
        searchSourceBuilder.query(QueryBuilders.matchQuery("address","mill"));

        //按照年龄的值分布进行聚合
        TermsAggregationBuilder ageAgg = AggregationBuilders.terms("ageAgg").field("age").size(10);
        searchSourceBuilder.aggregation(ageAgg);


        //1.3)、计算平均薪资
        AvgAggregationBuilder builderAvg = AggregationBuilders.avg("balanceAvg").field("balance");
        searchSourceBuilder.aggregation(builderAvg);
        System.out.println("检索条件"+searchSourceBuilder.toString());

        searchRequest.source(searchSourceBuilder);

        //2、执行搜索
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest,SearchConfig.COMMON_OPTIONS);

        //3 分析结果
        System.out.println(searchResponse.toString());
        //3.1 获取所有查到的数据
        SearchHits hits = searchResponse.getHits();
        SearchHit[] searchHits = hits.getHits();
        for (SearchHit searchHit: searchHits) {
            String sourceAsString = searchHit.getSourceAsString();
            Account account = JSON.parseObject(sourceAsString, Account.class);

            System.out.println("searchHit:"+account.toString());
        }

        //3.2 获取这次检索到的分析信息
        Aggregations aggregations = searchResponse.getAggregations();
//        for (Aggregation aggregation : aggregations.asList()) {
//            aggregation.getName();
//            System.out.println("当前聚合:"+aggregation.getName());
//        }
        Terms ageAgg1 = aggregations.get("ageAgg");

        for (Terms.Bucket bucket : ageAgg1.getBuckets()) {
            String keyAsString = bucket.getKeyAsString();
            System.out.println("年龄:"+keyAsString+"有几个人"+bucket.getDocCount());
        }

        Avg balanceAvg = aggregations.get("balanceAvg");

        System.out.println("平均薪资"+balanceAvg.getValue());


    }







@ToString
@Data
static class Account {

        private int account_number;
        private int balance;
        private String firstname;
        private String lastname;
        private int age;
        private String gender;
        private String address;
        private String employer;
        private String email;
        private String city;
        private String state;

    }
}

 

标签:检索,search,SpringBoot,aggregations,private,elasticsearch,org,import,Elasticsearch
From: https://www.cnblogs.com/mangoubiubiu/p/16818659.html

相关文章

  • docker 中 elasticsearch 的安装
    1通过阿里云镜像加速器地址配置docker加速服务 2拉取镜像dockerpullelasticsearch:7.4.23建立挂载目录mkdir-p/mydata/elasticsearch/configmkdir-p/myd......
  • SpringBoot 创建项目连接mysql数据库
    Spring 创建项目1.创建一个springboot项目2.点击File---- New---- project项目名称可以随便填写...3. Springboot版本尽量不要最新版,怕你们驾驭不了......
  • SpringBoot的 META-INF/spring.factories有什么用
    1,spring.factories文件中的内容,将来都会转化Properties对象。spring.factories内容示例org.springframework.data.repository.core.support.RepositoryFactorySupport=org.s......
  • 2流高手速成记(之四):SpringBoot整合redis及mongodb
    最近很忙,好不容易才抽出了时间,咱们接上回上次我们主要讲了如何通过SpringBoot快速集成mybatis/mybatis-plus,以实现业务交互中的数据持久化,而这一切都是基于关系型数据库(SQ......
  • SpringBoot 后台管理系统竟然出了详细教程!
    其实项目网上有很多了,但是教程比较详细的没多少,今天分享的项目从安装部署到代码具体功能都有很详细都说明。eladmin是一款基于SpringBoot2.1.0、Jpa、SpringSecurit......
  • SpringBoot微服务打包Docker镜像
    1.构建sprintboot项目2.打包应用3.编写dockerfileidea下载docker插件(可以高亮)4.构建镜像先把之前镜像都移除dockerrm-f$(dockerps-qa)在Linuxhome目......
  • 记一次SpringBoot整合WebSocket 找不到ServerEndpointExporter类的问题
    packagecom.mengxiangnongfu.cms.framework.configure;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Confi......
  • 16.Springboot集成Websocket
    Springboot集成Websocket1.导入pom依赖<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId><......
  • 三,SpringBoot Banner修改
     在上一节中已经知道怎么创建springboot项目了,是时候放松下了,于是乎看到别人bannner与众不同,我也想拥有,,,编辑不整是不可能的,废话不多说,直接开整1.去网站生成想要的banner图:......
  • 解决vue请求springBoot项目时跨域问题
    由于浏览器同源策略的限制,如果请求url的协议、域名、端口号中有一项不同,就会产生跨域问题当我们在本地开始前后端分离项目时,必然会启动不用的端口,所以就会发生跨域问题比......