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
    @ConditionalOnMissingBean
    public 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
    @ConditionalOnMissingBean
    public 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.1
    port: 9200
    username: admin
    password: admin123
    connect-time-out: 1000
    socket-time-out: 30000
    connection-request-time-out: 500
    search-request-time-out: 5000
    max-connect-num: 100
    max-connect-per-route: 100

7、测试

class DemoApplicationTests {
	/**
	 * 获取ElasticsearchUtilTemplate模板
	 */
	@Autowired
	private 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));
}
}

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

安装conda搭建python环境(保姆级教程)

目录 一、Anaconda简介二、Anaconda安装 2.1 Anaconda下载2.2 Anaconda安装2.3 配置环境变量 三、通过conda配置python环境 3.1 创建并激活虚拟环境3.2 管理虚拟环境 一、Anaconda简介 Anaconda 是专门为了方便使用 Python 进行数据科学研究而建立的一组软件包&#xff0c;…

洛谷P5731 【深基5.习6】蛇形方阵(C语言)

思路感觉还是比较好想的。 从 1 到 n 依次算。先往右&#xff0c;走到头往下&#xff0c;再走到头往左&#xff0c;以此类推。 #include<stdio.h>int main() {int n, i, j, k1,t0;scanf("%d", &n);int a[100][100];if (n % 2 0)t n / 2;elset n / 2 …

轻空间气膜游泳馆助您冬日尽情畅游

随着气温逐渐降低&#xff0c;寒冷的冬季让许多热爱游泳的人感到不便。然而&#xff0c;随着气膜建筑技术的不断创新&#xff0c;气膜游泳馆应运而生&#xff0c;为冬日游泳提供了理想场所。其轻盈灵活的结构、优越的保温性能&#xff0c;以及独特的设计理念&#xff0c;让您在…

前端面试题(持续更新~~)

文章目录 一、基础1、数组常用的方法2、数组有哪几种循环方式&#xff1f;分别有什么作用&#xff1f;3、字符串常用的方法4、原型链5、闭包6、常见的继承7、cookie 、localstorage 、 sessionstrorage区别8、数组去重方法9、http 的请求方式10、数据类型的判断方法11、cookie …

Python——基本语法(二)

一、while 循环 语法&#xff1a; while 条件表达式:条件表达示为真&#xff0c;就执⾏这⾥的代码&#xff0c;必须缩进 4 个空格多⾏代码保持缩进⼀致 条件表达式可以是: True # 布尔值的 True 1 < 10 # 凡是在 if 语句中使⽤的判断表达示&#xff0c;这⾥都可以使…

基于SkyEye仿真飞腾处理器:运行U-Boot并加载Phytium-FreeRTOS

仿真平台在帮助提升研发效率、加快产品面市时间上的作用已得到诸多验证&#xff0c;通过对处理器进行仿真来支持嵌入式系统及软件的虚拟化开发、测试和验证成为目前应用较为广泛的方法。天目全数字实时仿真软件SkyEye是一款基于可视化建模的硬件行为级仿真平台&#xff0c;在众…

24 小时经营,15 秒出饮,这台无人饮品机横空出世

随着科技的不断进步&#xff0c;无人饮品机应运而生&#xff0c;它以其 24 小时经营、15 秒出饮的特点&#xff0c;迅速成为人们关注的焦点。 D咖无人饮品机的外观设计简洁大方&#xff0c;体积小巧&#xff0c;操作界面简单易懂&#xff0c;消费者可以通过触屏选择自己喜欢的饮…

Stability AI发布全新代码模型Stable Code 3B

Stable Code 3B: Coding on the Edge 要点&#xff1a; Stable Code 3B 是一个包含 30 亿个参数的大型语言模型 (LLM)&#xff0c;可实现准确且响应灵敏的代码补全&#xff0c;其水平与大 2.5 倍的 CodeLLaMA 7b 等模型相当。即使在 MacBook Air 等普通笔记本电脑上没有 GPU&…

C++ 设计模式之 中介者模式

【声明】本题目来源于卡码网&#xff08;题目页面 (kamacoder.com)&#xff09; 【提示&#xff1a;如果不想看文字介绍&#xff0c;可以直接跳转到C编码部分】 【设计模式大纲】 【简介】 -- 什么是中介者模式 &#xff08;第16种模式&#xff09; 中介者模式&#xff08;Medi…

TCO-AF488,AF488-反式环辛烯,一种明亮的绿色荧光染料

文章关键词&#xff1a;AF488 TCO&#xff0c;Alexa Fluor TCO&#xff0c;TCO AF488&#xff0c;AF488 反式环辛烯 一、基本信息 产品简介&#xff1a;AF488 TCO&#xff0c;这是一款独特的荧光染料&#xff0c;以其鲜明的绿色光华吸引了众人的目光。在成像和流式细胞术中&a…

云HIS为连锁医院机构提供统一医院管理解决方案

云HIS重建统一的信息架构体系&#xff0c;重构管理服务流程&#xff0c;重造病人服务环境&#xff0c;向不同类型的医疗机构提供SaaS化HIS服务解决方案。 云HIS优势 1、云端数据优势 在传统的HIS模式里&#xff0c;数据存于医院本身的服务器机组&#xff0c;一旦发生故障&…

docker-compose安装mongodb

shigen坚持更新文章的博客写手&#xff0c;擅长Java、python、vue、shell等编程语言和各种应用程序、脚本的开发。记录成长&#xff0c;分享认知&#xff0c;留住感动。 早上醒来的第一件事情就是摸了一下手机&#xff0c;看了一下微信相关的技术推文&#xff0c;给我推荐了一篇…

SpringBoot Redis入门(四)——Redis单机、哨兵、集群模式

单机模式&#xff1a;单台缓存服务器&#xff0c;开发、测试环境下使用&#xff1b;哨兵模式&#xff1a;主-从模式&#xff0c;提高缓存服务器的高可用和安全性。所有缓存的数据在每个节点上都一致。每个节点添加监听器&#xff0c;不断监听节点可用状态&#xff0c;一旦主节点…

three.js从入门到精通系列教程002 - three.js正交相机OrthographicCamera

<!DOCTYPE html> <html><head><meta charset"UTF-8"><title>three.js从入门到精通系列教程002 - three.js正交相机OrthographicCamera</title><script src"ThreeJS/three.js"></script><script src&qu…

服务器数据恢复—OceanStor存储raid5热备盘同步数据失败的数据恢复案例

服务器数据恢复环境&#xff1a; 华为OceanStor某型号存储&#xff0c;存储内有一组由24块硬盘组建的raid5阵列&#xff0c;配置1块热备盘。 服务器故障&#xff1a; 该存储raid5阵列中有一块硬盘离线&#xff0c;热备盘自动激活并开始同步数据&#xff0c;在热备盘同步数据的…

【北亚企安数据恢复】RAIDZ多块磁盘离线导致服务器崩溃的数据恢复案例

服务器数据恢复环境&#xff1a; ORACLE SUN ZFS某型号存储&#xff0c;共40块磁盘组建存储池&#xff0c;其中的36块磁盘分为三组&#xff0c;每组12块&#xff0c;单个组使用ZFS特有的RAIDZ管理所有磁盘&#xff0c;RAIDZ级别为2&#xff1b;另外的4块磁盘作为全局热备。存储…

关于 overflow 滚动条(滑动条)配置,简单使用的案例和案例代码

运行环境&#xff1a; Google Chrome 浏览器 前言&#xff1a; 滚动条的样式在CSS中属于伪元素&#xff08;pseudo-element&#xff09;&#xff0c;滚动条的样式则需要通过使用::-webkit-scrollbar 伪元素来定义。 滚动条(滑动条)的区域内包含三个基本部分&#xff0c;轨道…

视频智能识别周界入侵检测AI智能分析网关V4如何配置ONVIF摄像机接入

AI边缘计算智能分析网关V4性能高、功耗低、检测速度快&#xff0c;易安装、易维护&#xff0c;硬件内置了近40种AI算法模型&#xff0c;支持对接入的视频图像进行人、车、物、行为等实时检测分析&#xff0c;上报识别结果&#xff0c;并能进行语音告警播放。算法可按需组合、按…

K8S Informer机制原理解读 | 架构设计

在Kubernetes系统中&#xff0c;组件之间通过HTTP协议进行通信&#xff0c;在不依赖任何中间件的情况下需要保证消息的实时性、可靠性、顺序性等。那么Kubernetes是如何做到的呢&#xff1f;答案就是Informer机制。Kubernetes的其他组件都是通过client-go的Informer机制与Kuber…

12- OpenCV:算子(Sobel和Laplance) 和Canny边缘检测 详解

目录 一、Sobel算子 1、卷积应用-图像边缘提取 2、Sobel算子&#xff08;索贝尔算子&#xff09; 3、相关的API&#xff08;代码例子&#xff09; 二、Laplance算子 1、理论 2、API使用&#xff08;代码例子&#xff09; 三、Canny边缘检测 1、Canny算法介绍 2、API使…