ElasticSearch的常用增删改查DSL和代码

es增删改查常用语法

我们日常开发中,操作数据库写sql倒是不可能忘记,但是操作es的dsl语句有时候很容易忘记,特地记录一下方便查找。

DSL语句

1、创建索引

-- 创建索引
PUT /my_index
{"mappings": {"properties": {"title": {"type": "text"},"description": {"type": "text"},"timestamp": {"type": "date"}}}
}

2、插入文档

-- 插入文档
POST /my_index/_doc/主键值
{"title": "Sample Document","description": "This is a sample document for Elasticsearch","timestamp": "2022-01-01"
}

3、更新文档

-- 更新文档
POST /my_index/_update/主键值
{"doc": {"description": "Updated description"}
}

4、删除文档(单独、多个、全部)

-- 删除单条文档
DELETE /my_index/_doc/主键值或者
-- 删除单条文档  
POST 索引名/_delete_by_query
{"query":{"term":{"_id":4043}}
}-- 删除索引中的所有数据
POST my_index/_delete_by_query
{"query": { "match_all": {}}
}

5、删除索引

-- 删除索引
DELETE /my_index

6、设置索引别名

-- 设置索引别名
POST /_aliases{"actions": [{"add": {"index": "my_index2", "alias": "my_index"}}]}

7、设置切片和副本数量

-- 设置切片和副本数量
PUT your_index
{"mappings" : {"properties" : {#索引字段(略)}}"settings" : {"number_of_shards" : 3,"number_of_replicas" : 1}
}

8、查询

-- 查询单个字段内容
POST /my_index/_search
{"query": {"bool": {"must": {"term": {"messageId": "CS202303160008-2"}}}}
}-- 查询单个字段的多个内容  类似mysql中的in 用terms 多了个s
POST /my_index/_search
{"query": {"bool": {"must": {"terms": {"messageId": ["22222","1111"]}}}}
}-- 分页排序查询  	不带其他条件POST /my_index/_search
{"query": {"match_all": {}},"from": 0,"size": 20,"sort": [{"createdAt": {"order": "desc"}}]
}
-- 分页排序查询  	带其他条件
{"query": {"bool": {"must": [{"prefix": {"action": "aa开头"}},{"wildcard": {"param": "*左右匹配内容*"}}],"must_not": [],"should": []}},"from": 0,"size": 10,"sort": [{"createdAt": {"order": "desc"}}]
}

9、统计

POST /my_index/_count
{"query": {"bool": {"must": {"term": {"messageId": "CS202303160008-2"}}}}
}

代码

pom依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.demo.sdk</groupId>
<artifactId>elasticsearch-util</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>elasticsearch-util</name>
<description>Spring Boot Support for elasticsearch-util</description><properties><java.version>11</java.version><elasticsearch.version>7.10.0</elasticsearch.version><spring-boot.version>2.7.0</spring-boot.version><hutool.version>5.8.15</hutool.version><pagehelper.version>1.4.2</pagehelper.version>
</properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-autoconfigure</artifactId><version>${spring-boot.version}</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><version>${spring-boot.version}</version><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-logging</artifactId><version>${spring-boot.version}</version></dependency><dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-high-level-client</artifactId><version>${elasticsearch.version}</version></dependency><dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper-spring-boot-starter</artifactId><version>${pagehelper.version}</version></dependency><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>${hutool.version}</version></dependency>
</dependencies><build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.8.1</version><configuration><source>11</source><target>11</target><encoding>UTF-8</encoding></configuration></plugin><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-source-plugin</artifactId><configuration><attach>true</attach></configuration><executions><execution><phase>compile</phase><goals><goal>jar</goal></goals></execution></executions></plugin></plugins>
</build>

1、ES配置类

	import cn.hutool.core.text.CharSequenceUtil;import org.apache.http.auth.AuthScope;import org.apache.http.auth.UsernamePasswordCredentials;import org.apache.http.client.CredentialsProvider;import org.apache.http.impl.client.BasicCredentialsProvider;import org.springframework.boot.context.properties.ConfigurationProperties;/*** ES配置类* @author ppp* @date 2023/3/21*/@ConfigurationProperties(prefix = "elasticsearch.config")public class ElasticsearchProperties {/*** 域名*/private String host;/*** 端口*/private String port;/*** 用户名*/private String username;/*** 密码*/private String password;/*** 连接超时时间*/private int connectTimeOut;/*** 连接超时时间*/private int socketTimeOut;/*** 获取连接的超时时间*/private int connectionRequestTimeOut;/*** 获取搜索的超时时间*/private long searchRequestTimeOut = 10000L;/*** 最大连接数*/private int maxConnectNum;/*** 最大路由连接数*/private int maxConnectPerRoute;public String getHost() {return host;}public void setHost(String host) {this.host = host;}public String getPort() {return port;}public void setPort(String port) {this.port = port;}public int getConnectTimeOut() {return connectTimeOut;}public void setConnectTimeOut(int connectTimeOut) {this.connectTimeOut = connectTimeOut;}public int getSocketTimeOut() {return socketTimeOut;}public void setSocketTimeOut(int socketTimeOut) {this.socketTimeOut = socketTimeOut;}public int getConnectionRequestTimeOut() {return connectionRequestTimeOut;}public void setConnectionRequestTimeOut(int connectionRequestTimeOut) {this.connectionRequestTimeOut = connectionRequestTimeOut;}public long getSearchRequestTimeOut() {return searchRequestTimeOut;}public void setSearchRequestTimeOut(long searchRequestTimeOut) {this.searchRequestTimeOut = searchRequestTimeOut;}public int getMaxConnectNum() {return maxConnectNum;}public void setMaxConnectNum(int maxConnectNum) {this.maxConnectNum = maxConnectNum;}public int getMaxConnectPerRoute() {return maxConnectPerRoute;}public void setMaxConnectPerRoute(int maxConnectPerRoute) {this.maxConnectPerRoute = maxConnectPerRoute;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public CredentialsProvider getCredentialsProvider() {if (CharSequenceUtil.isNotBlank(username) && CharSequenceUtil.isNotBlank(password)) {CredentialsProvider credentialsProvider = new BasicCredentialsProvider();credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));return credentialsProvider;}return null;}}

2、ES工具自动配置类

import cn.hutool.core.text.CharSequenceUtil;
import com.demo.sdk.elasticsearch.template.ElasticsearchUtilTemplate;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;/**
* ES工具自动配置类
* @author ppp
* @date 2023/3/21
*/
@Configuration
@ConditionalOnClass(ElasticsearchUtilTemplate.class)
@EnableConfigurationProperties(ElasticsearchProperties.class)
public class ElasticsearchUtilAutoConfiguration {@Bean@ConditionalOnMissingBeanpublic RestHighLevelClient esRestClient(ElasticsearchProperties esearchProperties) {if (esearchProperties == null) {throw new NullPointerException("Es Configuration Properties Is Null");}String host = esearchProperties.getHost();String port = esearchProperties.getPort();RestClientBuilder builder;if (CharSequenceUtil.isNotBlank(host) && CharSequenceUtil.isBlank(port)) {builder = RestClient.builder(HttpHost.create(host));}else {builder = RestClient.builder(new HttpHost(host, Integer.parseInt(port)));}// 异步httpclient连接延时配置builder.setRequestConfigCallback(requestConfigBuilder -> {requestConfigBuilder.setConnectTimeout(esearchProperties.getConnectTimeOut());requestConfigBuilder.setSocketTimeout(esearchProperties.getSocketTimeOut());requestConfigBuilder.setConnectionRequestTimeout(esearchProperties.getConnectionRequestTimeOut());return requestConfigBuilder;});// 异步httpclient连接数配置builder.setHttpClientConfigCallback(httpClientBuilder -> {httpClientBuilder.setMaxConnTotal(esearchProperties.getMaxConnectNum());httpClientBuilder.setMaxConnPerRoute(esearchProperties.getMaxConnectPerRoute());httpClientBuilder.setDefaultCredentialsProvider(esearchProperties.getCredentialsProvider());return httpClientBuilder;});return  new RestHighLevelClient(builder);}@Bean@ConditionalOnMissingBeanpublic ElasticsearchUtilTemplate elasticsearchUtilTemplate(RestHighLevelClient esRestClient, ElasticsearchProperties elasticsearchProperties) {if (esRestClient == null) {throw new NullPointerException("RestHighLevelClient init Error");}return new ElasticsearchUtilTemplate(esRestClient,elasticsearchProperties.getSearchRequestTimeOut());}}

3、自动装配配置

装配要生效需要ElasticsearchUtilAutoConfiguration加入springboot的自动装配文件spring.factories
这是spring配置的特定目录文件,自己新建一个,名字和目录要一致
在这里插入图片描述

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\com.demo.sdk.elasticsearch.config.ElasticsearchUtilAutoConfiguration

4、定义一个模板工具类

	import cn.hutool.json.JSONUtil;import com.github.pagehelper.Page;import com.github.pagehelper.page.PageMethod;import com.demo.sdk.elasticsearch.exception.ElasticsearchErrorException;import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;import org.elasticsearch.action.bulk.BulkRequest;import org.elasticsearch.action.bulk.BulkResponse;import org.elasticsearch.action.delete.DeleteRequest;import org.elasticsearch.action.delete.DeleteResponse;import org.elasticsearch.action.get.GetRequest;import org.elasticsearch.action.get.GetResponse;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.action.support.master.AcknowledgedResponse;import org.elasticsearch.action.update.UpdateRequest;import org.elasticsearch.action.update.UpdateResponse;import org.elasticsearch.client.RequestOptions;import org.elasticsearch.client.RestHighLevelClient;import org.elasticsearch.client.core.CountRequest;import org.elasticsearch.client.core.CountResponse;import org.elasticsearch.client.indices.CreateIndexRequest;import org.elasticsearch.client.indices.CreateIndexResponse;import org.elasticsearch.common.unit.TimeValue;import org.elasticsearch.common.xcontent.XContentType;import org.elasticsearch.search.SearchHit;import org.elasticsearch.search.builder.SearchSourceBuilder;import java.util.ArrayList;import java.util.List;import java.util.Map;/*** ES搜索引擎模板* @author ppp* @date 2023/3/21*/public class ElasticsearchUtilTemplate {private final RestHighLevelClient esRestClient;private final long searchRequestTimeOut;public ElasticsearchUtilTemplate(RestHighLevelClient esRestClient, long searchRequestTimeOut) {this.searchRequestTimeOut = searchRequestTimeOut;this.esRestClient = esRestClient;}/*** 列表查询** @param searchSourceBuilder SearchSourceBuilder* @param clazz               返回结果class对象* @param indices             ES索引* @return java.util.List    对象列表*/public <T> List<T> listSearch(SearchSourceBuilder searchSourceBuilder, Class<T> clazz, String... indices) {Page<T> resultPage = PageMethod.getLocalPage();boolean isResultPage = resultPage != null;if (isResultPage) {PageMethod.clearPage();searchSourceBuilder.from((int) resultPage.getStartRow());searchSourceBuilder.size(resultPage.getPageSize());}if (isResultPage && resultPage.isCount()) {resultPage.setTotal(count(searchSourceBuilder, indices));}SearchResponse searchResponse = search(searchSourceBuilder, indices);List<T> resultList = formatSearchResult(searchResponse, clazz);if (isResultPage && resultPage.isCount()) {resultPage.addAll(resultList);return resultPage;}return resultList;}public SearchResponse search(SearchSourceBuilder searchSourceBuilder, String... indices) {SearchRequest searchRequest = new SearchRequest(indices);searchSourceBuilder.timeout(TimeValue.timeValueMillis(searchRequestTimeOut));searchRequest.source(searchSourceBuilder);return search(searchRequest);}public SearchResponse search(SearchRequest searchRequest) {try {return esRestClient.search(searchRequest, RequestOptions.DEFAULT);} catch (Exception e) {throw new ElasticsearchErrorException(e.getMessage(), e.getCause());}}/*** 统计数量** @param searchSourceBuilder SearchSourceBuilder* @param indices             ES索引* @return CountResponse*/public long count(SearchSourceBuilder searchSourceBuilder, String... indices) {CountRequest countRequest = new CountRequest(indices);searchSourceBuilder.timeout(TimeValue.timeValueMillis(searchRequestTimeOut));countRequest.query(searchSourceBuilder.query());return count(countRequest, RequestOptions.DEFAULT).getCount();}public CountResponse count(CountRequest countRequest, RequestOptions options) {try {return esRestClient.count(countRequest, options);} catch (Exception e) {throw new ElasticsearchErrorException(e.getMessage(), e.getCause());}}/*** 创建索引** @param createIndexRequest CreateIndexRequest* @return CreateIndexResponse*/public CreateIndexResponse createIndices(CreateIndexRequest createIndexRequest) {try {return esRestClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);} catch (Exception e) {throw new ElasticsearchErrorException(e.getMessage(), e.getCause());}}/*** 删除索引(谨慎操作,索引下所有数据都将清空)** @param index 索引名称* @return AcknowledgedResponse*/public AcknowledgedResponse deleteIndex(String index) {DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest();deleteIndexRequest.indices(index);return deleteIndices(deleteIndexRequest);}/*** 删除索引(谨慎操作,索引下所有数据都将清空)** @param deleteIndexRequest DeleteIndexRequest* @return AcknowledgedResponse*/public AcknowledgedResponse deleteIndices(DeleteIndexRequest deleteIndexRequest) {try {return esRestClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);} catch (Exception e) {throw new ElasticsearchErrorException(e.getMessage(), e.getCause());}}/*** 插入数据** @param index  索引* @param id     唯一id* @param source 插入对象* @return IndexResponse*/public IndexResponse add(String index, Object id, Object source) {IndexRequest indexRequest = new IndexRequest(index).id(String.valueOf(id));indexRequest.source(JSONUtil.toJsonStr(source), XContentType.JSON);try {return esRestClient.index(indexRequest, RequestOptions.DEFAULT);} catch (Exception e) {throw new ElasticsearchErrorException(e.getMessage(), e.getCause());}}/*** 批量插入数据* 建议:数量控制在5000以内** @param index     索引* @param sourceMap 数据<唯一id,对象>* @return BulkResponse*/public BulkResponse addBulk(String index, Map<String, Object> sourceMap) {BulkRequest request = new BulkRequest();sourceMap.forEach((id, source) -> {request.add(new IndexRequest(index).id(id).source(JSONUtil.toJsonStr(source), XContentType.JSON));});try {return esRestClient.bulk(request, RequestOptions.DEFAULT);} catch (Exception e) {throw new ElasticsearchErrorException(e.getMessage(), e.getCause());}}/*** 获取数据** @param getRequest GetRequest* @return GetResponse*/public GetResponse get(GetRequest getRequest) {try {return esRestClient.get(getRequest, RequestOptions.DEFAULT);} catch (Exception e) {throw new ElasticsearchErrorException(e.getMessage(), e.getCause());}}/*** 更新数据** @param updateRequest UpdateRequest* @return UpdateResponse*/public UpdateResponse update(UpdateRequest updateRequest) {try {return esRestClient.update(updateRequest, RequestOptions.DEFAULT);} catch (Exception e) {throw new ElasticsearchErrorException(e.getMessage(), e.getCause());}}/*** 删除数据** @param deleteRequest DeleteRequest* @return DeleteResponse*/public DeleteResponse delete(DeleteRequest deleteRequest) {try {return esRestClient.delete(deleteRequest, RequestOptions.DEFAULT);} catch (Exception e) {throw new ElasticsearchErrorException(e.getMessage(), e.getCause());}}/*** 格式化搜索结果** @param searchResponse 搜索结果* @param clazz          返回对象* @return java.util.List*/public <T> List<T> formatSearchResult(SearchResponse searchResponse, Class<T> clazz) {SearchHit[] searchHits = searchResponse.getHits().getHits();List<T> resultList = new ArrayList<T>();for (SearchHit searchHit : searchHits) {resultList.add(JSONUtil.toBean(searchHit.getSourceAsString(), clazz));}return resultList;}}

5、定义一个异常

/**
* 错误异常
* @author ppp
* @date 2023/3/21
*/
public class ElasticsearchErrorException extends RuntimeException {public ElasticsearchErrorException(String message) {super(message);}public ElasticsearchErrorException(String message, Throwable cause) {super(message, cause);}
}

6、application.yml配置

# elasticsearch
elasticsearch.config:host: 127.0.0.1port: 9200username: adminpassword: admin123connect-time-out: 1000socket-time-out: 30000connection-request-time-out: 500search-request-time-out: 5000max-connect-num: 100max-connect-per-route: 100

7、测试

class DemoApplicationTests {/*** 获取ElasticsearchUtilTemplate模板*/@Autowiredprivate ElasticsearchUtilTemplate elasticsearchTemplate;/*** 分页查询*/
@Test
void getListPage() {// 分页PageHelper.startPage(1, 10);SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();// 筛选boolQueryBuilder.filter(QueryBuilders.termQuery("ip", "192.168.0.1"));// 筛选多个值  类似mysq  termsQuery和termQuery区别boolQueryBuilder.filter(QueryBuilders.termsQuery("name", Arrays.asList("张三","李四"));// 模糊boolQueryBuilder.must(QueryBuilders.wildcardQuery("ext1", "*测试*"));searchSourceBuilder.query(boolQueryBuilder);// 排序searchSourceBuilder.sort("createTime", SortOrder.DESC);List<StudyLogIndex> logIndexList = this.elasticsearchTemplate.listSearch(searchSourceBuilder, StudyLogIndex.class, index);PageInfo<StudyLogIndex> studyLogIndexPageInfo = new PageInfo<>(logIndexList);System.out.println(JSONUtil.toJsonStr(studyLogIndexPageInfo));
}/*** 统计*/
@Test
void countTest() {// 分页PageHelper.startPage(1, 10);SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();// 筛选boolQueryBuilder.filter(QueryBuilders.termQuery("ip", "127.0.0.1"));// 模糊boolQueryBuilder.must(QueryBuilders.wildcardQuery("ext2", "*用*"));searchSourceBuilder.query(boolQueryBuilder);CountResponse count = elasticsearchTemplate.count(searchSourceBuilder, index);System.out.println("统计总数:"+ count.getCount());
}/*** 删除索引*/
@Test
void deleteIndicesTest() {elasticsearchTemplate.deleteIndex(index);
}/*** 创建es索引*/
@Test
void createIndicesTest() {CreateIndexRequest createIndexRequest = new CreateIndexRequest(index);createIndexRequest.mapping("{\n" +"    \"properties\": {\n" +"        \"globalId\": {\n" +"            \"type\": \"keyword\"\n" +"        },\n" +"        \"site\": {\n" +"            \"type\": \"keyword\"\n" +"        },\n" +"        \"tag\": {\n" +"            \"type\": \"keyword\"\n" +"        },\n" +"        \"uid\": {\n" +"            \"type\": \"keyword\"\n" +"        },\n" +"        \"classId\": {\n" +"            \"type\": \"keyword\"\n" +"        },\n" +"        \"courseId\": {\n" +"            \"type\": \"keyword\"\n" +"        },\n" +"        \"videoId\": {\n" +"            \"type\": \"keyword\"\n" +"        },\n" +"        \"startTime\": {\n" +"            \"type\": \"keyword\"\n" +"        },\n" +"        \"time\": {\n" +"            \"type\": \"keyword\"\n" +"        },\n" +"        \"ip\": {\n" +"            \"type\": \"keyword\"\n" +"        },\n" +"        \"start\": {\n" +"            \"type\": \"integer\"\n" +"        },\n" +"        \"end\": {\n" +"            \"type\": \"integer\"\n" +"        },\n" +"        \"createTime\": {\n" +"            \"type\": \"keyword\"\n" +"        },\n" +"        \"ext1\": {\n" +"            \"type\": \"keyword\"\n" +"        },\n" +"        \"ext2\": {\n" +"            \"type\": \"keyword\"\n" +"        }\n" +"    }\n" +"}", XContentType.JSON);elasticsearchTemplate.createIndices(createIndexRequest);
}/*** 插入es数据*/
@Test
void addDataTest() {for (int i = 0; i < 10; i++) {StudyLogIndex studyLogIndex = new StudyLogIndex();studyLogIndex.setGlobalId("CX"+i);studyLogIndex.setSite("CX");studyLogIndex.setTag("SUCCESS");studyLogIndex.setUid(12000000L+i);studyLogIndex.setClassId(123456L);studyLogIndex.setCourseId(123456L);studyLogIndex.setVideoId(123456L);studyLogIndex.setStartTime(123456L);studyLogIndex.setTime(123456L);studyLogIndex.setIp("127.0.0.1");studyLogIndex.setStart(0);studyLogIndex.setEnd(0);studyLogIndex.setCreateTime(0L);studyLogIndex.setExt1("测试es工具");studyLogIndex.setExt2("备用");elasticsearchTemplate.add(index, studyLogIndex.getGlobalId(), studyLogIndex);}
}/*** 批量插入es*/
@Test
void bulkAddDataTest() {Map<String, Object> map = new HashMap<>(16);for (int i = 100; i < 1000; i++) {StudyLogIndex studyLogIndex = new StudyLogIndex();studyLogIndex.setGlobalId(IdUtil.getSnowflakeNextIdStr());studyLogIndex.setSite("ZJ");studyLogIndex.setTag("SUCCESS");studyLogIndex.setUid(12000000L+i);studyLogIndex.setClassId(123456L);studyLogIndex.setCourseId(123456L);studyLogIndex.setVideoId(123456L);studyLogIndex.setStartTime(123456L);studyLogIndex.setTime(123456L);studyLogIndex.setIp("192.168.0.3");studyLogIndex.setStart(0);studyLogIndex.setEnd(0);studyLogIndex.setCreateTime(0L);studyLogIndex.setExt1("批量测试es工具");studyLogIndex.setExt2("备用");map.put(studyLogIndex.getGlobalId(), studyLogIndex);}elasticsearchTemplate.addBulk(index, map);
}/*** 聚合检索*/
@Test
void aggregateTest() {SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();// 聚合检索不设置大小会默认只返回10个统计结果TermsAggregationBuilder field = AggregationBuilders.terms("group_by_ip").field("ip").size(1000);searchSourceBuilder.aggregation(field).size(10);SearchResponse search = elasticsearchTemplate.search(searchSourceBuilder, index);System.out.println(JSONUtil.toJsonStr(search));Map<String, Long> countMap = AggregationsUtil.getCountMap(search.getAggregations());System.out.println(JSONUtil.toJsonStr(countMap));
}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/243165.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Python实现Lasso回归模型

• Tibshirani(1996)提出了Lasso(The Least Absolute Shrinkage and Selectionator operator)算法。 • 通过构造一个一阶惩罚函数获得一个精炼的模型&#xff1b;通过最终确定一些指标&#xff08;变量&#xff09;的系数为零&#xff08;岭回归估计系数等于0的机会微乎其微&a…

【HarmonyOS】体验鸿蒙电商平台的未来之旅!

从今天开始&#xff0c;博主将开设一门新的专栏用来讲解市面上比较热门的技术 “鸿蒙开发”&#xff0c;对于刚接触这项技术的小伙伴在学习鸿蒙开发之前&#xff0c;有必要先了解一下鸿蒙&#xff0c;从你的角度来讲&#xff0c;你认为什么是鸿蒙呢&#xff1f;它出现的意义又是…

【堂堂狼人杀(定制开发)】

堂堂狼人杀游戏♨️风险规避与优势。?零投资也可参与规避五大风险 政策风险(点对点场外交易)账户风险(无资金池&#xff09; 推广风险(免费注册&#xff0c;注册送大礼包&#xff09; 网络风险(大平台&#xff0c;全网场外交易) 人脉风险(预约角色&#xff0c;强制出售) …

力扣hot100 相交链表 超全注释 满级表达

Problem: 160. 相交链表 文章目录 思路复杂度&#x1f496; Ac Code 思路 &#x1f468;‍&#x1f3eb; 参考题解 &#x1f469;‍&#x1f3eb; 参考图解 复杂度 时间复杂度: O ( n m ) O(nm) O(nm) 空间复杂度: 添加空间复杂度, 示例&#xff1a; O ( 1 ) O(1) O(…

python 正则表达式学习(1)

正则表达式是一个特殊的字符序列&#xff0c;它能帮助你方便的检查一个字符串是否与某种模式匹配。 1. 特殊符号 1.1 符号含义 模式描述^匹配字符串的开头$匹配字符串的末尾.匹配任意字符&#xff0c;除了换行符&#xff0c;当re.DOTALL标记被指定时&#xff0c;则可以匹配包…

飞书+ChatGPT+cpolar搭建企业智能AI助手并实现无公网ip远程访问

文章目录 推荐 前言环境列表1.飞书设置2.克隆feishu-chatgpt项目3.配置config.yaml文件4.运行feishu-chatgpt项目5.安装cpolar内网穿透6.固定公网地址7.机器人权限配置8.创建版本9.创建测试企业10. 机器人测试 推荐 前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂…

用pandas实现用前一行的excel的值填充后一行

今天接到一份数据需要分析&#xff0c;数据在一个excel文件里&#xff0c;内容大概形式如下&#xff1a; 后面空的格子里的值就是默认是前面的非空的值&#xff0c;由于数据分析的需要需要对重复的数据进行去重&#xff0c;去重就需要把控的cell的值补上&#xff0c;然后根据几…

数字IC后端设计实现 | PR工具中到底应该如何控制density和congestion?(ICC2Innovus)

吾爱IC社区星友提问&#xff1a;请教星主和各位大佬&#xff0c;对于一个模块如果不加干预工具会让inst挤成一团&#xff0c;后面eco修时序就没有空间了。如果全都加instPadding会导致面积不够overlap&#xff0c;大家一般怎么处理这种问题&#xff1f; 在数字IC后端设计实现中…

Python内置的20个高阶函数的功能和示例详解

更多资料获取 &#x1f4da; 个人网站&#xff1a;ipengtao.com Python是一门功能丰富的编程语言&#xff0c;提供了许多内置函数来处理各种数据操作。其中&#xff0c;高阶函数是一类特殊的函数&#xff0c;它们接受其他函数作为参数&#xff0c;或者返回函数作为结果。高阶函…

如何禁用WordPress站点的管理员电子邮件验证或修改检查频率?

今天boke112百科登录某个WordPress站点时&#xff0c;又出现“管理员邮件确认”的提示&#xff0c;要求确认此站点的管理员电子邮箱地址是否仍然正确。具体如下图所示&#xff1a; 如果点击“稍后提醒我”&#xff0c;那么管理员邮件验证页面就会在3天后重新显示。 说实话&…

Unity - 简单音频

“Test_04” AudioTest public class AudioTest : MonoBehaviour {// 声明音频// AudioClippublic AudioClip music;public AudioClip se;// 声明播放器组件private AudioSource player;void Start(){// 获取播放器组件player GetComponent<AudioSource>();// 赋值…

搭建开源数据库中间件MyCat2-配置mysql数据库双主双从

mycat2官网&#xff1a;MyCat2 前言&#xff1a;mycat2下载地址无法访问&#xff0c;不知道是不是被DNS污染了&#xff0c;还是需要搭梯子访问&#xff0c;所以我只能找到1.21的版本进行安装。搭建mycat2的前提是搭建数据库主从复制。 架构&#xff1a;双主双从 配置&#xf…

Verilog基础:强度建模与net型信号的多驱动问题(三)

相关阅读 Verilog基础https://blog.csdn.net/weixin_45791458/category_12263729.html?spm1001.2014.3001.5482 四、一般情况下的net型信号的线与组合&#xff08;线网多驱动&#xff09; 在Verilog基础&#xff1a;强度建模与net型信号的多驱动问题&#xff08;二&#xff0…

成功解决java.nio.charset.MalformedInputException: Input length = 1

项目启动时报错如下 Connected to the target VM, address: 127.0.0.1:5309, transport: socket 18:01:22.607 [main] ERROR o.s.b.SpringApplication - [reportFailure,843] - Application run failed org.yaml.snakeyaml.error.YAMLException: java.nio.charset.MalformedIn…

开年大瓜!Mobileye股价暴跌

编者按&#xff1a;作为汽车智能化的第一波受益者&#xff0c;Mobileye的市场红利已经接近尾声。尤其是汽车芯片市场的白热化竞争&#xff0c;新一轮格局重构正在开启。 汽车智能化的供给关系&#xff0c;正在发生微妙变化。 本周&#xff0c;作为全球主要的辅助驾驶芯片及感知…

Joern环境的安装(Windows版)

Joern环境的安装(Windows版) 网上很少有关于Windows下安装Joern的教程&#xff0c;而我最初使用也是装在Ubuntu虚拟机中&#xff0c;这样使用很占内存&#xff0c;影响体验感。在Windows下使用源码安装Joern也是非常简单的过程&#xff1a; 提前需要的本地环境&#xff1a; …

【大数据】流处理基础概念(一):Dataflow 编程基础、并行流处理

流处理基础概念&#xff08;一&#xff09;&#xff1a;Dataflow 编程基础、并行流处理 1.Dataflow 编程基础1.1 Dataflow 图1.2 数据并行和任务并行1.3 数据交换策略 2.并行流处理2.1 延迟与吞吐2.1.1 延迟2.1.2 吞吐2.1.3 延迟与吞吐 2.2 数据流上的操作2.2.1 数据接入和数据…

GPS位置虚拟软件 AnyGo mac激活版

AnyGo for Mac是一款一键将iPhone的GPS位置更改为任何位置的强大软件&#xff01;使用AnyGo在其iOS或Android设备上改变其GPS位置&#xff0c;并在任何想要的地方显示自己的位置。这对那些需要测试应用程序、游戏或其他依赖于地理位置信息的应用程序的开发人员来说非常有用&…

【网络奇遇记】揭秘计算机网络性能指标:全面指南

&#x1f308;个人主页&#xff1a;聆风吟 &#x1f525;系列专栏&#xff1a;网络奇遇记、数据结构 &#x1f516;少年有梦不应止于心动&#xff0c;更要付诸行动。 文章目录 &#x1f4cb;前言一. 速率1.1 数据量1.2 速率 二. 带宽三. 吞吐量四. 时延4.1 发送时延4.2 传播时延…

苹果电脑(Mac)的node版本安装以及升降级

在开发过程中&#xff0c;对于不同的开发环境或者较老的项目可能需要切换不同的node版本&#xff0c;此过程会涉及到node版本的升级与降级&#xff0c;安装node版本管理模块n&#xff08;sudo命令&#xff09;。 全局安装n模块 sudo npm install n -g//输入后回车&#xff0c…