es分组聚合统计记录数大于某值

1,使用jest链接es

2,使用es原生API链接es

【使用jest链接es】

参考:

https://blog.csdn.net/weixin_37701177/article/details/87860794

https://blog.csdn.net/qq_38151401/article/details/103931433

当springboot的jpa和@query参数形式查询无法满足复杂es查询时

依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>2.5.2</version>
</dependency>

<!--es-->
<dependency>
    <groupId>io.searchbox</groupId>
    <artifactId>jest</artifactId>
    <version>6.3.1</version>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
</dependency>
package org.example;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestClientFactory;
import io.searchbox.client.config.HttpClientConfig;
import io.searchbox.core.Search;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.nio.conn.SchemeIOSessionStrategy;
import org.apache.http.nio.conn.ssl.SSLIOSessionStrategy;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.junit.*;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;

public class JestUtils {
    private JestClient jestClient;
    private String indexName = "mail_e";
    private String username = "admin";
    private String password = "admin";
    private String url = "http://xxx.xxx.xxx.xxx:xxxx/";

    @Before
    public void getClient() throws Exception {
        //本地连接,不用密码
//        JestClientFactory factory = new JestClientFactory();
//        factory.setHttpClientConfig(new HttpClientConfig.Builder(url)
//                .gson(new GsonBuilder().setDateFormat("yyyy-MM-dd hh:mm:ss").create())
//                .connTimeout(1500)
//                .readTimeout(3000)
//                .multiThreaded(true)
//                .build());

        //服务器连接
        JestClientFactory factory = new JestClientFactory();
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
            public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                return true;
            }
        }).build();
        HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
        SchemeIOSessionStrategy httpsIOSessionStrategy = new SSLIOSessionStrategy(sslContext, hostnameVerifier);
        factory.setHttpClientConfig(new HttpClientConfig.Builder(url)
                .defaultCredentials(username, password)
                .defaultSchemeForDiscoveredNodes("http")
                .sslSocketFactory(sslSocketFactory)
                .httpsIOSessionStrategy(httpsIOSessionStrategy)
                .readTimeout(2000000)
                .build());
        jestClient = factory.getObject();
    }

    @After
    public void closeClient() throws Exception {
        if (jestClient != null) {
            jestClient.shutdownClient();
        }
    }


    @Test
    //根据mailFrom分组聚合,条件:smPerson包含true且mailFrom为@qq.com,分组条件:记录数大于阈值
    public void get() throws IOException {
        String dsl = "{\n" +
                "  \"query\": {\n" +
                "    \"bool\": {\n" +
                "      \"must\": [\n" +
                "        {\n" +
                "          \"query_string\": {\n" +
                "            \"query\": \"*false*\",\n" +
                "            \"fields\": [\n" +
                "              \"smPerson\"\n" +
                "            ]\n" +
                "          }\n" +
                "        },\n" +
                "        {\n" +
                "          \"query_string\": {\n" +
                "            \"query\": \"*@qq.com*\",\n" +
                "            \"fields\": [\n" +
                "              \"mailFrom\"\n" +
                "            ]\n" +
                "          }\n" +
                "        }\n" +
                "      ]\n" +
                "    }\n" +
                "  },\n" +
                "  \"size\": 0,\n" +
                "  \"aggs\": {\n" +
                "    \"group_by\": {\n" +
                "      \"terms\": {\n" +
                "        \"field\": \"mailFrom\",\n" +
                "        \"min_doc_count\": \"80\"\n" +
                "      }\n" +
                "    }\n" +
                "  }\n" +
                "}";
        Search search = new Search.Builder(dsl).addIndex(indexName).build();

        String resultString = jestClient.execute(search).getJsonString();
        JSONObject resultObject = JSON.parseObject(resultString);
        JSONObject aggs = (JSONObject)resultObject.get("aggregations");
        JSONObject group_by = (JSONObject)aggs.get("group_by");
        JSONArray buckets = group_by.getJSONArray("buckets");

        List<String> mailList = new ArrayList<>();
        for (int i = 0; i < buckets.size(); i++) {
            String key = buckets.getJSONObject(i).getString("key");
            mailList.add(key);
            System.out.println(key);
        }

    }
}

【使用es原生API链接es】

依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>2.5.2</version>
</dependency>
@Test
    public void testAggsFindSmPerson(){
        String groupByName = "groupBymailFrom";
        Query query = new NativeSearchQueryBuilder()
                .addAggregation(terms(groupByName).field("mailFrom").minDocCount(80))
                .withQuery(QueryBuilders.fuzzyQuery("content", "测试"))
                .withQuery(QueryBuilders.wildcardQuery("smPerson", "*false*"))
                .build();

        SearchHits<MailDocsE> searchHits =  elasticsearchRestTemplate.search(query, MailDocsE.class);
        System.out.println(searchHits.getTotalHits());
        Aggregations aggregations = searchHits.getAggregations();
        assert aggregations != null;
        Aggregation docIds = aggregations.asMap().get(groupByName);
        ParsedStringTerms stringTerms = (ParsedStringTerms) docIds;
        stringTerms.getBuckets().forEach(bucket -> System.out.println(bucket.getKeyAsString() + " " + bucket.getDocCount()));
    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在 Elasticsearch 中,可以使用聚合(Aggregation)实现对文档进行聚合统计,其中包括出现次统计。下面是一个示例: 假设我们有一个名为 "sales" 的索引,包含以下文档: ``` { "product": "A", "price": 10.0, "timestamp": "2021-08-01T10:00:00Z" } { "product": "B", "price": 15.0, "timestamp": "2021-08-01T10:05:00Z" } { "product": "A", "price": 12.0, "timestamp": "2021-08-01T10:10:00Z" } { "product": "C", "price": 20.0, "timestamp": "2021-08-01T10:15:00Z" } { "product": "A", "price": 8.0, "timestamp": "2021-08-01T10:20:00Z" } { "product": "B", "price": 18.0, "timestamp": "2021-08-01T10:25:00Z" } ``` 现在,我们想要统计每个产品出现的次,可以使用以下聚合查询: ``` { "aggs": { "products": { "terms": { "field": "product" } } } } ``` 其中,"aggs" 是聚合查询的关键字,"products" 是我们给这个聚合起的名字,"terms" 表示我们要按照某个字段进行分组,"field" 指定了我们要按照哪个字段进行分组。 运行上述查询后,得到的结果如下: ``` { "aggregations": { "products": { "buckets": [ { "key": "A", "doc_count": 3 }, { "key": "B", "doc_count": 2 }, { "key": "C", "doc_count": 1 } ] } } } ``` 其中,"key" 表示产品名称,"doc_count" 表示该产品出现的次。 如果想要对出现次进行排序,可以使用以下聚合查询: ``` { "aggs": { "products": { "terms": { "field": "product", "order": { "_count": "desc" } } } } } ``` 其中,"order" 表示按照什么字段进行排序,"_count" 表示按照出现次进行排序,"desc" 表示降序排列。 运行上述查询后,得到的结果如下: ``` { "aggregations": { "products": { "buckets": [ { "key": "A", "doc_count": 3 }, { "key": "B", "doc_count": 2 }, { "key": "C", "doc_count": 1 } ] } } } ``` 其中,产品 A 出现的次最多,排在第一位。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值