030 elasticsearch查询、聚合

news/2024/10/25 16:57:24/

文章目录

    • 查询
    • 聚合查询
      • RestHighLevelClient
      • ElasticsearchRestTemplat

SpringData对ES客户端的封装:ElasticsearchRestTemplate
SpringData对CRUD的封装:ElasticsearchRepository
原生ES客户端:RestHighLevelClient

查询

package com.xd.cubemall.sdes;import com.xd.cubemall.search.CubemallSearchApplication;
import com.xd.cubemall.search.model.Blog;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
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.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.test.context.junit4.SpringRunner;import java.util.List;
import java.util.Map;@RunWith(SpringRunner.class)
@SpringBootTest(classes = CubemallSearchApplication.class)
public class QueryTest {@Autowiredprivate ElasticsearchRestTemplate template;@Testpublic void testQuery1() {NativeSearchQuery query = new NativeSearchQueryBuilder().withQuery(QueryBuilders.matchAllQuery()).build();SearchHits<Blog> searchHits = template.search(query, Blog.class);//取总记录数long totalHits = searchHits.getTotalHits();System.out.println("总记录数:" + totalHits);//取文档列表List<SearchHit<Blog>> hits = searchHits.getSearchHits();hits.stream().forEach(h-> System.out.println(h));}@Testpublic void testQuery2() throws Exception {NativeSearchQuery query = new NativeSearchQueryBuilder()//查询设置.withQuery(QueryBuilders.multiMatchQuery("看电影","title","content"))//过滤条件,可以设置多个,支持查询条件.withFilter(QueryBuilders.boolQuery().should(QueryBuilders.termQuery("title", "电影")).should(QueryBuilders.termQuery("content","祝福")))
//                .withFilter(QueryBuilders.termQuery("mobile", "13000000000"))//分页设置.withPageable(PageRequest.of(0, 10))//高亮设置.withHighlightBuilder(new HighlightBuilder()//高亮显示的字段.field("title").field("content")//高亮显示的前缀.preTags("<em>")//高亮显示的后缀.postTags("</em>")).build();//使用template对象执行查询SearchHits<Blog> searchHits = template.search(query, Blog.class);//取返回结果//总记录数long totalHits = searchHits.getTotalHits();System.out.println("总记录数:" + totalHits);//取文档列表List<SearchHit<Blog>> hits = searchHits.getSearchHits();hits.stream().forEach(hit->{//取文档对象Blog blog = hit.getContent();//System.out.println(blog);//取高亮结果Map<String,List<String>> highlightFields = hit.getHighlightFields();//System.out.println(highlightFields);String title = highlightFields.get("title").get(0);String content = highlightFields.get("content").get(0);blog.setTitle(title);blog.setContent(content);System.out.println(blog);});}
}

聚合查询

api使用方法
搜索时,请求体中包含聚合条件
在aggs属性中设置聚合条件:
value_count
max
min
avg

GET blog_1/_search
{"query": {"match_all": {}},"aggs": {"mobile_count": {"value_count": {"field": "mobile"}},"mobile_max":{"max": {"field": "mobile"}}}
}

分桶(分组)聚合

GET blog_1/_search
{"query": {"match_all": {}},"aggs": {"mobile_count": {"value_count": {"field": "mobile"}},"mobile_group":{"terms": {"field": "mobile","size": 10}}}
}

RestHighLevelClient

@Autowiredprivate RestHighLevelClient restHighLevelClient;@Testpublic void testAggs() throws IOException {SearchRequest request = new SearchRequest().indices("blog_1").source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()).aggregation(new ValueCountAggregationBuilder("doc_count").field("mobile")).aggregation(new TermsAggregationBuilder("group_count").field("mobile").size(10)));SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);System.out.println(response);}

ElasticsearchRestTemplat

    @Testpublic void testQuery2() throws Exception {NativeSearchQuery query = new NativeSearchQueryBuilder()//查询设置.withQuery(QueryBuilders.multiMatchQuery("看电影","title","content"))//过滤条件,可以设置多个,支持查询条件.withFilter(QueryBuilders.boolQuery().should(QueryBuilders.termQuery("title", "电影")).should(QueryBuilders.termQuery("content","祝福")))
//                .withFilter(QueryBuilders.termQuery("mobile", "13000000000"))//分页设置.withPageable(PageRequest.of(0, 10))//高亮设置.withHighlightBuilder(new HighlightBuilder()//高亮显示的字段.field("title").field("content")//高亮显示的前缀.preTags("<em>")//高亮显示的后缀.postTags("</em>")).addAggregation(new TermsAggregationBuilder("mobile_group").field("mobile")).build();//使用template对象执行查询SearchHits<Blog> searchHits = template.search(query, Blog.class);//取返回结果//总记录数long totalHits = searchHits.getTotalHits();System.out.println("总记录数:" + totalHits);//取文档列表List<SearchHit<Blog>> hits = searchHits.getSearchHits();hits.stream().forEach(hit->{//取文档对象Blog blog = hit.getContent();//System.out.println(blog);//取高亮结果Map<String,List<String>> highlightFields = hit.getHighlightFields();//System.out.println(highlightFields);String title = highlightFields.get("title").get(0);String content = highlightFields.get("content").get(0);blog.setTitle(title);blog.setContent(content);System.out.println(blog);});Aggregations aggregations = searchHits.getAggregations();ParsedStringTerms aggregation = aggregations.get("mobile_group");List<? extends Terms.Bucket> buckets = aggregation.getBuckets();buckets.forEach(e-> {System.out.println(e.getKeyAsString());System.out.println(e.getDocCount());});}

http://www.ppmy.cn/news/1541876.html

相关文章

大数据-182 Elasticsearch - 原理剖析 数据结构-倒排索引、SkipList 跳表

点一下关注吧&#xff01;&#xff01;&#xff01;非常感谢&#xff01;&#xff01;持续更新&#xff01;&#xff01;&#xff01; 目前已经更新到了&#xff1a; Hadoop&#xff08;已更完&#xff09;HDFS&#xff08;已更完&#xff09;MapReduce&#xff08;已更完&am…

智能汽车制造:海康NVR管理平台/工具EasyNVR多品牌NVR管理工具/设备实现无插件视频监控直播方案

一、背景介绍 近年来&#xff0c;随着网络在我国的普及和深化发展&#xff0c;企业的信息化建设不断深入&#xff0c;各行各业都加快了信息网络平台的建设&#xff0c;大多数单位已经或者正在铺设企业内部的计算机局域网。与此同时&#xff0c;网络也成为先进的新兴应用提供了…

FreeRTOS 入门指南

目录 一、引言 二、FreeRTOS 简介 1.什么是 FreeRTOS 2.FreeRTOS 的特点 三、安装 FreeRTOS 1.获取 FreeRTOS 源代码 2.导入到开发环境 四、FreeRTOS 的基本概念 1.任务 2.任务状态 3.任务优先级 4.调度器 5.同步与通信机制 五、创建任务 1.任务函数 2.创建任…

当遇到 502 错误(Bad Gateway)怎么办

很多安装雷池社区版的时候&#xff0c;配置完成&#xff0c;访问的时候可能会遇到当前问题&#xff0c;如何解决呢&#xff1f; 客户端&#xff0c;浏览器排查 1.刷新页面和清除缓存 首先尝试刷新页面&#xff0c;因为有时候 502 错误可能是由于网络临时波动导致服务器无法连…

【python实战】利用代理ip爬取Alibaba海外版数据

引言 在跨境电商的业务场景中&#xff0c;数据采集是分析市场、了解竞争对手以及优化经营策略的重要环节。然而&#xff0c;随着越来越多企业依赖数据驱动决策&#xff0c;许多跨境电商平台为了保护自身数据&#xff0c;采取了更严格的防护措施。这些平台通过屏蔽大陆IP地址或部…

分布式---raft算法

1、Leader的选举和Failover过程 首先了解raft中节点的三种状态&#xff1a; 1、Follower&#xff1a;Follower是请求的被动更新者&#xff0c;从Leader接收更新请求&#xff0c;将日志写入到本地文件2、Candidate:如果Follower在一定时间内&#xff0c;如果每收到Leader的心跳…

【Docker】安装、镜像、容器

什么是Docker&#xff1f; Docker&#xff1a;是基于Go语言实现的开源项目。 Docker 是一个用于开发、交付和运行应用程序的开放平台。它允许开发人员将应用程序及其依赖包打包到一个可移植的容器中&#xff0c; 然后在任何流行的 Linux 机器上运行。Docker 容器是完全隔离的&…

华山论剑之Rust的Trait

华山论剑&#xff0c;群雄荟萃&#xff0c;各显神通。武林中人&#xff0c;各有所长&#xff0c;或剑法飘逸&#xff0c;或掌法刚猛&#xff0c;或轻功绝顶。这就好比Rust中的trait&#xff0c;它定义了一种武功套路&#xff0c;而不同的门派、不同的人&#xff0c;可以将这套武…