indexMappingFields = clientInterfaceDefault.getIndexMappingFields(indexes.get(j).getIndex());
38 | // log.info("");
39 | // }
40 | // }
41 | //
42 | // }
43 | // }
44 | // log.info("");
45 | // }
46 | }
47 |
--------------------------------------------------------------------------------
/src/main/java/com/example/esbboss/service/zjh/JobStart.java:
--------------------------------------------------------------------------------
1 | package com.example.esbboss.service.zjh;
2 | /**
3 | * Copyright 2023 bboss
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | import com.frameworkset.common.poolman.util.DBConf;
19 | import com.frameworkset.common.poolman.util.SQLManager;
20 | import org.frameworkset.elasticsearch.boot.ElasticSearchBoot;
21 |
22 | import java.util.HashMap;
23 | import java.util.Map;
24 |
25 | /**
26 | *
Description:
27 | *
28 | * Copyright (c) 2023
29 | * @Date 2023/7/28
30 | * @author biaoping.yin
31 | * @version 1.0
32 | */
33 | public class JobStart {
34 | public static void main(String[] args){
35 | //初始化Elasticsearch数据源:
36 | Map properties = new HashMap();
37 | /**
38 | * 这里只设置必须的配置项,其他的属性参考配置文件:resources/application.properties
39 | *
40 | */
41 | ////认证账号和口令配置,如果启用了安全认证才需要,支持xpack和searchguard
42 | // properties.put("elasticUser","elastic");
43 | // properties.put("elasticPassword","changeme");
44 | ////es服务器地址和端口,多个用逗号分隔
45 | // properties.put("elasticsearch.rest.hostNames","127.0.0.1:9200");
46 | ////是否在控制台打印dsl语句,log4j组件日志级别为INFO或者DEBUG
47 | // properties.put("elasticsearch.showTemplate","true");
48 | ////集群节点自动发现
49 | // properties.put("elasticsearch.discoverHost","true");
50 | // properties.put("http.timeoutSocket","60000");
51 | // properties.put("http.timeoutConnection","40000");
52 | // properties.put("http.connectionRequestTimeout","70000");
53 |
54 | properties.put("elasticsearch.serverNames", "hemiao_es");
55 | properties.put("hemiao_es.elasticsearch.rest.hostNames", "es-cn-x0r3bkhai000dw7t4.elasticsearch.aliyuncs.com:9200");
56 | properties.put("hemiao_es.elasticsearch.showTemplate", "true");
57 | properties.put("hemiao_es.elasticUser", "elastic");
58 | properties.put("hemiao_es.elasticPassword", "axsMFaGASJwDTOh3");
59 | properties.put("hemiao_es.elasticsearch.failAllContinue", "true");
60 | properties.put("hemiao_es.http.timeoutSocket", "60000");
61 | properties.put("hemiao_es.http.timeoutConnection", "40000");
62 | properties.put("hemiao_es.http.connectionRequestTimeout", "70000");
63 | properties.put("hemiao_es.http.maxTotal", "200");
64 | properties.put("hemiao_es.http.defaultMaxPerRoute", "100");
65 | ElasticSearchBoot.boot(properties);
66 |
67 |
68 | /**
69 | //从配置文件加载配置:初始化数据库数据源
70 | PropertiesContainer propertiesContainer = PropertiesUtil.getPropertiesContainer("application.properties");
71 | String dbName = propertiesContainer.getProperty("db.name");
72 | String dbUser = propertiesContainer.getProperty("db.user");
73 | String dbPassword = propertiesContainer.getProperty("db.password");
74 | String dbDriver = propertiesContainer.getProperty("db.driver");
75 | String dbUrl = propertiesContainer.getProperty("db.url");
76 |
77 | String showsql = propertiesContainer.getProperty("db.showsql");
78 | String validateSQL = propertiesContainer.getProperty("db.validateSQL");
79 | String dbInfoEncryptClass = propertiesContainer.getProperty("db.dbInfoEncryptClass");
80 |
81 | DBConf tempConf = new DBConf();
82 | tempConf.setPoolname(dbName);
83 | tempConf.setDriver(dbDriver);
84 | tempConf.setJdbcurl(dbUrl);
85 | tempConf.setUsername(dbUser);
86 | tempConf.setPassword(dbPassword);
87 | tempConf.setValidationQuery(validateSQL);
88 | tempConf.setShowsql(showsql != null && showsql.equals("true"));
89 | //tempConf.setTxIsolationLevel("READ_COMMITTED");
90 | tempConf.setJndiName("jndi-"+dbName);
91 | tempConf.setDbInfoEncryptClass(dbInfoEncryptClass);
92 | String initialConnections = propertiesContainer.getProperty("db.initialSize");
93 | int _initialConnections = 10;
94 | if(initialConnections != null && !initialConnections.equals("")){
95 | _initialConnections = Integer.parseInt(initialConnections);
96 | }
97 | String minimumSize = propertiesContainer.getProperty("db.minimumSize");
98 | int _minimumSize = 10;
99 | if(minimumSize != null && !minimumSize.equals("")){
100 | _minimumSize = Integer.parseInt(minimumSize);
101 | }
102 | String maximumSize = propertiesContainer.getProperty("db.maximumSize");
103 | int _maximumSize = 20;
104 | if(maximumSize != null && !maximumSize.equals("")){
105 | _maximumSize = Integer.parseInt(maximumSize);
106 | }
107 | tempConf.setInitialConnections(_initialConnections);
108 | tempConf.setMinimumSize(_minimumSize);
109 | tempConf.setMaximumSize(_maximumSize);
110 | tempConf.setUsepool(false);
111 | tempConf.setExternal(false);
112 | tempConf.setEncryptdbinfo(false);
113 | if(showsql != null && showsql.equalsIgnoreCase("true"))
114 | tempConf.setShowsql(true);
115 | else{
116 | tempConf.setShowsql(false);
117 | }
118 | //# 控制map中的列名采用小写,默认为大写
119 | tempConf.setColumnLableUpperCase(false);
120 | //启动数据源
121 | SQLManager.startPool(tempConf);
122 | */
123 |
124 | // .setDbName("middle_platformsecond")
125 | // .setDbDriver("com.mysql.cj.jdbc.Driver") //数据库驱动程序,必须导入相关数据库的驱动jar包
126 | //
127 | //
128 | // .setDbUrl(jdbcUrl) //通过useCursorFetch=true启用mysql的游标fetch机制,否则会有严重的性能隐患,useCursorFetch必须和jdbcFetchSize参数配合使用,否则不会生效
129 | // .setJdbcFetchSize(-2147483648)
130 | // .setDbUser("sync")
131 | // .setDbPassword("zFfBu21vvfuUzkEE")
132 | // .setValidateSQL("select 1")
133 | // .setUsePool(false)
134 | // .setDbInitSize(5)
135 | // .setDbMinIdleSize(5)
136 | // .setDbMaxSize(10)
137 | // .setShowSql(true);//是否使用连接池;
138 | String jdbcUrl = "jdbc:mysql://192.168.88.10:3306/middle_platform?rewriteBatchedStatements=true&useServerPrepStmts=false&useCompression=true&useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=Asia/Shanghai";
139 |
140 | DBConf tempConf = new DBConf();
141 | tempConf.setPoolname("middle_platform");
142 | tempConf.setDriver("com.mysql.cj.jdbc.Driver");
143 | tempConf.setJdbcurl(jdbcUrl);
144 | tempConf.setUsername("sync");
145 | tempConf.setPassword("zFfBu21vvfuUzkEE");
146 | tempConf.setValidationQuery("select 1");
147 | tempConf.setShowsql(true);
148 | //tempConf.setTxIsolationLevel("READ_COMMITTED");
149 | tempConf.setJndiName("jndi-middle_platform");
150 | // String initialConnections = propertiesContainer.getProperty("db.initialSize");
151 | // int _initialConnections = 10;
152 | // if(initialConnections != null && !initialConnections.equals("")){
153 | // _initialConnections = Integer.parseInt(initialConnections);
154 | // }
155 | // String minimumSize = propertiesContainer.getProperty("db.minimumSize");
156 | // int _minimumSize = 10;
157 | // if(minimumSize != null && !minimumSize.equals("")){
158 | // _minimumSize = Integer.parseInt(minimumSize);
159 | // }
160 | // String maximumSize = propertiesContainer.getProperty("db.maximumSize");
161 | // int _maximumSize = 20;
162 | // if(maximumSize != null && !maximumSize.equals("")){
163 | // _maximumSize = Integer.parseInt(maximumSize);
164 | // }
165 | // tempConf.setInitialConnections(10);
166 | // tempConf.setMinimumSize(20);
167 | // tempConf.setMaximumSize(20);
168 | tempConf.setUsepool(false);
169 |
170 | //# 控制map中的列名采用小写,默认为大写
171 | tempConf.setColumnLableUpperCase(false);
172 | //启动数据源
173 | SQLManager.startPool(tempConf);
174 |
175 | //运行作业,可以不同的作业在不同的线程里面运行
176 | Db2EleasticsearchFullRunOncestore_order_detail_pos.main(args);
177 | Db2EleasticsearchFullRunOncestore_order_pos.main(args);
178 |
179 | }
180 | }
181 |
--------------------------------------------------------------------------------
/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | server.port=808
2 | logging.level.org.bboss=INFO
3 | logging.level.bboss=INFO
4 | logging.level.com.frameworkset=INFO
5 | logging.level.org.frameworkset=INFO
6 |
7 | logging.level.org.apache=INFO
8 | logging.level.com.example=INFO
9 |
10 | spring.elasticsearch.bboss.propertiesInterceptor=com.example.esbboss.service.TestPropertiesInterceptor
11 | # DSL configuration file hot load scan interval, in milliseconds, 5 seconds scan by default, turn off scan mechanism when <= 0
12 | spring.elasticsearch.bboss.dslfile.refreshInterval = -1
13 | ##ES authentication configuration, support for x-pack and searchguard
14 | spring.elasticsearch.bboss.elasticUser=elastic
15 | spring.elasticsearch.bboss.elasticPassword=changeme
16 |
17 | spring.elasticsearch.bboss.elasticsearch.includeTypeName = false
18 | spring.elasticsearch.bboss.elasticsearch.rest.hostNames=192.168.137.1:9200
19 | #spring.elasticsearch.bboss.elasticsearch.rest.hostNames=10.180.211.27:9280,10.180.211.27:9281,10.180.211.27:9282
20 | ##HTTPS configuration, add the https:// protocol header
21 | #spring.elasticsearch.bboss.default.elasticsearch.rest.hostNames=https://10.180.211.27:9280,https://10.180.211.27:9281,https://10.180.211.27:9282
22 | spring.elasticsearch.bboss.elasticsearch.dateFormat=yyyy.MM.dd
23 | spring.elasticsearch.bboss.elasticsearch.timeZone=Asia/Shanghai
24 | #Debug switch to output DSL statement on console: showTemplate,false off, true on, log4j at least info level
25 | spring.elasticsearch.bboss.elasticsearch.showTemplate=false
26 | #spring.elasticsearch.bboss.elasticsearch.logDslCallback=org.frameworkset.elasticsearch.client.LoggerDslCallback
27 |
28 | spring.elasticsearch.bboss.elasticsearch.discoverHost=false
29 |
30 | spring.elasticsearch.bboss.elasticsearch.sliceScrollThreadCount=20
31 |
32 | spring.elasticsearch.bboss.elasticsearch.sliceScrollThreadQueue=20
33 | spring.elasticsearch.bboss.elasticsearch.scrollThreadCount=10
34 |
35 | spring.elasticsearch.bboss.elasticsearch.scrollThreadQueue=10
36 | #spring.elasticsearch.bboss.elasticsearch.slowDslThreshold = 1000
37 | #spring.elasticsearch.bboss.elasticsearch.slowDslCallback=org.bboss.elasticsearchtest.crud.TestSlowDslCallback
38 | ##Elasticsearch restclient HTTP connection pool configuration
39 | spring.elasticsearch.bboss.http.timeoutConnection = 50000
40 | spring.elasticsearch.bboss.http.timeoutSocket = 50000
41 | spring.elasticsearch.bboss.http.connectionRequestTimeout=50000
42 | spring.elasticsearch.bboss.http.retryTime = 1
43 | spring.elasticsearch.bboss.http.maxLineLength = -1
44 | spring.elasticsearch.bboss.http.maxHeaderCount = 200
45 | spring.elasticsearch.bboss.http.maxTotal = 200
46 | spring.elasticsearch.bboss.http.defaultMaxPerRoute = 100
47 | spring.elasticsearch.bboss.http.soReuseAddress = false
48 | spring.elasticsearch.bboss.http.soKeepAlive = false
49 |
50 | spring.elasticsearch.bboss.http.keepAlive = 3600000
51 | spring.elasticsearch.bboss.http.keystore =
52 | spring.elasticsearch.bboss.http.keyPassword =
53 | spring.elasticsearch.bboss.http.backoffAuth=true
54 | # SSL host name validation, whether default configuration is used,
55 | # If the specified as the default, use DefaultHostnameVerifier, otherwise use SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
56 | spring.elasticsearch.bboss.http.hostnameVerifier =
57 |
58 | spring.elasticsearch.bboss.http.evictExpiredConnections=false
59 | spring.elasticsearch.bboss.http.timeToLive = 3600000
60 | #The idle connection is verified every few milliseconds,
61 | # and the invalid connection is automatically released, with <=0 unchecked
62 |
63 | spring.elasticsearch.bboss.http.validateAfterInactivity=2000
64 | # There is a performance overhead to validate connections every time a connection is acquired,
65 | # true:check, false:no check
66 |
67 | spring.elasticsearch.bboss.http.staleConnectionCheckEnabled=false
68 | #* Custom retry control interface. Interface methods must be implemented
69 | #* public interface CustomHttpRequestRetryHandler {
70 | #* public boolean retryRequest(IOException exception, int executionCount, HttpContext context,ClientConfiguration configuration);
71 | #* }
72 | #* Method returns true and retries false without retrying
73 | spring.elasticsearch.bboss.http.customHttpRequestRetryHandler=org.frameworkset.spi.remote.http.ConnectionResetHttpRequestRetryHandler
74 | spring.elasticsearch.bboss.http.httpClientBuilderCallback=com.example.esbboss.HttpClientBuilderCallbackDemo
75 |
76 | # 演示数据库数据导入elasticsearch源配置
77 | # ip地址信息库配置
78 | spring.elasticsearch.bboss.ip.cachesize = 2000
79 | # 库下载地址https://dev.maxmind.com/geoip/geoip2/geolite2/
80 | spring.elasticsearch.bboss.ip.database = d:/geolite2/GeoLite2-City.mmdb
81 | spring.elasticsearch.bboss.ip.asnDatabase = d:/geolite2/GeoLite2-ASN.mmdb
82 |
83 |
84 | # 演示数据库数据导入elasticsearch源配置
85 | spring.elasticsearch.bboss.db.name = test
86 | spring.elasticsearch.bboss.db.user = root
87 | spring.elasticsearch.bboss.db.password = 123456
88 | spring.elasticsearch.bboss.db.driver = com.mysql.cj.jdbc.Driver
89 | #db.url = jdbc:mysql://192.168.137.1:3306/bboss?useCursorFetch=true&useUnicode=true&characterEncoding=utf-8&useSSL=false
90 | ## mysql 5 jdbc配置
91 | #spring.elasticsearch.bboss.db.url = jdbc:mysql://192.168.137.1:3306/bboss?useUnicode=true&characterEncoding=utf-8&useSSL=false&rewriteBatchedStatements=true
92 | ## mysql jdbc 8配置
93 | spring.elasticsearch.bboss.db.url = jdbc:mysql://192.168.137.1:3306/bboss?allowPublicKeyRetrieval=true&useUnicode=true&characterEncoding=utf-8&useSSL=false&rewriteBatchedStatements=true&serverTimezone=Asia/Shanghai
94 | spring.elasticsearch.bboss.db.usePool = true
95 |
96 | spring.elasticsearch.bboss.db.initSize=5
97 | spring.elasticsearch.bboss.db.minIdleSize=5
98 | spring.elasticsearch.bboss.db.maxSize=5
99 |
100 |
101 | spring.elasticsearch.bboss.db.validateSQL = select 1
102 | spring.elasticsearch.bboss.db.showsql = true
103 |
104 | ## 同步状态status管理数据源配置,在同步作业中通过db.name引用并设置default为status表对应的数据库:
105 | ## importBuilder.setStatusDbname("default");
106 | #spring.bboss.db.name = default
107 | #spring.bboss.db.user = root
108 | #spring.bboss.db.password = 123456
109 | #spring.bboss.db.driver = com.mysql.cj.jdbc.Driver
110 | #spring.bboss.db.url = jdbc:mysql://localhost:3306/mysql
111 | #spring.bboss.db.usePool = true
112 | #spring.bboss.db.validateSQL = select 1
113 |
114 |
--------------------------------------------------------------------------------
/src/main/resources/dbbulktest.xml:
--------------------------------------------------------------------------------
1 |
2 |
28 |
29 |
30 |
31 |
34 |
35 |
36 |
--------------------------------------------------------------------------------
/src/main/resources/esmapper/demo.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
54 |
55 |
56 |
68 |
69 |
92 |
93 |
94 |
95 |
--------------------------------------------------------------------------------
/src/main/resources/esmapper/sentence_paragrah.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | java python javascriptoracle mysql sqlserver
"],
8 | "analyzer": "simple1_mainContent"
9 | }]]>
10 |
11 |
12 |
13 | java python javascriptoracle mysql sqlserver
"],
15 | "analyzer": "simple2_mainContent"
16 | }]]>
17 |
18 |
19 |
20 | => \u0020paragraph\u0020""",
40 | @""" => \u0020sentence\u0020paragraph\u0020""",
41 | @""" => \u0020paragraph\u0020""",
42 | @"""
=> \u0020sentence\u0020paragraph\u0020""",
43 | @""" => \u0020paragraph\u0020""",
44 | @"""
=> \u0020sentence\u0020paragraph\u0020""",
45 | @"""! => \u0020sentence\u0020""",
46 | @"""? => \u0020sentence\u0020""",
47 | @"""。=> \u0020sentence\u0020""",
48 | @"""?=> \u0020sentence\u0020""",
49 | @"""!=> \u0020sentence\u0020"""
50 | ]
51 | }
52 | }
53 | }
54 | },
55 | "mappings": {
56 | "properties": {
57 | "mainContent": {
58 | "type": "text",
59 | "analyzer": "simple1_mainContent",
60 | "search_analyzer": "ik_smart"
61 | }
62 | }
63 | }
64 | }]]>
65 |
66 |
67 |
68 |
69 | java python javascriptoracle mysql sqlserver
"}
72 | ]]>
73 |
74 |
75 |
76 |
77 |
112 |
113 |
114 |
115 |
116 | => \u0020paragraph\u0020""",
135 | @""" => \u0020sentence\u0020paragraph\u0020""",
136 | @""" => \u0020paragraph\u0020""",
137 | @"""
=> \u0020sentence\u0020paragraph\u0020""",
138 | @""" => \u0020paragraph\u0020""",
139 | @"""
=> \u0020sentence\u0020paragraph\u0020""",
140 | @"""! => \u0020sentence\u0020""",
141 | @"""? => \u0020sentence\u0020""",
142 | @"""。=> \u0020sentence\u0020""",
143 | @"""?=> \u0020sentence\u0020""",
144 | @"""\n => \u0020sentence\u0020paragraph\u0020""",
145 | @"""!=> \u0020sentence\u0020"""
146 | ]
147 | }
148 | }
149 | }
150 | },
151 | "mappings": {
152 | "properties": {
153 | "mainContent": {
154 | "type": "text",
155 | "analyzer": "simple2_mainContent",
156 | "search_analyzer": "ik_smart"
157 | }
158 | }
159 | }
160 | }]]>
161 |
162 |
163 |
164 |
165 |
169 |
170 |
171 |
--------------------------------------------------------------------------------
/src/main/resources/esmapper/span_query.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
20 |
21 |
22 |
23 |
24 |
30 |
31 |
32 |
33 |
34 |
43 |
44 |
45 |
46 |
47 |
71 |
72 |
73 |
74 |
75 |
110 |
111 |
--------------------------------------------------------------------------------
/src/main/resources/sqlFile.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
7 |
8 | #[log_id]]]>
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/src/test/java/com/example/esbboss/service/RestClientTest.java:
--------------------------------------------------------------------------------
1 | package com.example.esbboss.service;
2 | /**
3 | * Copyright 2008 biaoping.yin
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | import com.example.esbboss.entity.Demo;
19 | import com.example.esbboss.entity.DemoSearchResult;
20 | import org.frameworkset.elasticsearch.ElasticSearchException;
21 | import org.frameworkset.elasticsearch.boot.BBossESStarter;
22 | import org.frameworkset.elasticsearch.client.ClientInterface;
23 | import org.frameworkset.elasticsearch.entity.ESDatas;
24 | import org.junit.Test;
25 | import org.junit.runner.RunWith;
26 | import org.slf4j.Logger;
27 | import org.slf4j.LoggerFactory;
28 | import org.springframework.beans.factory.annotation.Autowired;
29 | import org.springframework.boot.test.context.SpringBootTest;
30 | import org.springframework.test.context.junit4.SpringRunner;
31 |
32 | import java.text.DateFormat;
33 | import java.text.ParseException;
34 | import java.text.SimpleDateFormat;
35 | import java.util.Date;
36 | import java.util.HashMap;
37 | import java.util.List;
38 | import java.util.Map;
39 |
40 | /**
41 | *
Description: for Elasticsearch 1.x,2.x,5.x,6.x,+
42 | *
43 | * Copyright (c) 2018
44 | * @Date 2019/9/18 10:27
45 | * @author biaoping.yin
46 | * @version 1.0
47 | */
48 | @RunWith(SpringRunner.class)
49 | @SpringBootTest
50 | public class RestClientTest {
51 | private Logger logger = LoggerFactory.getLogger(RestClientTest.class);
52 | @Autowired
53 | private BBossESStarter bbossESStarter;
54 | //DSL config file path
55 | private String mappath = "esmapper/demo.xml";
56 |
57 | @Test
58 | public void test(){
59 | this.dropAndCreateAndGetIndice();
60 | addAndUpdateDocument();
61 | searchAllPararrel();
62 | this.search();
63 | this.deleteDocuments();
64 | }
65 | public void dropAndCreateAndGetIndice(){
66 | //Create a client tool to load configuration files, single instance multithreaded security
67 | ClientInterface clientUtil = bbossESStarter.getConfigRestClient(mappath);
68 | try {
69 | //To determine whether the indice demo exists, it returns true if it exists and false if it does not
70 | boolean exist = clientUtil.existIndice("demo");
71 |
72 | //Delete mapping if the indice demo already exists
73 | if(exist) {
74 | String r = clientUtil.dropIndice("demo");
75 | logger.debug("clientUtil.dropIndice(\"demo\") response:"+r);
76 |
77 | }
78 | //Create index demo
79 | clientUtil.createIndiceMapping("demo",//The indice name
80 | "createDemoIndice");//Index mapping DSL script name, defined createDemoIndice in esmapper/demo.xml
81 |
82 | String demoIndice = clientUtil.getIndice("demo");//Gets the newly created indice structure
83 | logger.info("after createIndiceMapping clientUtil.getIndice(\"demo\") response:"+demoIndice);
84 | } catch (ElasticSearchException e) {
85 | // TODO Auto-generated catch block
86 | e.printStackTrace();
87 | }
88 |
89 | }
90 |
91 |
92 |
93 | public void addAndUpdateDocument() {
94 | //Build a create/modify/get/delete document client object, single instance multi-thread security
95 | ClientInterface clientUtil = bbossESStarter.getRestClient();
96 | //Build an object as index document
97 | Demo demo = new Demo();
98 | demo.setDemoId(2l);//Specify the document id, the unique identity, and mark with the @ESId annotation. If the demoId already exists, modify the document; otherwise, add the document
99 | demo.setAgentStarttime(new Date());
100 | demo.setAgentStarttimezh(new Date());
101 | demo.setApplicationName("blackcatdemo2");
102 | demo.setContentbody("this is content body2");
103 | demo.setName("liudehua");
104 | demo.setOrderId("NFZF15045871807281445364228");
105 | demo.setContrastStatus(2);
106 |
107 |
108 | //Add the document and force refresh
109 | String response = clientUtil.addDocument("demo",//indice name
110 | "demo",//idnex type
111 | demo,"refresh=true");
112 |
113 |
114 |
115 | logger.debug("Print the result:addDocument-------------------------");
116 | logger.debug(response);
117 |
118 | demo = new Demo();
119 | demo.setDemoId(3l);//Specify the document id, the unique identity, and mark with the @ESId annotation. If the demoId already exists, modify the document; otherwise, add the document
120 | demo.setAgentStarttime(new Date());
121 | demo.setApplicationName("blackcatdemo3");
122 | demo.setContentbody("this is content body3");
123 | demo.setName("zhangxueyou");
124 | demo.setOrderId("NFZF15045871807281445364228");
125 | demo.setContrastStatus(3);
126 | demo.setAgentStarttime(new Date());
127 | demo.setAgentStarttimezh(new Date());
128 |
129 | //Add the document and force refresh
130 | response = clientUtil.addDocument("demo",//indice name
131 | "demo",//idnex type
132 | demo,"refresh=true");
133 |
134 | //Get the document object according to the document id, and return the Demo object
135 | demo = clientUtil.getDocument("demo",//indice name
136 | "demo",//idnex type
137 | "2",//document id
138 | Demo.class);
139 |
140 | //update document
141 | demo = new Demo();
142 | demo.setDemoId(2l);//Specify the document id, the unique identity, and mark with the @ESId annotation. If the demoId already exists, modify the document; otherwise, add the document
143 | demo.setAgentStarttime(new Date());
144 | demo.setApplicationName("blackcatdemo2");
145 | demo.setContentbody("this is modify content body2");
146 | demo.setName("刘德华modify\t");
147 | demo.setOrderId("NFZF15045871807281445364228");
148 | demo.setContrastStatus(2);
149 | demo.setAgentStarttimezh(new Date());
150 | //Execute update and force refresh
151 | response = clientUtil.addDocument("demo",//index name
152 | "demo",//idnex type
153 | demo,"refresh=true");
154 |
155 |
156 | //Get the modified document object according to the document id and return the json message string
157 | response = clientUtil.getDocument("demo",//indice name
158 | "demo",//idnex type
159 | "2");//document id
160 | logger.debug("Print the modified result:getDocument-------------------------");
161 | logger.debug(response);
162 |
163 |
164 |
165 |
166 | logger.debug("Print the modified result:getDocument-------------------------");
167 | logger.debug(response);
168 |
169 |
170 | }
171 |
172 | public void deleteDocuments(){
173 | //Build a create/modify/get/delete document client object, single instance multi-thread security
174 | ClientInterface clientUtil = bbossESStarter.getRestClient();
175 | //Batch delete documents
176 | clientUtil.deleteDocuments("demo",//indice name
177 | "demo",//idnex type
178 | new String[]{"2","3"});//Batch delete document ids
179 | }
180 |
181 | /**
182 | * Use slice parallel scoll query all documents of indice demo by 2 thread tasks. DEFAULT_FETCHSIZE is 5000
183 | */
184 | public void searchAllPararrel(){
185 | ClientInterface clientUtil = bbossESStarter.getRestClient();
186 | ESDatas esDatas = clientUtil.searchAllParallel("demo", Demo.class,2);
187 | }
188 |
189 |
190 |
191 | /**
192 | * Search the documents
193 | */
194 | public DemoSearchResult search() {
195 | //Create a load DSL file client instance to retrieve documents, single instance multithread security
196 | ClientInterface clientUtil = bbossESStarter.getConfigRestClient(mappath);
197 | //Set query conditions, pass variable parameter values via map,key for variable names in DSL
198 | //There are four variables in the DSL:
199 | // applicationName1
200 | // applicationName2
201 | // startTime
202 | // endTime
203 | Map params = new HashMap();
204 | //Set the values of applicationName1 and applicationName2 variables
205 | params.put("applicationName1","blackcatdemo2");
206 | params.put("applicationName2","blackcatdemo3");
207 | DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
208 | //Set the time range, and accept the long value as the time parameter
209 | try {
210 | params.put("startTime",dateFormat.parse("2017-09-02 00:00:00").getTime());
211 | } catch (ParseException e) {
212 | e.printStackTrace();
213 | }
214 | params.put("endTime",new Date().getTime());
215 |
216 |
217 | //Execute the query
218 | ESDatas esDatas = //ESDatas contains a collection of currently retrieved records, up to 1000 records, specified by the size attribute in the DSL
219 | clientUtil.searchList("demo/_search",//demo as the indice, _search as the search action
220 | "searchDatas",//DSL statement name defined in esmapper/demo.xml
221 | params,//Query parameters
222 | Demo.class);//Data object type Demo returned
223 |
224 |
225 | //Gets a list of result objects and returns max up to 1000 records (specified in DSL)
226 | List demos = esDatas.getDatas();
227 |
228 | // String json = clientUtil.executeRequest("demo/_search",//demo as the index table, _search as the search action
229 | // "searchDatas",//DSL statement name defined in esmapper/demo.xml
230 | // params);//Query parameters
231 |
232 | // String json = com.frameworkset.util.SimpleStringUtil.object2json(demos);
233 | //Gets the total number of records
234 | long totalSize = esDatas.getTotalSize();
235 | DemoSearchResult demoSearchResult = new DemoSearchResult();
236 | demoSearchResult.setDemos(demos);
237 | demoSearchResult.setTotalSize(totalSize);
238 | return demoSearchResult;
239 | }
240 | }
241 |
--------------------------------------------------------------------------------
/src/test/java/com/example/esbboss/service/RestClientTest7.java:
--------------------------------------------------------------------------------
1 | package com.example.esbboss.service;
2 | /**
3 | * Copyright 2008 biaoping.yin
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | import com.example.esbboss.entity.Demo;
19 | import com.example.esbboss.entity.DemoSearchResult;
20 | import org.frameworkset.elasticsearch.ElasticSearchException;
21 | import org.frameworkset.elasticsearch.boot.BBossESStarter;
22 | import org.frameworkset.elasticsearch.client.ClientInterface;
23 | import org.frameworkset.elasticsearch.entity.ESDatas;
24 | import org.junit.Test;
25 | import org.junit.runner.RunWith;
26 | import org.slf4j.Logger;
27 | import org.slf4j.LoggerFactory;
28 | import org.springframework.beans.factory.annotation.Autowired;
29 | import org.springframework.boot.test.context.SpringBootTest;
30 | import org.springframework.test.context.junit4.SpringRunner;
31 |
32 | import java.text.DateFormat;
33 | import java.text.ParseException;
34 | import java.text.SimpleDateFormat;
35 | import java.util.Date;
36 | import java.util.HashMap;
37 | import java.util.List;
38 | import java.util.Map;
39 |
40 | /**
41 | *
Description: for Elasticsearch 7.x,8.x,+
42 | *
43 | * Copyright (c) 2018
44 | * @Date 2019/9/18 10:27
45 | * @author biaoping.yin
46 | * @version 1.0
47 | */
48 | @RunWith(SpringRunner.class)
49 | @SpringBootTest
50 | public class RestClientTest7 {
51 | private Logger logger = LoggerFactory.getLogger(RestClientTest7.class);
52 | @Autowired
53 | private BBossESStarter bbossESStarter;
54 | //DSL config file path
55 | private String mappath = "esmapper/demo7.xml";
56 |
57 | @Test
58 | public void test(){
59 | this.dropAndCreateAndGetIndice();
60 | addAndUpdateDocument();
61 | searchAllPararrel();
62 | this.search();
63 | this.deleteDocuments();
64 | }
65 | public void dropAndCreateAndGetIndice(){
66 | //Create a client tool to load configuration files, single instance multithreaded security
67 | ClientInterface clientUtil = bbossESStarter.getConfigRestClient(mappath);
68 | try {
69 | //To determine whether the indice demo exists, it returns true if it exists and false if it does not
70 | boolean exist = clientUtil.existIndice("demo");
71 |
72 | //Delete mapping if the indice demo already exists
73 | if(exist) {
74 | String r = clientUtil.dropIndice("demo");
75 | logger.debug("clientUtil.dropIndice(\"demo\") response:"+r);
76 |
77 | }
78 | //Create index demo
79 | clientUtil.createIndiceMapping("demo",//The indice name
80 | "createDemoIndice");//Index mapping DSL script name, defined createDemoIndice in esmapper/demo.xml
81 |
82 | String demoIndice = clientUtil.getIndice("demo");//Gets the newly created indice structure
83 | logger.info("after createIndiceMapping clientUtil.getIndice(\"demo\") response:"+demoIndice);
84 | } catch (ElasticSearchException e) {
85 | // TODO Auto-generated catch block
86 | e.printStackTrace();
87 | }
88 |
89 | }
90 |
91 |
92 |
93 | public void addAndUpdateDocument() {
94 | //Build a create/modify/get/delete document client object, single instance multi-thread security
95 | ClientInterface clientUtil = bbossESStarter.getRestClient();
96 | //Build an object as index document
97 | Demo demo = new Demo();
98 | demo.setDemoId(2l);//Specify the document id, the unique identity, and mark with the @ESId annotation. If the demoId already exists, modify the document; otherwise, add the document
99 | demo.setAgentStarttime(new Date());
100 | demo.setAgentStarttimezh(new Date());
101 | demo.setApplicationName("blackcatdemo2");
102 | demo.setContentbody("this is content body2");
103 | demo.setName("liudehua");
104 | demo.setOrderId("NFZF15045871807281445364228");
105 | demo.setContrastStatus(2);
106 |
107 |
108 | //Add the document and force refresh
109 | String response = clientUtil.addDocument("demo",//indice name
110 | demo,"refresh=true");
111 |
112 |
113 |
114 | logger.debug("Print the result:addDocument-------------------------");
115 | logger.debug(response);
116 |
117 | demo = new Demo();
118 | demo.setDemoId(3l);//Specify the document id, the unique identity, and mark with the @ESId annotation. If the demoId already exists, modify the document; otherwise, add the document
119 | demo.setAgentStarttime(new Date());
120 | demo.setApplicationName("blackcatdemo3");
121 | demo.setContentbody("this is content body3");
122 | demo.setName("zhangxueyou");
123 | demo.setOrderId("NFZF15045871807281445364228");
124 | demo.setContrastStatus(3);
125 | demo.setAgentStarttime(new Date());
126 | demo.setAgentStarttimezh(new Date());
127 |
128 | //Add the document and force refresh
129 | response = clientUtil.addDocument("demo",//indice name
130 | demo,"refresh=true");
131 |
132 | //Get the document object according to the document id, and return the Demo object
133 | demo = clientUtil.getDocument("demo",//indice name
134 | "2",//document id
135 | Demo.class);
136 |
137 | //update document
138 | demo = new Demo();
139 | demo.setDemoId(2l);//Specify the document id, the unique identity, and mark with the @ESId annotation. If the demoId already exists, modify the document; otherwise, add the document
140 | demo.setAgentStarttime(new Date());
141 | demo.setApplicationName("blackcatdemo2");
142 | demo.setContentbody("this is modify content body2");
143 | demo.setName("刘德华modify\t");
144 | demo.setOrderId("NFZF15045871807281445364228");
145 | demo.setContrastStatus(2);
146 | demo.setAgentStarttimezh(new Date());
147 | //Execute update and force refresh
148 | response = clientUtil.addDocument("demo",//index name
149 | demo,"refresh=true");
150 |
151 |
152 | //Get the modified document object according to the document id and return the json message string
153 | response = clientUtil.getDocument("demo",//indice name
154 | "2");//document id
155 | logger.debug("Print the modified result:getDocument-------------------------");
156 | logger.debug(response);
157 |
158 |
159 |
160 |
161 | logger.debug("Print the modified result:getDocument-------------------------");
162 | logger.debug(response);
163 |
164 |
165 | }
166 |
167 | public void deleteDocuments(){
168 | //Build a create/modify/get/delete document client object, single instance multi-thread security
169 | ClientInterface clientUtil = bbossESStarter.getRestClient();
170 | //Batch delete documents
171 | clientUtil.deleteDocuments("demo",//indice name
172 | new String[]{"2","3"});//Batch delete document ids
173 | }
174 |
175 | /**
176 | * Use slice parallel scoll query all documents of indice demo by 2 thread tasks. DEFAULT_FETCHSIZE is 5000
177 | */
178 | public void searchAllPararrel(){
179 | ClientInterface clientUtil = bbossESStarter.getRestClient();
180 | ESDatas esDatas = clientUtil.searchAllParallel("demo", Demo.class,2);
181 | }
182 |
183 |
184 |
185 | /**
186 | * Search the documents
187 | */
188 | public DemoSearchResult search() {
189 | //Create a load DSL file client instance to retrieve documents, single instance multithread security
190 | ClientInterface clientUtil = bbossESStarter.getConfigRestClient(mappath);
191 | //Set query conditions, pass variable parameter values via map,key for variable names in DSL
192 | //There are four variables in the DSL:
193 | // applicationName1
194 | // applicationName2
195 | // startTime
196 | // endTime
197 | Map params = new HashMap();
198 | //Set the values of applicationName1 and applicationName2 variables
199 | params.put("applicationName1","blackcatdemo2");
200 | params.put("applicationName2","blackcatdemo3");
201 | DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
202 | //Set the time range, and accept the long value as the time parameter
203 | try {
204 | params.put("startTime",dateFormat.parse("2017-09-02 00:00:00").getTime());
205 | } catch (ParseException e) {
206 | e.printStackTrace();
207 | }
208 | params.put("endTime",new Date().getTime());
209 |
210 |
211 | //Execute the query
212 | ESDatas esDatas = //ESDatas contains a collection of currently retrieved records, up to 1000 records, specified by the size attribute in the DSL
213 | clientUtil.searchList("demo/_search",//demo as the indice, _search as the search action
214 | "searchDatas",//DSL statement name defined in esmapper/demo.xml
215 | params,//Query parameters
216 | Demo.class);//Data object type Demo returned
217 |
218 |
219 | //Gets a list of result objects and returns max up to 1000 records (specified in DSL)
220 | List demos = esDatas.getDatas();
221 |
222 | // String json = clientUtil.executeRequest("demo/_search",//demo as the index table, _search as the search action
223 | // "searchDatas",//DSL statement name defined in esmapper/demo.xml
224 | // params);//Query parameters
225 |
226 | // String json = com.frameworkset.util.SimpleStringUtil.object2json(demos);
227 | //Gets the total number of records
228 | long totalSize = esDatas.getTotalSize();
229 | DemoSearchResult demoSearchResult = new DemoSearchResult();
230 | demoSearchResult.setDemos(demos);
231 | demoSearchResult.setTotalSize(totalSize);
232 | return demoSearchResult;
233 | }
234 | }
235 |
--------------------------------------------------------------------------------