├── .gitattributes ├── .gitignore ├── LICENSE ├── README.md ├── pom.xml └── src ├── main ├── java │ ├── com │ │ └── example │ │ │ └── esbboss │ │ │ └── entity │ │ │ ├── Demo.java │ │ │ ├── DemoSearchResult.java │ │ │ ├── DemoWithES7Index.java │ │ │ ├── DemoWithESIndex.java │ │ │ ├── FieldDemo.java │ │ │ ├── MetaDemo.java │ │ │ ├── NewDemo.java │ │ │ └── UUIDDemo.java │ └── org │ │ └── bboss │ │ └── elasticsearchtest │ │ └── springboot │ │ ├── Application.java │ │ ├── MultiESSTartConfigurer.java │ │ ├── TestPropertiesInterceptor.java │ │ ├── bulk │ │ ├── TestBulkProcessor.java │ │ └── TestBulkProcessor7x.java │ │ ├── crud │ │ ├── DemoWithES7Index.java │ │ ├── DocumentCRUD.java │ │ ├── DocumentCRUD7.java │ │ ├── MultiES7DocumentCRUD.java │ │ └── MultiESDocumentCRUD.java │ │ ├── script │ │ ├── DynamicPriceTemplate.java │ │ ├── Rule.java │ │ ├── ScriptImpl.java │ │ └── ScriptImpl7.java │ │ └── thirddslcontainer │ │ ├── DocumentCRUD.java │ │ ├── DocumentCRUD7.java │ │ ├── HighlightSearch.java │ │ ├── HighlightSearch7.java │ │ ├── ScriptImpl.java │ │ └── ScriptImpl7.java └── resources │ ├── application-multi-datasource.yml │ ├── application.yml │ ├── config │ ├── application-multi-datasource.properties.example │ └── application.properties.example │ ├── esmapper │ ├── demo.xml │ ├── demo7.xml │ └── scroll.xml │ └── log4j2.yaml └── test └── java └── org └── bboss └── elasticsearchtest └── springboot ├── BBossES7StarterTestCase.java ├── BBossESStarterTestCase.java ├── BulkProcessor7Test.java ├── BulkProcessorTest.java ├── MultiBBossES7StartersTestCase.java ├── MultiBBossESStartersTestCase.java ├── MultiES7RestClientTest.java ├── MultiESRestClientTest.java ├── RestClient7Test.java ├── RestClientTest.java ├── ScriptImpl7Test.java ├── ScriptImplTest.java ├── SimpleBBossESStarterTestCase.java └── thirddslcontainer ├── TestThirdDslContainer.java └── TestThirdDslContainer7.java /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | 7 | # Standard to msysgit 8 | *.doc diff=astextplain 9 | *.DOC diff=astextplain 10 | *.docx diff=astextplain 11 | *.DOCX diff=astextplain 12 | *.dot diff=astextplain 13 | *.DOT diff=astextplain 14 | *.pdf diff=astextplain 15 | *.PDF diff=astextplain 16 | *.rtf diff=astextplain 17 | *.RTF diff=astextplain 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Windows thumbnail cache files 2 | Thumbs.db 3 | ehthumbs.db 4 | ehthumbs_vista.db 5 | 6 | # Folder config file 7 | Desktop.ini 8 | 9 | # Recycle Bin used on file shares 10 | $RECYCLE.BIN/ 11 | 12 | # Windows Installer files 13 | *.cab 14 | *.msi 15 | *.msm 16 | *.msp 17 | 18 | # Windows shortcuts 19 | *.lnk 20 | 21 | # ========================= 22 | # Operating System Files 23 | # ========================= 24 | /target/ 25 | /.settings/ 26 | /.classpath 27 | /.project 28 | 29 | *.iml 30 | eshelloword-spring-boot-starter.iml -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 |  2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Bboss is a good elasticsearch Java rest client. It operates and accesses elasticsearch in a way similar to mybatis. 2 | 3 | # BBoss Environmental requirements 4 | 5 | JDK requirement: JDK 1.8+ 6 | 7 | Elasticsearch version requirements: 1.X,2.X,5.X,6.X,+ 8 | 9 | Spring booter 1.x,2.x,+ 10 | # 基于bboss es spring boot starter的maven工程 11 | 本实例是一个基于bboss es spring boot starter的demo maven工程,可供spring boot项目集成bboss elasticsearch rest client参考 12 | 13 | 展示了通过spring boot管理单集群功能和管理多集群功能 14 | 15 | 单集群测试用例:eshelloword-spring-boot-starter\src\test\java\org\bboss\elasticsearchtest\springboot\BBossESStarterTestCase.java 16 | * 单集群演示功能测试用例,spring boot配置项以spring.elasticsearch.bboss开头 17 | * 对应的配置文件为application.properties文件 18 | 19 | 多集群测试用例:eshelloword-spring-boot-starter\src\test\java\org\bboss\elasticsearchtest\springboot\MultiBBossESStartersTestCase.java 20 | * 多集群演示功能测试用例,spring boot配置项以spring.elasticsearch.bboss.集群名称开头,例如: 21 | * spring.elasticsearch.bboss.default 默认es集群 22 | * spring.elasticsearch.bboss.logs logs es集群 23 | * 两个集群通过 org.bboss.elasticsearchtest.springboot.MultiESSTartConfigurer加载 24 | * 对应的配置文件为application-multi-datasource.properties文件 25 | 26 | # 运行demo 27 | src/test/java目录下面提供提供两个可以直接运行的的junit测试用例 28 | ## 单集群测试用例运行 29 | org.bboss.elasticsearchtest.springboot.BBossESStarterTestCase 30 | ## 多集群测试用例运行 31 | org.bboss.elasticsearchtest.springboot.MultiBBossESStartersTestCase 32 | 33 | ## 在spring booter项目中配置es参数 34 | yml配置(默认配置) 35 | 单es集群配置,修改spring booter项目的配置文件:eshelloword-spring-boot-starter\src\main\resources\application.yml 36 | 37 | 多es集群配置,修改spring booter项目的配置文件:eshelloword-spring-boot-starter\src\main\resources\application-multi-datasource.yml 38 | 39 | properties配置:如果需要采用properties配置,则将下面的两个文件拷贝到resources目录下面,把后缀.example去掉即可,记住yml和properties只能保留一个 40 | 41 | 单es集群配置,修改spring booter项目的配置文件:eshelloword-spring-boot-starter\src\main\resources\config\application.properties.example 42 | 43 | 多es集群配置,修改spring booter项目的配置文件:eshelloword-spring-boot-starter\src\main\resources\config\application-multi-datasource.properties.example 44 | 45 | ## 快速集成和应用 46 | 47 | 非spring boot项目: 48 | 49 | https://esdoc.bbossgroups.com/#/common-project-with-bboss 50 | 51 | spring boot项目: 52 | 53 | https://esdoc.bbossgroups.com/#/spring-booter-with-bboss 54 | 55 | 详细配置说明参考文档: 56 | 57 | https://esdoc.bbossgroups.com/#/development 58 | 59 | ## 开发交流群 60 | 166471282 61 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | 1.8 8 | 1.8 9 | 10 | org.bboss.eshelloword 11 | eshelloword-spring-boot-starter 12 | 1.0-SNAPSHOT 13 | 14 | 15 | com.bbossgroups.plugins 16 | bboss-elasticsearch-spring-boot-starter 17 | 7.3.8 18 | 25 | 26 | 27 | com.bbossgroups.plugins 28 | bboss-datatran-jdbc 29 | 7.3.8 30 | 31 | 32 | org.xerial 33 | sqlite-jdbc 34 | 3.42.0.0 35 | test 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | org.apache.logging.log4j 46 | log4j-slf4j-impl 47 | 2.24.3 48 | 49 | 50 | 51 | org.apache.logging.log4j 52 | log4j-api 53 | 2.24.3 54 | 55 | 56 | 57 | org.apache.logging.log4j 58 | log4j-core 59 | 2.24.3 60 | 61 | 62 | com.fasterxml.jackson.dataformat 63 | jackson-dataformat-yaml 64 | 2.18.2 65 | 66 | 67 | org.springframework.boot 68 | spring-boot-starter-test 69 | test 70 | 71 | 72 | logback-classic 73 | ch.qos.logback 74 | 75 | 76 | log4j-to-slf4j 77 | org.apache.logging.log4j 78 | 79 | 80 | 2.7.12 81 | 82 | 83 | 84 | org.springframework.boot 85 | spring-boot-autoconfigure 86 | 87 | 88 | logback-classic 89 | ch.qos.logback 90 | 91 | 92 | 2.7.12 93 | 94 | 95 | org.springframework.boot 96 | spring-boot-configuration-processor 97 | 98 | 99 | logback-classic 100 | ch.qos.logback 101 | 102 | 103 | 2.7.12 104 | 105 | 106 | junit 107 | junit 108 | test 109 | 4.13.2 110 | 111 | 112 | org.yaml 113 | snakeyaml 114 | 2.2 115 | 116 | 117 | 118 | -------------------------------------------------------------------------------- /src/main/java/com/example/esbboss/entity/Demo.java: -------------------------------------------------------------------------------- 1 | package com.example.esbboss.entity;/* 2 | * Copyright 2008 biaoping.yin 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | import com.fasterxml.jackson.annotation.JsonFormat; 19 | import com.frameworkset.orm.annotation.Column; 20 | import com.frameworkset.orm.annotation.ESId; 21 | import org.frameworkset.elasticsearch.entity.ESBaseData; 22 | 23 | import java.util.Date; 24 | 25 | /** 26 | * 测试实体,可以从ESBaseData对象继承meta属性,检索时会将文档的一下meta属性设置到对象实例中 27 | */ 28 | public class Demo extends ESBaseData { 29 | private Object dynamicPriceTemplate; 30 | //设定文档标识字段 31 | @ESId(readSet = true,persistent = false) 32 | private Long demoId; 33 | private String contentbody; 34 | /** 当在mapping定义中指定了日期格式时,则需要指定以下两个注解,例如 35 | * 36 | "agentStarttime": { 37 | "type": "date",###指定多个日期格式 38 | "format":"yyyy-MM-dd HH:mm:ss.SSS||yyyy-MM-dd'T'HH:mm:ss.SSS||yyyy-MM-dd HH:mm:ss||epoch_millis" 39 | } 40 | @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS") 41 | @Column(dataformat = "yyyy-MM-dd HH:mm:ss.SSS") 42 | */ 43 | 44 | protected Date agentStarttime; 45 | 46 | public Date getAgentStarttimezh() { 47 | return agentStarttimezh; 48 | } 49 | 50 | public void setAgentStarttimezh(Date agentStarttimezh) { 51 | this.agentStarttimezh = agentStarttimezh; 52 | } 53 | @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS") 54 | @Column(dataformat = "yyyy-MM-dd HH:mm:ss.SSS") 55 | protected Date agentStarttimezh; 56 | private String applicationName; 57 | private String orderId; 58 | private int contrastStatus; 59 | 60 | public String getName() { 61 | return name; 62 | } 63 | 64 | public void setName(String name) { 65 | this.name = name; 66 | } 67 | 68 | private String name; 69 | 70 | public String getContentbody() { 71 | return contentbody; 72 | } 73 | 74 | public void setContentbody(String contentbody) { 75 | this.contentbody = contentbody; 76 | } 77 | 78 | public Date getAgentStarttime() { 79 | return agentStarttime; 80 | } 81 | 82 | public void setAgentStarttime(Date agentStarttime) { 83 | this.agentStarttime = agentStarttime; 84 | } 85 | 86 | public String getApplicationName() { 87 | return applicationName; 88 | } 89 | 90 | public void setApplicationName(String applicationName) { 91 | this.applicationName = applicationName; 92 | } 93 | 94 | public Long getDemoId() { 95 | return demoId; 96 | } 97 | 98 | public void setDemoId(Long demoId) { 99 | this.demoId = demoId; 100 | } 101 | 102 | public Object getDynamicPriceTemplate() { 103 | return dynamicPriceTemplate; 104 | } 105 | 106 | public void setDynamicPriceTemplate(Object dynamicPriceTemplate) { 107 | this.dynamicPriceTemplate = dynamicPriceTemplate; 108 | } 109 | 110 | public String getOrderId() { 111 | return orderId; 112 | } 113 | 114 | public void setOrderId(String orderId) { 115 | this.orderId = orderId; 116 | } 117 | 118 | public int getContrastStatus() { 119 | return contrastStatus; 120 | } 121 | 122 | public void setContrastStatus(int contrastStatus) { 123 | this.contrastStatus = contrastStatus; 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /src/main/java/com/example/esbboss/entity/DemoSearchResult.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2008-2019 bboss 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.example.esbboss.entity; 17 | 18 | 19 | import java.util.List; 20 | 21 | /** 22 | * @author yinbp[yin-bp@163.com] 23 | */ 24 | public class DemoSearchResult { 25 | private List demos; 26 | private long totalSize; 27 | 28 | public List getDemos() { 29 | return demos; 30 | } 31 | 32 | public void setDemos(List demos) { 33 | this.demos = demos; 34 | } 35 | 36 | public long getTotalSize() { 37 | return totalSize; 38 | } 39 | 40 | public void setTotalSize(long totalSize) { 41 | this.totalSize = totalSize; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/example/esbboss/entity/DemoWithES7Index.java: -------------------------------------------------------------------------------- 1 | package com.example.esbboss.entity;/* 2 | * Copyright 2008 biaoping.yin 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | import com.frameworkset.orm.annotation.ESId; 19 | import com.frameworkset.orm.annotation.ESIndex; 20 | import org.frameworkset.elasticsearch.entity.ESBaseData; 21 | 22 | import java.util.Date; 23 | 24 | /** 25 | * 测试实体,可以从ESBaseData对象继承meta属性,检索时会将文档的一下meta属性设置到对象实例中 26 | */ 27 | //@ESIndex(name="demowithesindex-{agentStarttime,yyyy.MM.dd}",type="demowithesindex") 28 | @ESIndex(name="demowithesindex-{dateformat=yyyy.MM.dd}") 29 | public class DemoWithES7Index extends ESBaseData { 30 | private Object dynamicPriceTemplate; 31 | //设定文档标识字段 32 | @ESId(readSet = true,persistent = false) 33 | private Long demoId; 34 | private String contentbody; 35 | /** 当在mapping定义中指定了日期格式时,则需要指定以下两个注解,例如 36 | * 37 | "agentStarttime": { 38 | "type": "date",###指定多个日期格式 39 | "format":"yyyy-MM-dd HH:mm:ss.SSS||yyyy-MM-dd'T'HH:mm:ss.SSS||yyyy-MM-dd HH:mm:ss||epoch_millis" 40 | } 41 | @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS") 42 | @Column(dataformat = "yyyy-MM-dd HH:mm:ss.SSS") 43 | */ 44 | 45 | protected Date agentStarttime; 46 | private String applicationName; 47 | private String orderId; 48 | private int contrastStatus; 49 | 50 | public String getName() { 51 | return name; 52 | } 53 | 54 | public void setName(String name) { 55 | this.name = name; 56 | } 57 | 58 | private String name; 59 | 60 | public String getContentbody() { 61 | return contentbody; 62 | } 63 | 64 | public void setContentbody(String contentbody) { 65 | this.contentbody = contentbody; 66 | } 67 | 68 | public Date getAgentStarttime() { 69 | return agentStarttime; 70 | } 71 | 72 | public void setAgentStarttime(Date agentStarttime) { 73 | this.agentStarttime = agentStarttime; 74 | } 75 | 76 | public String getApplicationName() { 77 | return applicationName; 78 | } 79 | 80 | public void setApplicationName(String applicationName) { 81 | this.applicationName = applicationName; 82 | } 83 | 84 | public Long getDemoId() { 85 | return demoId; 86 | } 87 | 88 | public void setDemoId(Long demoId) { 89 | this.demoId = demoId; 90 | } 91 | 92 | public Object getDynamicPriceTemplate() { 93 | return dynamicPriceTemplate; 94 | } 95 | 96 | public void setDynamicPriceTemplate(Object dynamicPriceTemplate) { 97 | this.dynamicPriceTemplate = dynamicPriceTemplate; 98 | } 99 | 100 | public String getOrderId() { 101 | return orderId; 102 | } 103 | 104 | public void setOrderId(String orderId) { 105 | this.orderId = orderId; 106 | } 107 | 108 | public int getContrastStatus() { 109 | return contrastStatus; 110 | } 111 | 112 | public void setContrastStatus(int contrastStatus) { 113 | this.contrastStatus = contrastStatus; 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /src/main/java/com/example/esbboss/entity/DemoWithESIndex.java: -------------------------------------------------------------------------------- 1 | package com.example.esbboss.entity;/* 2 | * Copyright 2008 biaoping.yin 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | import com.frameworkset.orm.annotation.ESId; 19 | import com.frameworkset.orm.annotation.ESIndex; 20 | import org.frameworkset.elasticsearch.entity.ESBaseData; 21 | 22 | import java.util.Date; 23 | 24 | /** 25 | * 测试实体,可以从ESBaseData对象继承meta属性,检索时会将文档的一下meta属性设置到对象实例中 26 | */ 27 | //@ESIndex(name="demowithesindex-{agentStarttime,yyyy.MM.dd}",type="demowithesindex") 28 | @ESIndex(name="demowithesindex-{dateformat=yyyy.MM.dd}",type="demowithesindex") 29 | public class DemoWithESIndex extends ESBaseData { 30 | private Object dynamicPriceTemplate; 31 | //设定文档标识字段 32 | @ESId(readSet = true,persistent = false) 33 | private Long demoId; 34 | private String contentbody; 35 | /** 当在mapping定义中指定了日期格式时,则需要指定以下两个注解,例如 36 | * 37 | "agentStarttime": { 38 | "type": "date",###指定多个日期格式 39 | "format":"yyyy-MM-dd HH:mm:ss.SSS||yyyy-MM-dd'T'HH:mm:ss.SSS||yyyy-MM-dd HH:mm:ss||epoch_millis" 40 | } 41 | @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS") 42 | @Column(dataformat = "yyyy-MM-dd HH:mm:ss.SSS") 43 | */ 44 | 45 | protected Date agentStarttime; 46 | private String applicationName; 47 | private String orderId; 48 | private int contrastStatus; 49 | 50 | public String getName() { 51 | return name; 52 | } 53 | 54 | public void setName(String name) { 55 | this.name = name; 56 | } 57 | 58 | private String name; 59 | 60 | public String getContentbody() { 61 | return contentbody; 62 | } 63 | 64 | public void setContentbody(String contentbody) { 65 | this.contentbody = contentbody; 66 | } 67 | 68 | public Date getAgentStarttime() { 69 | return agentStarttime; 70 | } 71 | 72 | public void setAgentStarttime(Date agentStarttime) { 73 | this.agentStarttime = agentStarttime; 74 | } 75 | 76 | public String getApplicationName() { 77 | return applicationName; 78 | } 79 | 80 | public void setApplicationName(String applicationName) { 81 | this.applicationName = applicationName; 82 | } 83 | 84 | public Long getDemoId() { 85 | return demoId; 86 | } 87 | 88 | public void setDemoId(Long demoId) { 89 | this.demoId = demoId; 90 | } 91 | 92 | public Object getDynamicPriceTemplate() { 93 | return dynamicPriceTemplate; 94 | } 95 | 96 | public void setDynamicPriceTemplate(Object dynamicPriceTemplate) { 97 | this.dynamicPriceTemplate = dynamicPriceTemplate; 98 | } 99 | 100 | public String getOrderId() { 101 | return orderId; 102 | } 103 | 104 | public void setOrderId(String orderId) { 105 | this.orderId = orderId; 106 | } 107 | 108 | public int getContrastStatus() { 109 | return contrastStatus; 110 | } 111 | 112 | public void setContrastStatus(int contrastStatus) { 113 | this.contrastStatus = contrastStatus; 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /src/main/java/com/example/esbboss/entity/FieldDemo.java: -------------------------------------------------------------------------------- 1 | package com.example.esbboss.entity;/* 2 | * Copyright 2008 biaoping.yin 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | import java.util.Date; 19 | 20 | /** 21 | * 测试实体,可以从ESBaseData对象继承meta属性,检索时会将文档的一下meta属性设置到对象实例中 22 | */ 23 | public class FieldDemo { 24 | private Object dynamicPriceTemplate; 25 | //设定文档标识字段 26 | private Long demoId; 27 | private String contentbody; 28 | /** 当在mapping定义中指定了日期格式时,则需要指定以下两个注解,例如 29 | * 30 | "agentStarttime": { 31 | "type": "date",###指定多个日期格式 32 | "format":"yyyy-MM-dd HH:mm:ss.SSS||yyyy-MM-dd'T'HH:mm:ss.SSS||yyyy-MM-dd HH:mm:ss||epoch_millis" 33 | } 34 | @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS") 35 | @Column(dataformat = "yyyy-MM-dd HH:mm:ss.SSS") 36 | */ 37 | 38 | protected Date agentStarttime; 39 | private String applicationName; 40 | private String orderId; 41 | private int contrastStatus; 42 | 43 | public String getName() { 44 | return name; 45 | } 46 | 47 | public void setName(String name) { 48 | this.name = name; 49 | } 50 | 51 | private String name; 52 | 53 | public String getContentbody() { 54 | return contentbody; 55 | } 56 | 57 | public void setContentbody(String contentbody) { 58 | this.contentbody = contentbody; 59 | } 60 | 61 | public Date getAgentStarttime() { 62 | return agentStarttime; 63 | } 64 | 65 | public void setAgentStarttime(Date agentStarttime) { 66 | this.agentStarttime = agentStarttime; 67 | } 68 | 69 | public String getApplicationName() { 70 | return applicationName; 71 | } 72 | 73 | public void setApplicationName(String applicationName) { 74 | this.applicationName = applicationName; 75 | } 76 | 77 | public Long getDemoId() { 78 | return demoId; 79 | } 80 | 81 | public void setDemoId(Long demoId) { 82 | this.demoId = demoId; 83 | } 84 | 85 | public Object getDynamicPriceTemplate() { 86 | return dynamicPriceTemplate; 87 | } 88 | 89 | public void setDynamicPriceTemplate(Object dynamicPriceTemplate) { 90 | this.dynamicPriceTemplate = dynamicPriceTemplate; 91 | } 92 | 93 | public String getOrderId() { 94 | return orderId; 95 | } 96 | 97 | public void setOrderId(String orderId) { 98 | this.orderId = orderId; 99 | } 100 | 101 | public int getContrastStatus() { 102 | return contrastStatus; 103 | } 104 | 105 | public void setContrastStatus(int contrastStatus) { 106 | this.contrastStatus = contrastStatus; 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /src/main/java/com/example/esbboss/entity/MetaDemo.java: -------------------------------------------------------------------------------- 1 | package com.example.esbboss.entity;/* 2 | * Copyright 2008 biaoping.yin 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | import com.frameworkset.orm.annotation.*; 19 | import org.frameworkset.elasticsearch.entity.Explanation; 20 | import org.frameworkset.elasticsearch.entity.InnerSearchHits; 21 | 22 | import java.util.Date; 23 | import java.util.List; 24 | import java.util.Map; 25 | 26 | /** 27 | * 测试实体,可以从ESBaseData对象继承meta属性,检索时会将文档的一下meta属性设置到对象实例中 28 | */ 29 | public class MetaDemo { 30 | private Object dynamicPriceTemplate; 31 | //设定文档标识字段 32 | @ESMetaId 33 | private Long demoId; 34 | private String contentbody; 35 | /** 当在mapping定义中指定了日期格式时,则需要指定以下两个注解,例如 36 | * 37 | "agentStarttime": { 38 | "type": "date",###指定多个日期格式 39 | "format":"yyyy-MM-dd HH:mm:ss.SSS||yyyy-MM-dd'T'HH:mm:ss.SSS||yyyy-MM-dd HH:mm:ss||epoch_millis" 40 | } 41 | @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS") 42 | @Column(dataformat = "yyyy-MM-dd HH:mm:ss.SSS") 43 | */ 44 | 45 | protected Date agentStarttime; 46 | private String applicationName; 47 | private String orderId; 48 | private int contrastStatus; 49 | @ESMetaType 50 | private String type; 51 | @ESMetaFields 52 | private Map> fields; 53 | @ESMetaVersion 54 | private long version; 55 | @ESMetaIndex 56 | private String index;//"_index": "trace-2017.09.01", 57 | @ESMetaHighlight 58 | private Map> highlight; 59 | @ESMetaSort 60 | private Object[] sort; 61 | @ESMetaScore 62 | private Double score; 63 | @ESMetaParentId 64 | private Object parent; 65 | @ESRouting 66 | private Object routing; 67 | @ESMetaFound 68 | private boolean found; 69 | @ESMetaNested 70 | private Map nested; 71 | @ESMetaInnerHits 72 | private Map> innerHits; 73 | @ESMetaShard 74 | private String shard;//"_index": "trace-2017.09.01", 75 | @ESMetaNode 76 | private String node;//"_index": "trace-2017.09.01", 77 | @ESMetaExplanation 78 | private Explanation explanation;//"_index": "trace-2017.09.01", 79 | public String getName() { 80 | return name; 81 | } 82 | 83 | public void setName(String name) { 84 | this.name = name; 85 | } 86 | 87 | private String name; 88 | 89 | public String getContentbody() { 90 | return contentbody; 91 | } 92 | 93 | public void setContentbody(String contentbody) { 94 | this.contentbody = contentbody; 95 | } 96 | 97 | public Date getAgentStarttime() { 98 | return agentStarttime; 99 | } 100 | 101 | public void setAgentStarttime(Date agentStarttime) { 102 | this.agentStarttime = agentStarttime; 103 | } 104 | 105 | public String getApplicationName() { 106 | return applicationName; 107 | } 108 | 109 | public void setApplicationName(String applicationName) { 110 | this.applicationName = applicationName; 111 | } 112 | 113 | public Long getDemoId() { 114 | return demoId; 115 | } 116 | 117 | public void setDemoId(Long demoId) { 118 | this.demoId = demoId; 119 | } 120 | 121 | public Object getDynamicPriceTemplate() { 122 | return dynamicPriceTemplate; 123 | } 124 | 125 | public void setDynamicPriceTemplate(Object dynamicPriceTemplate) { 126 | this.dynamicPriceTemplate = dynamicPriceTemplate; 127 | } 128 | 129 | public String getOrderId() { 130 | return orderId; 131 | } 132 | 133 | public void setOrderId(String orderId) { 134 | this.orderId = orderId; 135 | } 136 | 137 | public int getContrastStatus() { 138 | return contrastStatus; 139 | } 140 | 141 | public void setContrastStatus(int contrastStatus) { 142 | this.contrastStatus = contrastStatus; 143 | } 144 | 145 | public String getType() { 146 | return type; 147 | } 148 | 149 | public void setType(String type) { 150 | this.type = type; 151 | } 152 | 153 | public Map> getFields() { 154 | return fields; 155 | } 156 | 157 | public void setFields(Map> fields) { 158 | this.fields = fields; 159 | } 160 | 161 | public long getVersion() { 162 | return version; 163 | } 164 | 165 | public void setVersion(long version) { 166 | this.version = version; 167 | } 168 | 169 | public String getIndex() { 170 | return index; 171 | } 172 | 173 | public void setIndex(String index) { 174 | this.index = index; 175 | } 176 | 177 | public Map> getHighlight() { 178 | return highlight; 179 | } 180 | 181 | public void setHighlight(Map> highlight) { 182 | this.highlight = highlight; 183 | } 184 | 185 | public Object[] getSort() { 186 | return sort; 187 | } 188 | 189 | public void setSort(Object[] sort) { 190 | this.sort = sort; 191 | } 192 | 193 | public Double getScore() { 194 | return score; 195 | } 196 | 197 | public void setScore(Double score) { 198 | this.score = score; 199 | } 200 | 201 | public Object getParent() { 202 | return parent; 203 | } 204 | 205 | public void setParent(Object parent) { 206 | this.parent = parent; 207 | } 208 | 209 | public Object getRouting() { 210 | return routing; 211 | } 212 | 213 | public void setRouting(Object routing) { 214 | this.routing = routing; 215 | } 216 | 217 | public boolean isFound() { 218 | return found; 219 | } 220 | 221 | public void setFound(boolean found) { 222 | this.found = found; 223 | } 224 | 225 | public Map getNested() { 226 | return nested; 227 | } 228 | 229 | public void setNested(Map nested) { 230 | this.nested = nested; 231 | } 232 | 233 | public Map> getInnerHits() { 234 | return innerHits; 235 | } 236 | 237 | public void setInnerHits(Map> innerHits) { 238 | this.innerHits = innerHits; 239 | } 240 | 241 | public String getShard() { 242 | return shard; 243 | } 244 | 245 | public void setShard(String shard) { 246 | this.shard = shard; 247 | } 248 | 249 | public String getNode() { 250 | return node; 251 | } 252 | 253 | public void setNode(String node) { 254 | this.node = node; 255 | } 256 | 257 | public Explanation getExplanation() { 258 | return explanation; 259 | } 260 | 261 | public void setExplanation(Explanation explanation) { 262 | this.explanation = explanation; 263 | } 264 | } 265 | -------------------------------------------------------------------------------- /src/main/java/com/example/esbboss/entity/NewDemo.java: -------------------------------------------------------------------------------- 1 | package com.example.esbboss.entity; 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.frameworkset.orm.annotation.ESId; 19 | 20 | /** 21 | *

Description:

22 | *

23 | *

Copyright (c) 2018

24 | * @Date 2018/7/8 13:41 25 | * @author biaoping.yin 26 | * @version 1.0 27 | */ 28 | public class NewDemo { 29 | @ESId(readSet = true) 30 | private Long demoId; 31 | 32 | public Long getDemoId() { 33 | return demoId; 34 | } 35 | 36 | public void setDemoId(Long demoId) { 37 | this.demoId = demoId; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/example/esbboss/entity/UUIDDemo.java: -------------------------------------------------------------------------------- 1 | package com.example.esbboss.entity;/* 2 | * Copyright 2008 biaoping.yin 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | import com.frameworkset.orm.annotation.ESMetaId; 19 | 20 | import java.util.Date; 21 | 22 | /** 23 | * 测试实体,可以从ESBaseData对象继承meta属性,检索时会将文档的一下meta属性设置到对象实例中 24 | */ 25 | public class UUIDDemo { 26 | @ESMetaId 27 | private String did; 28 | private Object dynamicPriceTemplate; 29 | //设定文档标识字段 30 | private Long demoId; 31 | private String contentbody; 32 | /** 当在mapping定义中指定了日期格式时,则需要指定以下两个注解,例如 33 | * 34 | "agentStarttime": { 35 | "type": "date",###指定多个日期格式 36 | "format":"yyyy-MM-dd HH:mm:ss.SSS||yyyy-MM-dd'T'HH:mm:ss.SSS||yyyy-MM-dd HH:mm:ss||epoch_millis" 37 | } 38 | @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS") 39 | @Column(dataformat = "yyyy-MM-dd HH:mm:ss.SSS") 40 | */ 41 | 42 | protected Date agentStarttime; 43 | private String applicationName; 44 | private String orderId; 45 | private int contrastStatus; 46 | 47 | public String getName() { 48 | return name; 49 | } 50 | 51 | public void setName(String name) { 52 | this.name = name; 53 | } 54 | 55 | private String name; 56 | 57 | public String getContentbody() { 58 | return contentbody; 59 | } 60 | 61 | public void setContentbody(String contentbody) { 62 | this.contentbody = contentbody; 63 | } 64 | 65 | public Date getAgentStarttime() { 66 | return agentStarttime; 67 | } 68 | 69 | public void setAgentStarttime(Date agentStarttime) { 70 | this.agentStarttime = agentStarttime; 71 | } 72 | 73 | public String getApplicationName() { 74 | return applicationName; 75 | } 76 | 77 | public void setApplicationName(String applicationName) { 78 | this.applicationName = applicationName; 79 | } 80 | 81 | public Long getDemoId() { 82 | return demoId; 83 | } 84 | 85 | public void setDemoId(Long demoId) { 86 | this.demoId = demoId; 87 | } 88 | 89 | public Object getDynamicPriceTemplate() { 90 | return dynamicPriceTemplate; 91 | } 92 | 93 | public void setDynamicPriceTemplate(Object dynamicPriceTemplate) { 94 | this.dynamicPriceTemplate = dynamicPriceTemplate; 95 | } 96 | 97 | public String getOrderId() { 98 | return orderId; 99 | } 100 | 101 | public void setOrderId(String orderId) { 102 | this.orderId = orderId; 103 | } 104 | 105 | public int getContrastStatus() { 106 | return contrastStatus; 107 | } 108 | 109 | public void setContrastStatus(int contrastStatus) { 110 | this.contrastStatus = contrastStatus; 111 | } 112 | 113 | public String getDid() { 114 | return did; 115 | } 116 | 117 | public void setDid(String did) { 118 | this.did = did; 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /src/main/java/org/bboss/elasticsearchtest/springboot/Application.java: -------------------------------------------------------------------------------- 1 | package org.bboss.elasticsearchtest.springboot; 2 | 3 | 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | import org.springframework.boot.SpringApplication; 7 | import org.springframework.boot.autoconfigure.SpringBootApplication; 8 | 9 | /** 10 | * @author yinbp [122054810@qq.com] 11 | * 12 | */ 13 | 14 | @SpringBootApplication 15 | //改变自动扫描的包 16 | //@ComponentScan(basePackages = {"org.bboss.elasticsearchtest.springboot", 17 | // "org.frameworkset.elasticsearch.boot"}) 18 | public class Application { 19 | 20 | private Logger logger = LoggerFactory.getLogger(Application.class); 21 | public Application(){ 22 | System.out.println("aa"); 23 | } 24 | public static void main(String[] args) { 25 | SpringApplication.run(Application.class, args); 26 | } 27 | 28 | 29 | 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/org/bboss/elasticsearchtest/springboot/MultiESSTartConfigurer.java: -------------------------------------------------------------------------------- 1 | package org.bboss.elasticsearchtest.springboot; 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 org.frameworkset.elasticsearch.boot.BBossESStarter; 19 | import org.springframework.boot.context.properties.ConfigurationProperties; 20 | import org.springframework.context.annotation.Bean; 21 | import org.springframework.context.annotation.Configuration; 22 | import org.springframework.context.annotation.Primary; 23 | 24 | /** 25 | * 配置和加载多个es集群实例,在application.yml配置文件中定义了两个集群default和logs 26 | * spring.elasticsearch.bboss.default 27 | * spring.elasticsearch.bboss.logs 28 | */ 29 | //@Configuration 30 | //@Profile("multi-datasource") 31 | @Configuration 32 | public class MultiESSTartConfigurer { 33 | @Primary 34 | @Bean(initMethod = "start") 35 | @ConfigurationProperties("spring.elasticsearch.bboss.default") 36 | public BBossESStarter bbossESStarterDefault(){ 37 | return new BBossESStarter(); 38 | 39 | } 40 | 41 | @Bean(initMethod = "start") 42 | @ConfigurationProperties("spring.elasticsearch.bboss.logs") 43 | public BBossESStarter bbossESStarterLogs(){ 44 | return new BBossESStarter(); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/org/bboss/elasticsearchtest/springboot/TestPropertiesInterceptor.java: -------------------------------------------------------------------------------- 1 | package org.bboss.elasticsearchtest.springboot; 2 | /** 3 | * Copyright 2022 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 org.frameworkset.spi.assemble.PropertiesInterceptor; 19 | import org.frameworkset.spi.assemble.PropertyContext; 20 | import org.slf4j.Logger; 21 | import org.slf4j.LoggerFactory; 22 | 23 | /** 24 | *

Description:

25 | *

26 | *

Copyright (c) 2020

27 | * @Date 2022/4/18 28 | * @author biaoping.yin 29 | * @version 1.0 30 | */ 31 | public class TestPropertiesInterceptor implements PropertiesInterceptor { 32 | private static Logger logger = LoggerFactory.getLogger(TestPropertiesInterceptor.class); 33 | public Object convert(PropertyContext propertyContext) { 34 | logger.info(propertyContext.toString()); 35 | return propertyContext.getValue(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/org/bboss/elasticsearchtest/springboot/bulk/TestBulkProcessor.java: -------------------------------------------------------------------------------- 1 | package org.bboss.elasticsearchtest.springboot.bulk; 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 org.frameworkset.elasticsearch.boot.BBossESStarter; 19 | import org.frameworkset.elasticsearch.bulk.BulkCommand; 20 | import org.frameworkset.elasticsearch.bulk.BulkInterceptor; 21 | import org.frameworkset.elasticsearch.bulk.BulkProcessor; 22 | import org.frameworkset.elasticsearch.bulk.BulkProcessorBuilder; 23 | import org.frameworkset.elasticsearch.client.ClientOptions; 24 | import org.springframework.beans.factory.annotation.Autowired; 25 | import org.springframework.stereotype.Service; 26 | 27 | import java.util.ArrayList; 28 | import java.util.HashMap; 29 | import java.util.List; 30 | import java.util.Map; 31 | 32 | /** 33 | *

Description: for elasticsearch 5x,6x

34 | *

35 | *

Copyright (c) 2018

36 | * @Date 2019/12/8 9:57 37 | * @author biaoping.yin 38 | * @version 1.0 39 | */ 40 | @Service 41 | public class TestBulkProcessor { 42 | @Autowired 43 | private BBossESStarter bbossESStarter; 44 | /** 45 | * BulkProcessor批处理组件,一般作为单实例使用,单实例多线程安全,可放心使用 46 | */ 47 | private BulkProcessor bulkProcessor; 48 | public static void main(String[] args){ 49 | TestBulkProcessor testBulkProcessor = new TestBulkProcessor(); 50 | testBulkProcessor.buildBulkProcessor(); 51 | 52 | testBulkProcessor.testBulkDatas(); 53 | 54 | //testBulkProcessor.shutdown(false);//调用shutDown停止方法后,BulkProcessor不会接收新的请求,但是会处理完所有已经进入bulk队列的数据 55 | 56 | 57 | } 58 | public void buildBulkProcessor(){ 59 | //定义BulkProcessor批处理组件构建器 60 | BulkProcessorBuilder bulkProcessorBuilder = new BulkProcessorBuilder(); 61 | bulkProcessorBuilder.setBlockedWaitTimeout(0)//指定bulk数据缓冲队列已满时后续添加的bulk数据排队等待时间,如果超过指定的时候数据将被拒绝处理,单位:毫秒,默认为0,不拒绝并一直等待成功为止 62 | .setBulkSizes(1000)//按批处理数据记录数 63 | .setFlushInterval(5000)//强制bulk操作时间,单位毫秒,如果自上次bulk操作flushInterval毫秒后,数据量没有满足BulkSizes对应的记录数,但是有记录,那么强制进行bulk处理 64 | 65 | .setWarnMultsRejects(1000)//bulk处理操作被每被拒绝WarnMultsRejects次(1000次),在日志文件中输出拒绝告警信息 66 | .setWorkThreads(20)//bulk处理工作线程数 67 | .setWorkThreadQueue(20)//bulk处理工作线程池缓冲队列大小 68 | .setBulkProcessorName("test_bulkprocessor")//工作线程名称,实际名称为BulkProcessorName-+线程编号 69 | .setBulkRejectMessage("Reject test bulkprocessor")//bulk处理操作被每被拒绝WarnMultsRejects次(1000次),在日志文件中输出拒绝告警信息提示前缀 70 | // .setElasticsearch("default")//指定Elasticsearch集群数据源名称,bboss可以支持多数据源 71 | .addBulkInterceptor(new BulkInterceptor() { 72 | public void beforeBulk(BulkCommand bulkCommand) { 73 | System.out.println("beforeBulk"); 74 | } 75 | 76 | public void afterBulk(BulkCommand bulkCommand, String result) { 77 | System.out.println("afterBulk:"+result); 78 | // System.out.println("totalSize:"+bulkCommand.getTotalSize()); 79 | // System.out.println("totalFailedSize:"+bulkCommand.getTotalFailedSize()); 80 | } 81 | 82 | public void exceptionBulk(BulkCommand bulkCommand, Throwable exception) { 83 | System.out.println("exceptionBulk:"); 84 | exception.printStackTrace(); 85 | } 86 | public void errorBulk(BulkCommand bulkCommand, String result) { 87 | System.out.println("errorBulk:"+result); 88 | } 89 | }) 90 | // https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html 91 | //下面的参数都是bulk url请求的参数:RefreshOption和其他参数只能二选一,配置了RefreshOption(类似于refresh=true&&aaaa=bb&cc=dd&zz=ee这种形式,将相关参数拼接成合法的url参数格式)就不能配置其他参数, 92 | // 其中的refresh参数控制bulk操作结果强制refresh入elasticsearch,便于实时查看数据,测试环境可以打开,生产不要设置 93 | // .setRefreshOption("refresh") 94 | // .setTimeout("100s") 95 | // .setMasterTimeout("50s") 96 | // .setRefresh("true") 97 | // .setWaitForActiveShards(2) 98 | // .setRouting("1") //(Optional, string) Target the specified primary shard. 99 | // .setPipeline("1") // (Optional, string) ID of the pipeline to use to preprocess incoming documents. 100 | ; 101 | /** 102 | * 构建BulkProcessor批处理组件,一般作为单实例使用,单实例多线程安全,可放心使用 103 | */ 104 | bulkProcessor = bulkProcessorBuilder.build();//构建批处理作业组件 105 | } 106 | public void testBulkDatas(){ 107 | System.out.println("testBulkDatas"); 108 | ClientOptions clientOptions = new ClientOptions(); 109 | clientOptions.setIdField("id")//通过clientOptions指定map中的key为id的字段值作为文档_id, 110 | .setEsRetryOnConflict(1) 111 | // .setPipeline("1") 112 | 113 | .setOpType("index") 114 | // .setIfPrimaryTerm(2l) 115 | // .setIfSeqNo(3l) 116 | ; 117 | Map data = new HashMap(); 118 | data.put("name","duoduo1"); 119 | data.put("id",1); 120 | bulkProcessor.insertData("bulkdemo","bulkdemo",data,clientOptions); 121 | data = new HashMap(); 122 | data.put("name","duoduo2"); 123 | data.put("id",2); 124 | bulkProcessor.insertData("bulkdemo","bulkdemo",data,clientOptions); 125 | data = new HashMap(); 126 | data.put("name","duoduo3"); 127 | data.put("id",3); 128 | bulkProcessor.insertData("bulkdemo","bulkdemo",data,clientOptions); 129 | data = new HashMap(); 130 | data.put("name","duoduo4"); 131 | data.put("id",4); 132 | bulkProcessor.insertData("bulkdemo","bulkdemo",data,clientOptions); 133 | data = new HashMap(); 134 | data.put("name","duoduo5"); 135 | data.put("id",5); 136 | 137 | bulkProcessor.insertData("bulkdemo","bulkdemo",data,clientOptions); 138 | ClientOptions deleteclientOptions = new ClientOptions(); 139 | 140 | 141 | deleteclientOptions.setEsRetryOnConflict(1); 142 | //.setPipeline("1") 143 | bulkProcessor.deleteData("bulkdemo","bulkdemo","1",deleteclientOptions); 144 | List datas = new ArrayList(); 145 | for(int i = 6; i < 106; i ++) { 146 | data = new HashMap(); 147 | data.put("name","duoduo"+i); 148 | data.put("id",i); 149 | datas.add(data); 150 | } 151 | bulkProcessor.insertDatas("bulkdemo","bulkdemo",datas,clientOptions); 152 | data = new HashMap(); 153 | data.put("name","updateduoduo5"); 154 | data.put("id",5); 155 | ClientOptions updateOptions = new ClientOptions(); 156 | // List sourceUpdateExcludes = new ArrayList(); 157 | // sourceUpdateExcludes.add("name"); 158 | // updateOptions.setSourceUpdateExcludes(sourceUpdateExcludes); //es 7不起作用 159 | List sourceUpdateIncludes = new ArrayList(); 160 | sourceUpdateIncludes.add("name"); 161 | 162 | /** 163 | * ersion typesedit 164 | * In addition to the external version type, Elasticsearch also supports other types for specific use cases: 165 | * 166 | * internal 167 | * Only index the document if the given version is identical to the version of the stored document. 168 | * external or external_gt 169 | * Only index the document if the given version is strictly higher than the version of the stored document or if there is no existing document. The given version will be used as the new version and will be stored with the new document. The supplied version must be a non-negative long number. 170 | * external_gte 171 | * Only index the document if the given version is equal or higher than the version of the stored document. If there is no existing document the operation will succeed as well. The given version will be used as the new version and will be stored with the new document. The supplied version must be a non-negative long number. 172 | * The external_gte version type is meant for special use cases and should be used with care. If used incorrectly, it can result in loss of data. There is another option, force, which is deprecated because it can cause primary and replica shards to diverge. 173 | */ 174 | updateOptions.setSourceUpdateIncludes(sourceUpdateIncludes);//es 7不起作用 175 | updateOptions.setDetectNoop(false) 176 | .setDocasupsert(false) 177 | .setReturnSource(true) 178 | // .setEsRetryOnConflict(1) 179 | .setIdField("id") //elasticsearch7不能同时指定EsRetryOnConflict和IfPrimaryTerm/IfSeqNo 180 | //.setVersion(10).setVersionType("internal") elasticsearch 7x必须使用IfPrimaryTerm和IfSeqNo代替version 181 | // .setIfPrimaryTerm(2l) 182 | // .setIfSeqNo(3l).setPipeline("1") 183 | ; 184 | bulkProcessor.updateData("bulkdemo","bulkdemo",data,updateOptions); 185 | 186 | } 187 | 188 | public void shutdown(boolean asyn) { 189 | if(asyn) { 190 | Thread t = new Thread() { 191 | public void run() { 192 | bulkProcessor.shutDown(); 193 | } 194 | }; 195 | t.start(); 196 | } 197 | else { 198 | bulkProcessor.shutDown(); 199 | } 200 | 201 | // System.out.println("bulkProcessor.getTotalSize():"+bulkProcessor.getTotalSize()); 202 | } 203 | 204 | } 205 | -------------------------------------------------------------------------------- /src/main/java/org/bboss/elasticsearchtest/springboot/bulk/TestBulkProcessor7x.java: -------------------------------------------------------------------------------- 1 | package org.bboss.elasticsearchtest.springboot.bulk; 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 org.frameworkset.elasticsearch.bulk.BulkCommand; 19 | import org.frameworkset.elasticsearch.bulk.BulkInterceptor; 20 | import org.frameworkset.elasticsearch.bulk.BulkProcessor; 21 | import org.frameworkset.elasticsearch.bulk.BulkProcessorBuilder; 22 | import org.frameworkset.elasticsearch.client.ClientOptions; 23 | import org.slf4j.Logger; 24 | import org.slf4j.LoggerFactory; 25 | import org.springframework.stereotype.Service; 26 | 27 | import java.util.ArrayList; 28 | import java.util.HashMap; 29 | import java.util.List; 30 | import java.util.Map; 31 | 32 | /** 33 | *

Description: for elasticsearch 7x

34 | *

35 | *

Copyright (c) 2018

36 | * @Date 2019/12/8 9:57 37 | * @author biaoping.yin 38 | * @version 1.0 39 | */ 40 | @Service 41 | public class TestBulkProcessor7x { 42 | private static Logger logger = LoggerFactory.getLogger(TestBulkProcessor7x.class); 43 | 44 | public static void main(String[] args){ 45 | ArrayList list = new ArrayList(2); 46 | list.add(1); 47 | list.add(2); 48 | } 49 | 50 | /** 51 | * BulkProcessor批处理组件,一般作为单实例使用,单实例多线程安全,可放心使用 52 | */ 53 | private BulkProcessor bulkProcessor; 54 | 55 | public void buildBulkProcessor(){ 56 | //定义BulkProcessor批处理组件构建器 57 | BulkProcessorBuilder bulkProcessorBuilder = new BulkProcessorBuilder(); 58 | bulkProcessorBuilder.setBlockedWaitTimeout(0)//指定bulk数据缓冲队列已满时后续添加的bulk数据排队等待时间,如果超过指定的时候数据将被拒绝处理,单位:毫秒,默认为0,不拒绝并一直等待成功为止 59 | .setBulkSizes(50)//按批处理数据记录数 60 | .setFlushInterval(5000)//强制bulk操作时间,单位毫秒,如果自上次bulk操作flushInterval毫秒后,数据量没有满足BulkSizes对应的记录数,但是有记录,那么强制进行bulk处理 61 | 62 | .setWarnMultsRejects(1000)//bulk处理操作被每被拒绝WarnMultsRejects次(1000次),在日志文件中输出拒绝告警信息 63 | .setWorkThreads(5)//bulk处理工作线程数 64 | .setWorkThreadQueue(1)//bulk处理工作线程池缓冲队列大小 65 | .setBulkProcessorName("test_bulkprocessor")//工作线程名称,实际名称为BulkProcessorName-+线程编号 66 | .setBulkRejectMessage("Reject test bulkprocessor")//bulk处理操作被每被拒绝WarnMultsRejects次(1000次),在日志文件中输出拒绝告警信息提示前缀 67 | // .setElasticsearch("default")//指定Elasticsearch集群数据源名称,bboss可以支持多数据源 68 | .addBulkInterceptor(new BulkInterceptor() { 69 | public void beforeBulk(BulkCommand bulkCommand) { 70 | logger.debug("beforeBulk"); 71 | } 72 | 73 | public void afterBulk(BulkCommand bulkCommand, String result) { 74 | if(logger.isDebugEnabled()) 75 | logger.debug("afterBulk:"+result); 76 | // System.out.println("totalSize:"+bulkCommand.getTotalSize()); 77 | // System.out.println("totalFailedSize:"+bulkCommand.getTotalFailedSize()); 78 | } 79 | 80 | public void exceptionBulk(BulkCommand bulkCommand, Throwable exception) { 81 | logger.info("exceptionBulk:",exception); 82 | } 83 | public void errorBulk(BulkCommand bulkCommand, String result) { 84 | logger.info("errorBulk:"+result); 85 | } 86 | }) 87 | // https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html 88 | //下面的参数都是bulk url请求的参数:RefreshOption和其他参数只能二选一,配置了RefreshOption(类似于refresh=true&&aaaa=bb&cc=dd&zz=ee这种形式,将相关参数拼接成合法的url参数格式)就不能配置其他参数, 89 | // 其中的refresh参数控制bulk操作结果强制refresh入elasticsearch,便于实时查看数据,测试环境可以打开,生产不要设置 90 | // .setRefreshOption("refresh") 91 | // .setTimeout("100s") 92 | // .setMasterTimeout("50s") 93 | // .setRefresh("true") 94 | // .setWaitForActiveShards(2) 95 | // .setRouting("1") //(Optional, string) Target the specified primary shard. 96 | // .setPipeline("1") // (Optional, string) ID of the pipeline to use to preprocess incoming documents. 97 | ; 98 | /** 99 | * 构建BulkProcessor批处理组件,一般作为单实例使用,单实例多线程安全,可放心使用 100 | */ 101 | bulkProcessor = bulkProcessorBuilder.build();//构建批处理作业组件 102 | } 103 | public void testBulkDatas(){ 104 | logger.info("testBulkDatas"); 105 | ClientOptions clientOptions = new ClientOptions(); 106 | clientOptions.setIdField("id")//通过clientOptions指定map中的key为id的字段值作为文档_id, 107 | .setEsRetryOnConflict(1) 108 | // .setPipeline("1") 109 | 110 | .setOpType("index") 111 | // .setIfPrimaryTerm(2l) 112 | // .setIfSeqNo(3l) 113 | ; 114 | Map data = new HashMap(); 115 | data.put("name","duoduo1"); 116 | data.put("id",1); 117 | bulkProcessor.insertData("bulkdemo",data,clientOptions); 118 | data = new HashMap(); 119 | data.put("name","duoduo2"); 120 | data.put("id",2); 121 | bulkProcessor.insertData("bulkdemo",data,clientOptions); 122 | data = new HashMap(); 123 | data.put("name","duoduo3"); 124 | data.put("id",3); 125 | bulkProcessor.insertData("bulkdemo",data,clientOptions); 126 | data = new HashMap(); 127 | data.put("name","duoduo4"); 128 | data.put("id",4); 129 | bulkProcessor.insertData("bulkdemo",data,clientOptions); 130 | data = new HashMap(); 131 | data.put("name","duoduo5"); 132 | data.put("id",5); 133 | 134 | bulkProcessor.insertData("bulkdemo",data,clientOptions); 135 | ClientOptions deleteclientOptions = new ClientOptions(); 136 | 137 | 138 | deleteclientOptions.setEsRetryOnConflict(1); 139 | //.setPipeline("1") 140 | bulkProcessor.deleteDataWithClientOptions("bulkdemo","1",deleteclientOptions); 141 | List datas = new ArrayList(); 142 | for(int i = 6; i < 106; i ++) { 143 | data = new HashMap(); 144 | data.put("name","duoduo"+i); 145 | data.put("id",i); 146 | datas.add(data); 147 | } 148 | bulkProcessor.insertDatas("bulkdemo",datas,clientOptions); 149 | data = new HashMap(); 150 | data.put("name","updateduoduo5"); 151 | data.put("id",5); 152 | ClientOptions updateOptions = new ClientOptions(); 153 | // List sourceUpdateExcludes = new ArrayList(); 154 | // sourceUpdateExcludes.add("name"); 155 | // updateOptions.setSourceUpdateExcludes(sourceUpdateExcludes); //es 7不起作用 156 | List sourceUpdateIncludes = new ArrayList(); 157 | sourceUpdateIncludes.add("name"); 158 | 159 | /** 160 | * ersion typesedit 161 | * In addition to the external version type, Elasticsearch also supports other types for specific use cases: 162 | * 163 | * internal 164 | * Only index the document if the given version is identical to the version of the stored document. 165 | * external or external_gt 166 | * Only index the document if the given version is strictly higher than the version of the stored document or if there is no existing document. The given version will be used as the new version and will be stored with the new document. The supplied version must be a non-negative long number. 167 | * external_gte 168 | * Only index the document if the given version is equal or higher than the version of the stored document. If there is no existing document the operation will succeed as well. The given version will be used as the new version and will be stored with the new document. The supplied version must be a non-negative long number. 169 | * The external_gte version type is meant for special use cases and should be used with care. If used incorrectly, it can result in loss of data. There is another option, force, which is deprecated because it can cause primary and replica shards to diverge. 170 | */ 171 | updateOptions.setSourceUpdateIncludes(sourceUpdateIncludes);//es 7不起作用 172 | updateOptions.setDetectNoop(false) 173 | .setDocasupsert(false) 174 | .setReturnSource(true) 175 | // .setEsRetryOnConflict(1) 176 | .setIdField("id") //elasticsearch7不能同时指定EsRetryOnConflict和IfPrimaryTerm/IfSeqNo 177 | //.setVersion(10).setVersionType("internal") elasticsearch 7x必须使用IfPrimaryTerm和IfSeqNo代替version 178 | // .setIfPrimaryTerm(2l) 179 | // .setIfSeqNo(3l).setPipeline("1") 180 | ; 181 | bulkProcessor.updateData("bulkdemo",data,updateOptions); 182 | 183 | } 184 | 185 | public void shutdown(boolean asyn) { 186 | if(asyn) { 187 | Thread t = new Thread() { 188 | public void run() { 189 | bulkProcessor.shutDown(); 190 | } 191 | }; 192 | t.start(); 193 | } 194 | else { 195 | bulkProcessor.shutDown(); 196 | } 197 | 198 | 199 | // System.out.println("bulkProcessor.getTotalSize():"+bulkProcessor.getTotalSize()); 200 | } 201 | 202 | } 203 | -------------------------------------------------------------------------------- /src/main/java/org/bboss/elasticsearchtest/springboot/crud/DemoWithES7Index.java: -------------------------------------------------------------------------------- 1 | package org.bboss.elasticsearchtest.springboot.crud;/* 2 | * Copyright 2008 biaoping.yin 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | import com.frameworkset.orm.annotation.ESId; 19 | import com.frameworkset.orm.annotation.ESIndex; 20 | import org.frameworkset.elasticsearch.entity.ESBaseData; 21 | 22 | import java.util.Date; 23 | 24 | /** 25 | * 测试实体,可以从ESBaseData对象继承meta属性,检索时会将文档的一下meta属性设置到对象实例中 26 | */ 27 | //@ESIndex(name="demowithesindex-{agentStarttime,yyyy.MM.dd}",type="demowithesindex") 28 | @ESIndex(name="demowithesindex-{dateformat=yyyy.MM.dd}") 29 | public class DemoWithES7Index extends ESBaseData { 30 | private Object dynamicPriceTemplate; 31 | //设定文档标识字段 32 | @ESId(readSet = true,persistent = false) 33 | private Long demoId; 34 | private String contentbody; 35 | /** 当在mapping定义中指定了日期格式时,则需要指定以下两个注解,例如 36 | * 37 | "agentStarttime": { 38 | "type": "date",###指定多个日期格式 39 | "format":"yyyy-MM-dd HH:mm:ss.SSS||yyyy-MM-dd'T'HH:mm:ss.SSS||yyyy-MM-dd HH:mm:ss||epoch_millis" 40 | } 41 | @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS") 42 | @Column(dataformat = "yyyy-MM-dd HH:mm:ss.SSS") 43 | */ 44 | 45 | protected Date agentStarttime; 46 | private String applicationName; 47 | private String orderId; 48 | private int contrastStatus; 49 | 50 | public String getName() { 51 | return name; 52 | } 53 | 54 | public void setName(String name) { 55 | this.name = name; 56 | } 57 | 58 | private String name; 59 | 60 | public String getContentbody() { 61 | return contentbody; 62 | } 63 | 64 | public void setContentbody(String contentbody) { 65 | this.contentbody = contentbody; 66 | } 67 | 68 | public Date getAgentStarttime() { 69 | return agentStarttime; 70 | } 71 | 72 | public void setAgentStarttime(Date agentStarttime) { 73 | this.agentStarttime = agentStarttime; 74 | } 75 | 76 | public String getApplicationName() { 77 | return applicationName; 78 | } 79 | 80 | public void setApplicationName(String applicationName) { 81 | this.applicationName = applicationName; 82 | } 83 | 84 | public Long getDemoId() { 85 | return demoId; 86 | } 87 | 88 | public void setDemoId(Long demoId) { 89 | this.demoId = demoId; 90 | } 91 | 92 | public Object getDynamicPriceTemplate() { 93 | return dynamicPriceTemplate; 94 | } 95 | 96 | public void setDynamicPriceTemplate(Object dynamicPriceTemplate) { 97 | this.dynamicPriceTemplate = dynamicPriceTemplate; 98 | } 99 | 100 | public String getOrderId() { 101 | return orderId; 102 | } 103 | 104 | public void setOrderId(String orderId) { 105 | this.orderId = orderId; 106 | } 107 | 108 | public int getContrastStatus() { 109 | return contrastStatus; 110 | } 111 | 112 | public void setContrastStatus(int contrastStatus) { 113 | this.contrastStatus = contrastStatus; 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /src/main/java/org/bboss/elasticsearchtest/springboot/script/DynamicPriceTemplate.java: -------------------------------------------------------------------------------- 1 | package org.bboss.elasticsearchtest.springboot.script;/* 2 | * Copyright 2008 biaoping.yin 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import java.util.List; 18 | 19 | public class DynamicPriceTemplate { 20 | private int goodsId; 21 | private String goodName; 22 | private List rules; 23 | 24 | public int getGoodsId() { 25 | return goodsId; 26 | } 27 | 28 | public void setGoodsId(int goodsId) { 29 | this.goodsId = goodsId; 30 | } 31 | 32 | public List getRules() { 33 | return rules; 34 | } 35 | 36 | public void setRules(List rules) { 37 | this.rules = rules; 38 | } 39 | 40 | public String getGoodName() { 41 | return goodName; 42 | } 43 | 44 | public void setGoodName(String goodName) { 45 | this.goodName = goodName; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/org/bboss/elasticsearchtest/springboot/script/Rule.java: -------------------------------------------------------------------------------- 1 | package org.bboss.elasticsearchtest.springboot.script;/* 2 | * Copyright 2008 biaoping.yin 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | public class Rule { 18 | private String ruleId; 19 | private int ruleCount; 20 | 21 | public String getRuleId() { 22 | return ruleId; 23 | } 24 | 25 | public void setRuleId(String ruleId) { 26 | this.ruleId = ruleId; 27 | } 28 | 29 | public int getRuleCount() { 30 | return ruleCount; 31 | } 32 | 33 | public void setRuleCount(int ruleCount) { 34 | this.ruleCount = ruleCount; 35 | } 36 | 37 | public boolean isRuleExist() { 38 | return ruleExist; 39 | } 40 | 41 | public void setRuleExist(boolean ruleExist) { 42 | this.ruleExist = ruleExist; 43 | } 44 | 45 | private boolean ruleExist; 46 | 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/org/bboss/elasticsearchtest/springboot/script/ScriptImpl.java: -------------------------------------------------------------------------------- 1 | package org.bboss.elasticsearchtest.springboot.script;/* 2 | * Copyright 2008 biaoping.yin 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import org.bboss.elasticsearchtest.springboot.crud.DocumentCRUD; 18 | import org.frameworkset.elasticsearch.boot.BBossESStarter; 19 | import org.frameworkset.elasticsearch.client.ClientInterface; 20 | import org.springframework.beans.factory.annotation.Autowired; 21 | import org.springframework.stereotype.Service; 22 | 23 | import java.util.ArrayList; 24 | import java.util.HashMap; 25 | import java.util.List; 26 | import java.util.Map; 27 | @Service 28 | public class ScriptImpl { 29 | private String mappath = "esmapper/demo.xml"; 30 | @Autowired 31 | private DocumentCRUD documentCRUD; 32 | @Autowired 33 | private BBossESStarter bbossESStarter; 34 | public void updateDocumentByScriptPath(){ 35 | //初始化数据,会创建type为demo的indice demo,并添加docid为2的文档 36 | documentCRUD.testCreateIndice(); 37 | documentCRUD.testBulkAddDocument(); 38 | //创建加载配置文件的客户端工具,用来检索文档,单实例多线程安全 39 | ClientInterface clientUtil = bbossESStarter.getConfigRestClient(mappath); 40 | Map params = new HashMap(); 41 | DynamicPriceTemplate dynamicPriceTemplate = new DynamicPriceTemplate(); 42 | dynamicPriceTemplate.setGoodsId(1); 43 | List ruleList = new ArrayList(); 44 | Rule rule = new Rule(); 45 | rule.setRuleCount(100); 46 | rule.setRuleExist(true); 47 | rule.setRuleId("asdfasdfasdf"); 48 | ruleList.add(rule); 49 | 50 | rule = new Rule(); 51 | rule.setRuleCount(101); 52 | rule.setRuleExist(false); 53 | rule.setRuleId("bbb$b"); 54 | ruleList.add(rule); 55 | 56 | rule = new Rule(); 57 | rule.setRuleCount(103); 58 | rule.setRuleExist(true); 59 | rule.setRuleId("ccccc"); 60 | ruleList.add(rule); 61 | dynamicPriceTemplate.setRules(ruleList); 62 | 63 | //为id为2的文档增加last和nick两个属性 64 | params.put("last","gaudreau"); 65 | params.put("nick","hockey"); 66 | params.put("dynamicPriceTemplate",dynamicPriceTemplate); 67 | //通过script脚本为id为2的文档增加last和nick两个属性,为了演示效果强制refresh,实际环境慎用 68 | clientUtil.updateByPath("demo/demo/2/_update?refresh","scriptDsl",params); 69 | //获取更新后的文档,会看到新加的2个字段属性 70 | String doc = clientUtil.getDocument("demo","demo","2"); 71 | System.out.println(doc); 72 | 73 | } 74 | 75 | 76 | public void updateDocumentByScriptQueryPath(){ 77 | //初始化数据,会创建type为demo的indice demo,并添加docid为2的文档 78 | documentCRUD.testCreateIndice(); 79 | documentCRUD.testBulkAddDocument(); 80 | //创建加载配置文件的客户端工具,用来检索文档,单实例多线程安全 81 | ClientInterface clientUtil = bbossESStarter.getConfigRestClient(mappath); 82 | Map params = new HashMap(); 83 | DynamicPriceTemplate dynamicPriceTemplate = new DynamicPriceTemplate(); 84 | dynamicPriceTemplate.setGoodsId(1); 85 | dynamicPriceTemplate.setGoodName("asd\"国家"); 86 | List ruleList = new ArrayList(); 87 | Rule rule = new Rule(); 88 | rule.setRuleCount(100); 89 | rule.setRuleExist(true); 90 | rule.setRuleId("asdfasd$fasdf"); 91 | ruleList.add(rule); 92 | 93 | rule = new Rule(); 94 | rule.setRuleCount(101); 95 | rule.setRuleExist(false); 96 | rule.setRuleId("bbbb"); 97 | ruleList.add(rule); 98 | 99 | rule = new Rule(); 100 | rule.setRuleCount(103); 101 | rule.setRuleExist(true); 102 | rule.setRuleId(null); 103 | ruleList.add(rule); 104 | dynamicPriceTemplate.setRules(ruleList); 105 | 106 | 107 | //为id为2的文档增加last和nick两个属性 108 | params.put("last","gaudre$au"); 109 | params.put("nick","hockey"); 110 | params.put("id",3); 111 | params.put("dynamicPriceTemplate",dynamicPriceTemplate); 112 | //通过script脚本为id为2的文档增加last和nick两个属性,为了演示效果强制refresh,实际环境慎用 113 | clientUtil.updateByPath("demo/demo/_update_by_query?refresh","scriptDslByQuery",params); 114 | //获取更新后的文档,会看到新加的2个字段属性 115 | String doc = clientUtil.getDocument("demo","demo","3"); 116 | System.out.println(doc); 117 | 118 | } 119 | 120 | 121 | } 122 | -------------------------------------------------------------------------------- /src/main/java/org/bboss/elasticsearchtest/springboot/script/ScriptImpl7.java: -------------------------------------------------------------------------------- 1 | package org.bboss.elasticsearchtest.springboot.script;/* 2 | * Copyright 2008 biaoping.yin 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import org.bboss.elasticsearchtest.springboot.crud.DocumentCRUD7; 18 | import org.frameworkset.elasticsearch.boot.BBossESStarter; 19 | import org.frameworkset.elasticsearch.client.ClientInterface; 20 | import org.springframework.beans.factory.annotation.Autowired; 21 | import org.springframework.stereotype.Service; 22 | 23 | import java.util.ArrayList; 24 | import java.util.HashMap; 25 | import java.util.List; 26 | import java.util.Map; 27 | @Service 28 | public class ScriptImpl7 { 29 | private String mappath = "esmapper/demo7.xml"; 30 | @Autowired 31 | private DocumentCRUD7 documentCRUD; 32 | @Autowired 33 | private BBossESStarter bbossESStarter; 34 | public void updateDocumentByScriptPath(){ 35 | //初始化数据,会创建type为demo的indice demo,并添加docid为2的文档 36 | 37 | documentCRUD.testCreateIndice(); 38 | documentCRUD.testBulkAddDocument(); 39 | //创建加载配置文件的客户端工具,用来检索文档,单实例多线程安全 40 | ClientInterface clientUtil = bbossESStarter.getConfigRestClient(mappath); 41 | Map params = new HashMap(); 42 | DynamicPriceTemplate dynamicPriceTemplate = new DynamicPriceTemplate(); 43 | dynamicPriceTemplate.setGoodsId(1); 44 | List ruleList = new ArrayList(); 45 | Rule rule = new Rule(); 46 | rule.setRuleCount(100); 47 | rule.setRuleExist(true); 48 | rule.setRuleId("asdfasdfasdf"); 49 | ruleList.add(rule); 50 | 51 | rule = new Rule(); 52 | rule.setRuleCount(101); 53 | rule.setRuleExist(false); 54 | rule.setRuleId("bbb$b"); 55 | ruleList.add(rule); 56 | 57 | rule = new Rule(); 58 | rule.setRuleCount(103); 59 | rule.setRuleExist(true); 60 | rule.setRuleId("ccccc"); 61 | ruleList.add(rule); 62 | dynamicPriceTemplate.setRules(ruleList); 63 | 64 | //为id为2的文档增加last和nick两个属性 65 | params.put("last","gaudreau"); 66 | params.put("nick","hockey"); 67 | params.put("dynamicPriceTemplate",dynamicPriceTemplate); 68 | //通过script脚本为id为2的文档增加last和nick两个属性,为了演示效果强制refresh,实际环境慎用 69 | clientUtil.updateByPath("demo/_update/2?refresh","scriptDsl",params); 70 | //获取更新后的文档,会看到新加的2个字段属性 71 | String doc = clientUtil.getDocument("demo","2"); 72 | System.out.println(doc); 73 | 74 | } 75 | 76 | 77 | public void updateDocumentByScriptQueryPath(){ 78 | //初始化数据,会创建type为demo的indice demo,并添加docid为2的文档 79 | 80 | documentCRUD.testCreateIndice(); 81 | documentCRUD.testBulkAddDocument(); 82 | //创建加载配置文件的客户端工具,用来检索文档,单实例多线程安全 83 | ClientInterface clientUtil = bbossESStarter.getConfigRestClient(mappath); 84 | Map params = new HashMap(); 85 | DynamicPriceTemplate dynamicPriceTemplate = new DynamicPriceTemplate(); 86 | dynamicPriceTemplate.setGoodsId(1); 87 | dynamicPriceTemplate.setGoodName("asd\"国家"); 88 | List ruleList = new ArrayList(); 89 | Rule rule = new Rule(); 90 | rule.setRuleCount(100); 91 | rule.setRuleExist(true); 92 | rule.setRuleId("asdfasd$fasdf"); 93 | ruleList.add(rule); 94 | 95 | rule = new Rule(); 96 | rule.setRuleCount(101); 97 | rule.setRuleExist(false); 98 | rule.setRuleId("bbbb"); 99 | ruleList.add(rule); 100 | 101 | rule = new Rule(); 102 | rule.setRuleCount(103); 103 | rule.setRuleExist(true); 104 | rule.setRuleId(null); 105 | ruleList.add(rule); 106 | dynamicPriceTemplate.setRules(ruleList); 107 | 108 | 109 | //为id为2的文档增加last和nick两个属性 110 | params.put("last","gaudre$au"); 111 | params.put("nick","hockey"); 112 | params.put("id",3); 113 | params.put("dynamicPriceTemplate",dynamicPriceTemplate); 114 | //通过script脚本为id为2的文档增加last和nick两个属性,为了演示效果强制refresh,实际环境慎用 115 | clientUtil.updateByPath("demo/_update_by_query?refresh","scriptDslByQuery",params); 116 | //获取更新后的文档,会看到新加的2个字段属性 117 | String doc = clientUtil.getDocument("demo","3"); 118 | System.out.println(doc); 119 | 120 | } 121 | 122 | 123 | } 124 | -------------------------------------------------------------------------------- /src/main/java/org/bboss/elasticsearchtest/springboot/thirddslcontainer/HighlightSearch.java: -------------------------------------------------------------------------------- 1 | package org.bboss.elasticsearchtest.springboot.thirddslcontainer;/* 2 | * Copyright 2008 biaoping.yin 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import com.example.esbboss.entity.Demo; 18 | import org.frameworkset.elasticsearch.client.ClientInterface; 19 | import org.frameworkset.elasticsearch.entity.ESDatas; 20 | 21 | import java.text.DateFormat; 22 | import java.text.ParseException; 23 | import java.text.SimpleDateFormat; 24 | import java.util.*; 25 | 26 | public class HighlightSearch { 27 | private ClientInterface clientInterface; 28 | 29 | public HighlightSearch(ClientInterface clientInterface) { 30 | this.clientInterface = clientInterface; 31 | } 32 | 33 | /** 34 | * 创建索引表并导入高亮检索功能需要的测试数据 35 | */ 36 | public void initIndiceAndData(){ 37 | DocumentCRUD documentCRUD = new DocumentCRUD(clientInterface); 38 | documentCRUD.testCreateIndice(); 39 | documentCRUD.testBulkAddDocuments(); 40 | } 41 | 42 | /** 43 | * 高亮显示测试用例 44 | "highlight": { 45 | "pre_tags": [ 46 | "" 47 | ], 48 | "post_tags": [ 49 | "" 50 | ], 51 | "fields": { 52 | "*": {} 53 | }, 54 | "fragment_size": 2147483647 55 | } 56 | } 57 | */ 58 | 59 | public void highlightSearch() throws ParseException { 60 | //创建加载配置文件的客户端工具,用来检索文档,单实例多线程安全 61 | //设定查询条件,通过map传递变量参数值,key对于dsl中的变量名称 62 | //dsl中有三个变量 63 | // condition 64 | // startTime 65 | // endTime 66 | Map params = new HashMap(); 67 | 68 | DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 69 | //设置时间范围,时间参数接受long值 70 | params.put("startTime",dateFormat.parse("2017-09-02 00:00:00")); 71 | params.put("endTime",new Date()); 72 | params.put("condition","喜欢唱歌");//全文检索条件,匹配上的记录的字段值对应的匹配内容都会被高亮显示 73 | //执行查询,demo为索引表,_search为检索操作action 74 | ESDatas esDatas = //ESDatas包含当前检索的记录集合,最多1000条记录,由dsl中的size属性指定 75 | clientInterface.searchList("demo/_search",//demo为索引表,_search为检索操作action 76 | "testHighlightSearch",//esmapper/demo.xml中定义的dsl语句 77 | params,//变量参数 78 | Demo.class);//返回的文档封装对象类型 79 | //获取总记录数 80 | long totalSize = esDatas.getTotalSize(); 81 | System.out.println(totalSize); 82 | //获取结果对象列表,最多返回1000条记录 83 | List demos = esDatas.getDatas(); 84 | for(int i = 0; demos != null && i < demos.size(); i ++){//遍历检索结果列表 85 | Demo demo = demos.get(i); 86 | //记录中匹配上检索条件的所有字段的高亮内容 87 | Map> highLights = demo.getHighlight(); 88 | Iterator>> entries = highLights.entrySet().iterator(); 89 | while(entries.hasNext()){ 90 | Map.Entry> entry = entries.next(); 91 | String fieldName = entry.getKey(); 92 | System.out.print(fieldName+":"); 93 | List fieldHighLightSegments = entry.getValue(); 94 | for (Object highLightSegment:fieldHighLightSegments){ 95 | /** 96 | * 在dsl中通过来标识需要高亮显示的内容,然后传到web ui前端的时候,通过为mark元素添加css样式来设置高亮的颜色背景样式 97 | * 例如: 98 | * 101 | */ 102 | System.out.println(highLightSegment); 103 | } 104 | } 105 | } 106 | 107 | // String json = clientUtil.executeRequest("demo/_search",//demo为索引表,_search为检索操作action 108 | // "searchDatas",//esmapper/demo.xml中定义的dsl语句 109 | // params); 110 | 111 | // String json = com.frameworkset.util.SimpleStringUtil.object2json(demos); 112 | 113 | } 114 | 115 | public void highlightSearchOther() throws ParseException { 116 | //创建加载配置文件的客户端工具,用来检索文档,单实例多线程安全 117 | //设定查询条件,通过map传递变量参数值,key对于dsl中的变量名称 118 | //dsl中有四个变量 119 | // applicationName1 120 | // applicationName2 121 | // startTime 122 | // endTime 123 | Map params = new HashMap(); 124 | 125 | DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 126 | //设置时间范围,时间参数接受long值 127 | params.put("startTime",dateFormat.parse("2017-09-02 00:00:00")); 128 | params.put("endTime",new Date()); 129 | params.put("condition","不喜欢唱歌");//全文检索条件,匹配上的记录的字段值对应的匹配内容都会被高亮显示 130 | //执行查询,demo为索引表,_search为检索操作action 131 | ESDatas esDatas = //ESDatas包含当前检索的记录集合,最多1000条记录,由dsl中的size属性指定 132 | clientInterface.searchList("demo/_search",//demo为索引表,_search为检索操作action 133 | "testHighlightSearch",//esmapper/demo.xml中定义的dsl语句 134 | params,//变量参数 135 | Demo.class);//返回的文档封装对象类型 136 | //获取结果对象列表,最多返回1000条记录 137 | List demos = esDatas.getDatas(); 138 | for(int i = 0; demos != null && i < demos.size(); i ++){//遍历检索结果列表 139 | Demo demo = demos.get(i); 140 | //记录中匹配上检索条件的所有字段的高亮内容 141 | Map> highLights = demo.getHighlight(); 142 | Iterator>> entries = highLights.entrySet().iterator(); 143 | while(entries.hasNext()){ 144 | Map.Entry> entry = entries.next(); 145 | String fieldName = entry.getKey(); 146 | System.out.print(fieldName+":"); 147 | List fieldHighLightSegments = entry.getValue(); 148 | for (Object highLightSegment:fieldHighLightSegments){ 149 | /** 150 | * 在dsl中通过来标识需要高亮显示的内容,然后传到web ui前端的时候,通过为mark元素添加css样式来设置高亮的颜色背景样式 151 | * 例如: 152 | * 155 | */ 156 | System.out.println(highLightSegment); 157 | } 158 | } 159 | } 160 | // String json = clientUtil.executeRequest("demo/_search",//demo为索引表,_search为检索操作action 161 | // "searchDatas",//esmapper/demo.xml中定义的dsl语句 162 | // params); 163 | 164 | // String json = com.frameworkset.util.SimpleStringUtil.object2json(demos); 165 | //获取总记录数 166 | long totalSize = esDatas.getTotalSize(); 167 | System.out.println(totalSize); 168 | } 169 | 170 | } 171 | -------------------------------------------------------------------------------- /src/main/java/org/bboss/elasticsearchtest/springboot/thirddslcontainer/HighlightSearch7.java: -------------------------------------------------------------------------------- 1 | package org.bboss.elasticsearchtest.springboot.thirddslcontainer;/* 2 | * Copyright 2008 biaoping.yin 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import com.example.esbboss.entity.Demo; 18 | import org.frameworkset.elasticsearch.client.ClientInterface; 19 | import org.frameworkset.elasticsearch.entity.ESDatas; 20 | 21 | import java.text.DateFormat; 22 | import java.text.ParseException; 23 | import java.text.SimpleDateFormat; 24 | import java.util.*; 25 | 26 | public class HighlightSearch7 { 27 | private ClientInterface clientInterface; 28 | 29 | public HighlightSearch7(ClientInterface clientInterface) { 30 | this.clientInterface = clientInterface; 31 | } 32 | /** 33 | * 创建索引表并导入高亮检索功能需要的测试数据 34 | */ 35 | public void initIndiceAndData(){ 36 | DocumentCRUD7 documentCRUD = new DocumentCRUD7(clientInterface); 37 | documentCRUD.testCreateIndice(); 38 | documentCRUD.testBulkAddDocuments(); 39 | } 40 | 41 | /** 42 | * 高亮显示测试用例 43 | "highlight": { 44 | "pre_tags": [ 45 | "" 46 | ], 47 | "post_tags": [ 48 | "" 49 | ], 50 | "fields": { 51 | "*": {} 52 | }, 53 | "fragment_size": 2147483647 54 | } 55 | } 56 | */ 57 | 58 | public void highlightSearch() throws ParseException { 59 | //创建加载配置文件的客户端工具,用来检索文档,单实例多线程安全 60 | //设定查询条件,通过map传递变量参数值,key对于dsl中的变量名称 61 | //dsl中有三个变量 62 | // condition 63 | // startTime 64 | // endTime 65 | Map params = new HashMap(); 66 | 67 | DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 68 | //设置时间范围,时间参数接受long值 69 | params.put("startTime",dateFormat.parse("2017-09-02 00:00:00")); 70 | params.put("endTime",new Date()); 71 | params.put("condition","喜欢唱歌");//全文检索条件,匹配上的记录的字段值对应的匹配内容都会被高亮显示 72 | //执行查询,demo为索引表,_search为检索操作action 73 | ESDatas esDatas = //ESDatas包含当前检索的记录集合,最多1000条记录,由dsl中的size属性指定 74 | clientInterface.searchList("demo/_search",//demo为索引表,_search为检索操作action 75 | "testHighlightSearch",//esmapper/demo.xml中定义的dsl语句 76 | params,//变量参数 77 | Demo.class);//返回的文档封装对象类型 78 | //获取总记录数 79 | long totalSize = esDatas.getTotalSize(); 80 | System.out.println(totalSize); 81 | //获取结果对象列表,最多返回1000条记录 82 | List demos = esDatas.getDatas(); 83 | for(int i = 0; demos != null && i < demos.size(); i ++){//遍历检索结果列表 84 | Demo demo = demos.get(i); 85 | //记录中匹配上检索条件的所有字段的高亮内容 86 | Map> highLights = demo.getHighlight(); 87 | Iterator>> entries = highLights.entrySet().iterator(); 88 | while(entries.hasNext()){ 89 | Map.Entry> entry = entries.next(); 90 | String fieldName = entry.getKey(); 91 | System.out.print(fieldName+":"); 92 | List fieldHighLightSegments = entry.getValue(); 93 | for (Object highLightSegment:fieldHighLightSegments){ 94 | /** 95 | * 在dsl中通过来标识需要高亮显示的内容,然后传到web ui前端的时候,通过为mark元素添加css样式来设置高亮的颜色背景样式 96 | * 例如: 97 | * 100 | */ 101 | System.out.println(highLightSegment); 102 | } 103 | } 104 | } 105 | 106 | // String json = clientUtil.executeRequest("demo/_search",//demo为索引表,_search为检索操作action 107 | // "searchDatas",//esmapper/demo.xml中定义的dsl语句 108 | // params); 109 | 110 | // String json = com.frameworkset.util.SimpleStringUtil.object2json(demos); 111 | 112 | } 113 | 114 | public void highlightSearchOther() throws ParseException { 115 | //创建加载配置文件的客户端工具,用来检索文档,单实例多线程安全 116 | //设定查询条件,通过map传递变量参数值,key对于dsl中的变量名称 117 | //dsl中有四个变量 118 | // applicationName1 119 | // applicationName2 120 | // startTime 121 | // endTime 122 | Map params = new HashMap(); 123 | 124 | DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 125 | //设置时间范围,时间参数接受long值 126 | params.put("startTime",dateFormat.parse("2017-09-02 00:00:00")); 127 | params.put("endTime",new Date()); 128 | params.put("condition","不喜欢唱歌");//全文检索条件,匹配上的记录的字段值对应的匹配内容都会被高亮显示 129 | //执行查询,demo为索引表,_search为检索操作action 130 | ESDatas esDatas = //ESDatas包含当前检索的记录集合,最多1000条记录,由dsl中的size属性指定 131 | clientInterface.searchList("demo/_search",//demo为索引表,_search为检索操作action 132 | "testHighlightSearch",//esmapper/demo.xml中定义的dsl语句 133 | params,//变量参数 134 | Demo.class);//返回的文档封装对象类型 135 | //获取结果对象列表,最多返回1000条记录 136 | List demos = esDatas.getDatas(); 137 | for(int i = 0; demos != null && i < demos.size(); i ++){//遍历检索结果列表 138 | Demo demo = demos.get(i); 139 | //记录中匹配上检索条件的所有字段的高亮内容 140 | Map> highLights = demo.getHighlight(); 141 | Iterator>> entries = highLights.entrySet().iterator(); 142 | while(entries.hasNext()){ 143 | Map.Entry> entry = entries.next(); 144 | String fieldName = entry.getKey(); 145 | System.out.print(fieldName+":"); 146 | List fieldHighLightSegments = entry.getValue(); 147 | for (Object highLightSegment:fieldHighLightSegments){ 148 | /** 149 | * 在dsl中通过来标识需要高亮显示的内容,然后传到web ui前端的时候,通过为mark元素添加css样式来设置高亮的颜色背景样式 150 | * 例如: 151 | * 154 | */ 155 | System.out.println(highLightSegment); 156 | } 157 | } 158 | } 159 | // String json = clientUtil.executeRequest("demo/_search",//demo为索引表,_search为检索操作action 160 | // "searchDatas",//esmapper/demo.xml中定义的dsl语句 161 | // params); 162 | 163 | // String json = com.frameworkset.util.SimpleStringUtil.object2json(demos); 164 | //获取总记录数 165 | long totalSize = esDatas.getTotalSize(); 166 | System.out.println(totalSize); 167 | } 168 | 169 | } 170 | -------------------------------------------------------------------------------- /src/main/java/org/bboss/elasticsearchtest/springboot/thirddslcontainer/ScriptImpl.java: -------------------------------------------------------------------------------- 1 | package org.bboss.elasticsearchtest.springboot.thirddslcontainer;/* 2 | * Copyright 2008 biaoping.yin 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import org.bboss.elasticsearchtest.springboot.script.DynamicPriceTemplate; 18 | import org.bboss.elasticsearchtest.springboot.script.Rule; 19 | import org.frameworkset.elasticsearch.client.ClientInterface; 20 | 21 | import java.util.ArrayList; 22 | import java.util.HashMap; 23 | import java.util.List; 24 | import java.util.Map; 25 | 26 | public class ScriptImpl { 27 | private ClientInterface clientInterface; 28 | 29 | public ScriptImpl(ClientInterface clientInterface) { 30 | this.clientInterface = clientInterface; 31 | } 32 | public void updateDocumentByScriptPath(){ 33 | //初始化数据,会创建type为demo的indice demo,并添加docid为2的文档 34 | DocumentCRUD documentCRUD = new DocumentCRUD(clientInterface); 35 | documentCRUD.testCreateIndice(); 36 | documentCRUD.testBulkAddDocument(); 37 | //创建加载配置文件的客户端工具,用来检索文档,单实例多线程安全 38 | Map params = new HashMap(); 39 | DynamicPriceTemplate dynamicPriceTemplate = new DynamicPriceTemplate(); 40 | dynamicPriceTemplate.setGoodsId(1); 41 | List ruleList = new ArrayList(); 42 | Rule rule = new Rule(); 43 | rule.setRuleCount(100); 44 | rule.setRuleExist(true); 45 | rule.setRuleId("asdfasdfasdf"); 46 | ruleList.add(rule); 47 | 48 | rule = new Rule(); 49 | rule.setRuleCount(101); 50 | rule.setRuleExist(false); 51 | rule.setRuleId("bbb$b"); 52 | ruleList.add(rule); 53 | 54 | rule = new Rule(); 55 | rule.setRuleCount(103); 56 | rule.setRuleExist(true); 57 | rule.setRuleId("ccccc"); 58 | ruleList.add(rule); 59 | dynamicPriceTemplate.setRules(ruleList); 60 | 61 | //为id为2的文档增加last和nick两个属性 62 | params.put("last","gaudreau"); 63 | params.put("nick","hockey"); 64 | params.put("dynamicPriceTemplate",dynamicPriceTemplate); 65 | //通过script脚本为id为2的文档增加last和nick两个属性,为了演示效果强制refresh,实际环境慎用 66 | clientInterface.updateByPath("demo/demo/2/_update?refresh","scriptDsl",params); 67 | //获取更新后的文档,会看到新加的2个字段属性 68 | String doc = clientInterface.getDocument("demo","demo","2"); 69 | System.out.println(doc); 70 | 71 | } 72 | 73 | 74 | public void updateDocumentByScriptQueryPath(){ 75 | //初始化数据,会创建type为demo的indice demo,并添加docid为2的文档 76 | DocumentCRUD documentCRUD = new DocumentCRUD(clientInterface); 77 | documentCRUD.testCreateIndice(); 78 | documentCRUD.testBulkAddDocument(); 79 | //创建加载配置文件的客户端工具,用来检索文档,单实例多线程安全 80 | Map params = new HashMap(); 81 | DynamicPriceTemplate dynamicPriceTemplate = new DynamicPriceTemplate(); 82 | dynamicPriceTemplate.setGoodsId(1); 83 | dynamicPriceTemplate.setGoodName("asd\"国家"); 84 | List ruleList = new ArrayList(); 85 | Rule rule = new Rule(); 86 | rule.setRuleCount(100); 87 | rule.setRuleExist(true); 88 | rule.setRuleId("asdfasd$fasdf"); 89 | ruleList.add(rule); 90 | 91 | rule = new Rule(); 92 | rule.setRuleCount(101); 93 | rule.setRuleExist(false); 94 | rule.setRuleId("bbbb"); 95 | ruleList.add(rule); 96 | 97 | rule = new Rule(); 98 | rule.setRuleCount(103); 99 | rule.setRuleExist(true); 100 | rule.setRuleId(null); 101 | ruleList.add(rule); 102 | dynamicPriceTemplate.setRules(ruleList); 103 | 104 | 105 | //为id为2的文档增加last和nick两个属性 106 | params.put("last","gaudre$au"); 107 | params.put("nick","hockey"); 108 | params.put("id",3); 109 | params.put("dynamicPriceTemplate",dynamicPriceTemplate); 110 | //通过script脚本为id为2的文档增加last和nick两个属性,为了演示效果强制refresh,实际环境慎用 111 | clientInterface.updateByPath("demo/demo/_update_by_query?refresh","scriptDslByQuery",params); 112 | //获取更新后的文档,会看到新加的2个字段属性 113 | String doc = clientInterface.getDocument("demo","demo","3"); 114 | System.out.println(doc); 115 | 116 | } 117 | 118 | 119 | } 120 | -------------------------------------------------------------------------------- /src/main/java/org/bboss/elasticsearchtest/springboot/thirddslcontainer/ScriptImpl7.java: -------------------------------------------------------------------------------- 1 | package org.bboss.elasticsearchtest.springboot.thirddslcontainer;/* 2 | * Copyright 2008 biaoping.yin 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import org.bboss.elasticsearchtest.springboot.script.DynamicPriceTemplate; 18 | import org.bboss.elasticsearchtest.springboot.script.Rule; 19 | import org.frameworkset.elasticsearch.client.ClientInterface; 20 | 21 | import java.util.ArrayList; 22 | import java.util.HashMap; 23 | import java.util.List; 24 | import java.util.Map; 25 | 26 | public class ScriptImpl7 { 27 | private ClientInterface clientInterface; 28 | 29 | public ScriptImpl7(ClientInterface clientInterface) { 30 | this.clientInterface = clientInterface; 31 | } 32 | public void updateDocumentByScriptPath(){ 33 | //初始化数据,会创建type为demo的indice demo,并添加docid为2的文档 34 | DocumentCRUD7 documentCRUD = new DocumentCRUD7(clientInterface); 35 | documentCRUD.testCreateIndice(); 36 | documentCRUD.testBulkAddDocument(); 37 | //创建加载配置文件的客户端工具,用来检索文档,单实例多线程安全 38 | Map params = new HashMap(); 39 | DynamicPriceTemplate dynamicPriceTemplate = new DynamicPriceTemplate(); 40 | dynamicPriceTemplate.setGoodsId(1); 41 | List ruleList = new ArrayList(); 42 | Rule rule = new Rule(); 43 | rule.setRuleCount(100); 44 | rule.setRuleExist(true); 45 | rule.setRuleId("asdfasdfasdf"); 46 | ruleList.add(rule); 47 | 48 | rule = new Rule(); 49 | rule.setRuleCount(101); 50 | rule.setRuleExist(false); 51 | rule.setRuleId("bbb$b"); 52 | ruleList.add(rule); 53 | 54 | rule = new Rule(); 55 | rule.setRuleCount(103); 56 | rule.setRuleExist(true); 57 | rule.setRuleId("ccccc"); 58 | ruleList.add(rule); 59 | dynamicPriceTemplate.setRules(ruleList); 60 | 61 | //为id为2的文档增加last和nick两个属性 62 | params.put("last","gaudreau"); 63 | params.put("nick","hockey"); 64 | params.put("dynamicPriceTemplate",dynamicPriceTemplate); 65 | //通过script脚本为id为2的文档增加last和nick两个属性,为了演示效果强制refresh,实际环境慎用 66 | clientInterface.updateByPath("demo/_update/2?refresh","scriptDsl",params); 67 | //获取更新后的文档,会看到新加的2个字段属性 68 | String doc = clientInterface.getDocument("demo","2"); 69 | System.out.println(doc); 70 | 71 | } 72 | 73 | 74 | public void updateDocumentByScriptQueryPath(){ 75 | //初始化数据,会创建type为demo的indice demo,并添加docid为2的文档 76 | DocumentCRUD7 documentCRUD = new DocumentCRUD7(clientInterface); 77 | documentCRUD.testCreateIndice(); 78 | documentCRUD.testBulkAddDocument(); 79 | //创建加载配置文件的客户端工具,用来检索文档,单实例多线程安全 80 | Map params = new HashMap(); 81 | DynamicPriceTemplate dynamicPriceTemplate = new DynamicPriceTemplate(); 82 | dynamicPriceTemplate.setGoodsId(1); 83 | dynamicPriceTemplate.setGoodName("asd\"国家"); 84 | List ruleList = new ArrayList(); 85 | Rule rule = new Rule(); 86 | rule.setRuleCount(100); 87 | rule.setRuleExist(true); 88 | rule.setRuleId("asdfasd$fasdf"); 89 | ruleList.add(rule); 90 | 91 | rule = new Rule(); 92 | rule.setRuleCount(101); 93 | rule.setRuleExist(false); 94 | rule.setRuleId("bbbb"); 95 | ruleList.add(rule); 96 | 97 | rule = new Rule(); 98 | rule.setRuleCount(103); 99 | rule.setRuleExist(true); 100 | rule.setRuleId(null); 101 | ruleList.add(rule); 102 | dynamicPriceTemplate.setRules(ruleList); 103 | 104 | 105 | //为id为2的文档增加last和nick两个属性 106 | params.put("last","gaudre$au"); 107 | params.put("nick","hockey"); 108 | params.put("id",3); 109 | params.put("dynamicPriceTemplate",dynamicPriceTemplate); 110 | //通过script脚本为id为2的文档增加last和nick两个属性,为了演示效果强制refresh,实际环境慎用 111 | clientInterface.updateByPath("demo/_update_by_query?refresh","scriptDslByQuery",params); 112 | //获取更新后的文档,会看到新加的2个字段属性 113 | String doc = clientInterface.getDocument("demo","3"); 114 | System.out.println(doc); 115 | 116 | } 117 | 118 | 119 | } 120 | -------------------------------------------------------------------------------- /src/main/resources/application-multi-datasource.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | elasticsearch: 3 | bboss: 4 | default: 5 | name: default 6 | elasticPassword: changeme 7 | elasticUser: elastic 8 | elasticsearch: 9 | dateFormat: yyyy.MM.dd 10 | discoverHost: false 11 | rest: 12 | hostNames: 192.168.137.1:9200 13 | scrollBlockedWaitTimeout: 0 14 | scrollThreadCount: 200 15 | scrollThreadQueue: 200 16 | showTemplate: true 17 | sliceScrollBlockedWaitTimeout: 0 18 | sliceScrollThreadCount: 100 19 | sliceScrollThreadQueue: 100 20 | timeZone: Asia/Shanghai 21 | http: 22 | connectionRequestTimeout: 50000 23 | customHttpRequestRetryHandler: org.frameworkset.spi.remote.http.ConnectionResetHttpRequestRetryHandler 24 | defaultMaxPerRoute: 200 25 | hostnameVerifier: '' 26 | keyPassword: '' 27 | keystore: '' 28 | maxHeaderCount: 200 29 | maxLineLength: -1 30 | maxTotal: 400 31 | retryTime: 1 32 | retryInterval: 10000 33 | staleConnectionCheckEnabled: false 34 | timeoutConnection: 50000 35 | timeoutSocket: 50000 36 | validateAfterInactivity: 200000 37 | dslfile: 38 | refreshInterval: -1 39 | logs: 40 | name: logs 41 | elasticPassword: changeme 42 | elasticUser: elastic 43 | elasticsearch: 44 | dateFormat: yyyy.MM.dd 45 | discoverHost: false 46 | rest: 47 | hostNames: 192.168.137.1:9200 48 | scrollBlockedWaitTimeout: 0 49 | scrollThreadCount: 200 50 | scrollThreadQueue: 200 51 | showTemplate: true 52 | sliceScrollBlockedWaitTimeout: 0 53 | sliceScrollThreadCount: 100 54 | sliceScrollThreadQueue: 100 55 | timeZone: Asia/Shanghai 56 | http: 57 | connectionRequestTimeout: 50000 58 | customHttpRequestRetryHandler: org.frameworkset.spi.remote.http.ConnectionResetHttpRequestRetryHandler 59 | defaultMaxPerRoute: 200 60 | hostnameVerifier: '' 61 | keyPassword: '' 62 | keystore: '' 63 | maxHeaderCount: 200 64 | maxLineLength: -1 65 | maxTotal: 400 66 | retryTime: 1 67 | staleConnectionCheckEnabled: false 68 | timeoutConnection: 50000 69 | timeoutSocket: 50000 70 | validateAfterInactivity: 200000 71 | 72 | -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | elasticsearch: 3 | bboss: 4 | elasticPassword: changeme 5 | elasticUser: elastic 6 | elasticsearch: 7 | dateFormat: yyyy.MM.dd 8 | discoverHost: false 9 | rest: 10 | hostNames: 192.168.137.1:9200 11 | scrollBlockedWaitTimeout: 0 12 | scrollThreadCount: 200 13 | scrollThreadQueue: 200 14 | showTemplate: true 15 | sliceScrollBlockedWaitTimeout: 0 16 | sliceScrollThreadCount: 100 17 | sliceScrollThreadQueue: 100 18 | http: 19 | connectionRequestTimeout: 50000 20 | customHttpRequestRetryHandler: org.frameworkset.spi.remote.http.ConnectionResetHttpRequestRetryHandler 21 | defaultMaxPerRoute: 200 22 | hostnameVerifier: 23 | keepAlive: 3600000 24 | keyPassword: 25 | keystore: 26 | maxHeaderCount: 200 27 | maxLineLength: -1 28 | maxTotal: 400 29 | retryTime: 1 30 | retryInterval: 1000 31 | soKeepAlive: false 32 | soReuseAddress: false 33 | staleConnectionCheckEnabled: false 34 | timeToLive: 3600000 35 | timeoutConnection: 50000 36 | timeoutSocket: 50000 37 | validateAfterInactivity: 50000 38 | db: 39 | driver: com.mysql.jdbc.Driver 40 | name: test 41 | password: 123456 42 | url: jdbc:mysql://localhost:3306/bboss 43 | usePool: false 44 | user: root 45 | validateSQL: select 1 46 | dslfile: 47 | refreshInterval: -1 48 | ##dslMappingDir: D:/workdir/es 49 | propertiesInterceptor: org.bboss.elasticsearchtest.springboot.TestPropertiesInterceptor 50 | # 添加 log4j2 配置 51 | logging: 52 | config: classpath:log4j2.yaml -------------------------------------------------------------------------------- /src/main/resources/config/application-multi-datasource.properties.example: -------------------------------------------------------------------------------- 1 | ##多集群配置样例,如果需要做多集群配置,请将参照本文内容修改application.properties文件内容 2 | spring.elasticsearch.bboss.default.name = default 3 | ##default集群配配置 4 | spring.elasticsearch.bboss.default.elasticUser=elastic 5 | spring.elasticsearch.bboss.default.elasticPassword=changeme 6 | 7 | spring.elasticsearch.bboss.default.elasticsearch.rest.hostNames=10.21.20.168:9200 8 | #spring.elasticsearch.bboss.default.elasticsearch.rest.hostNames=10.180.211.27:9280,10.180.211.27:9281,10.180.211.27:9282 9 | ##https配置 10 | #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 11 | spring.elasticsearch.bboss.default.elasticsearch.dateFormat=yyyy.MM.dd 12 | spring.elasticsearch.bboss.default.elasticsearch.timeZone=Asia/Shanghai 13 | #在控制台输出脚本调试开关showTemplate,false关闭,true打开,同时log4j至少是info级别 14 | spring.elasticsearch.bboss.default.elasticsearch.showTemplate=true 15 | spring.elasticsearch.bboss.default.elasticsearch.discoverHost=false 16 | 17 | #设置slice scroll查询对应的线程数和等待队列数 18 | spring.elasticsearch.bboss.default.elasticsearch.sliceScrollThreadCount=100 19 | spring.elasticsearch.bboss.default.elasticsearch.sliceScrollThreadQueue=100 20 | spring.elasticsearch.bboss.default.elasticsearch.sliceScrollBlockedWaitTimeout=0 21 | 22 | #设置scroll查询对应的线程数和等待队列数 23 | spring.elasticsearch.bboss.default.elasticsearch.scrollThreadCount=200 24 | spring.elasticsearch.bboss.default.elasticsearch.scrollThreadQueue=200 25 | spring.elasticsearch.bboss.default.elasticsearch.scrollBlockedWaitTimeout=0 26 | 27 | ##default连接池配置 28 | spring.elasticsearch.bboss.default.http.timeoutConnection = 5000 29 | spring.elasticsearch.bboss.default.http.timeoutSocket = 5000 30 | spring.elasticsearch.bboss.default.http.connectionRequestTimeout=5000 31 | spring.elasticsearch.bboss.default.http.retryTime = 1 32 | spring.elasticsearch.bboss.default.http.retryInterval = 1000 33 | spring.elasticsearch.bboss.default.http.maxLineLength = -1 34 | spring.elasticsearch.bboss.default.http.maxHeaderCount = 200 35 | spring.elasticsearch.bboss.default.http.maxTotal = 400 36 | spring.elasticsearch.bboss.default.http.defaultMaxPerRoute = 200 37 | spring.elasticsearch.bboss.default.http.keystore = 38 | spring.elasticsearch.bboss.default.http.keyPassword = 39 | # ssl 主机名称校验,是否采用default配置, 40 | # 如果指定为default,就采用DefaultHostnameVerifier,否则采用 SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER 41 | spring.elasticsearch.bboss.default.http.hostnameVerifier = 42 | #每隔多少毫秒校验空闲connection,自动释放无效链接 43 | # -1 或者0不检查 44 | spring.elasticsearch.bboss.default.http.validateAfterInactivity=2000 45 | # 每次获取connection时校验连接,true,校验,false不校验,有性能开销,推荐采用 46 | # validateAfterInactivity来控制连接是否有效 47 | # 默认值false 48 | spring.elasticsearch.bboss.default.http.staleConnectionCheckEnabled=false 49 | #* 自定义重试控制接口,必须实现接口方法 50 | #* public interface CustomHttpRequestRetryHandler { 51 | #* public boolean retryRequest(IOException exception, int executionCount, HttpContext context,ClientConfiguration configuration); 52 | #* } 53 | #* 方法返回true,进行重试,false不重试 54 | spring.elasticsearch.bboss.default.http.customHttpRequestRetryHandler=org.frameworkset.spi.remote.http.ConnectionResetHttpRequestRetryHandler 55 | 56 | 57 | ##logs集群配置 58 | spring.elasticsearch.bboss.logs.name = logs 59 | spring.elasticsearch.bboss.logs.elasticUser=elastic 60 | spring.elasticsearch.bboss.logs.elasticPassword=changeme 61 | 62 | #elasticsearch.rest.hostNames=10.1.236.88:9200 63 | spring.elasticsearch.bboss.logs.elasticsearch.rest.hostNames=10.1.236.88:9200 64 | #elasticsearch.rest.hostNames=10.21.20.168:9200 65 | #elasticsearch.rest.hostNames=10.180.211.27:9280,10.180.211.27:9281,10.180.211.27:9282 66 | spring.elasticsearch.bboss.logs.elasticsearch.dateFormat=yyyy.MM.dd 67 | spring.elasticsearch.bboss.logs.elasticsearch.timeZone=Asia/Shanghai 68 | #在控制台输出脚本调试开关showTemplate,false关闭,true打开,同时log4j至少是info级别 69 | spring.elasticsearch.bboss.logs.elasticsearch.showTemplate=true 70 | spring.elasticsearch.bboss.logs.elasticsearch.discoverHost=false 71 | 72 | #设置slice scroll查询对应的线程数和等待队列数 73 | spring.elasticsearch.bboss.logs.elasticsearch.sliceScrollThreadCount=100 74 | spring.elasticsearch.bboss.logs.elasticsearch.sliceScrollThreadQueue=100 75 | spring.elasticsearch.bboss.logs.elasticsearch.sliceScrollBlockedWaitTimeout=0 76 | 77 | #设置scroll查询对应的线程数和等待队列数 78 | spring.elasticsearch.bboss.logs.elasticsearch.scrollThreadCount=200 79 | spring.elasticsearch.bboss.logs.elasticsearch.scrollThreadQueue=200 80 | spring.elasticsearch.bboss.logs.elasticsearch.scrollBlockedWaitTimeout=0 81 | 82 | ##logs集群对应的连接池配置 83 | spring.elasticsearch.bboss.logs.http.timeoutConnection = 5000 84 | spring.elasticsearch.bboss.logs.http.timeoutSocket = 5000 85 | spring.elasticsearch.bboss.logs.http.connectionRequestTimeout=5000 86 | spring.elasticsearch.bboss.logs.http.retryTime = 1 87 | spring.elasticsearch.bboss.logs.http.retryInterval = 1000 88 | spring.elasticsearch.bboss.logs.http.maxLineLength = -1 89 | spring.elasticsearch.bboss.logs.http.maxHeaderCount = 200 90 | spring.elasticsearch.bboss.logs.http.maxTotal = 400 91 | spring.elasticsearch.bboss.logs.http.defaultMaxPerRoute = 200 92 | # https证书配置 93 | spring.elasticsearch.bboss.logs.http.keystore = 94 | spring.elasticsearch.bboss.logs.http.keyPassword = 95 | # ssl 主机名称校验,是否采用default配置, 96 | # 如果指定为default,就采用DefaultHostnameVerifier,否则采用 SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER 97 | spring.elasticsearch.bboss.logs.http.hostnameVerifier = 98 | #每隔多少毫秒校验空闲connection,自动释放无效链接 99 | # -1 或者0不检查 100 | spring.elasticsearch.bboss.logs.http.validateAfterInactivity=2000 101 | # 每次获取connection时校验连接,true,校验,false不校验,有性能开销,推荐采用 102 | # validateAfterInactivity来控制连接是否有效 103 | # 默认值false 104 | spring.elasticsearch.bboss.logs.http.staleConnectionCheckEnabled=false 105 | #* 自定义重试控制接口,必须实现接口方法 106 | #* public interface CustomHttpRequestRetryHandler { 107 | #* public boolean retryRequest(IOException exception, int executionCount, HttpContext context,ClientConfiguration configuration); 108 | #* } 109 | #* 方法返回true,进行重试,false不重试 110 | spring.elasticsearch.bboss.logs.http.customHttpRequestRetryHandler=org.frameworkset.spi.remote.http.ConnectionResetHttpRequestRetryHandler 111 | 112 | 113 | # dsl配置文件热加载扫描时间间隔,毫秒为单位,默认5秒扫描一次,<= 0时关闭扫描机制 114 | spring.elasticsearch.bboss.dslfile.refreshInterval = -1 -------------------------------------------------------------------------------- /src/main/resources/config/application.properties.example: -------------------------------------------------------------------------------- 1 | ##ES集群配置,支持x-pack和searchguard 2 | spring.elasticsearch.bboss.elasticUser=elastic 3 | spring.elasticsearch.bboss.elasticPassword=changeme 4 | 5 | 6 | spring.elasticsearch.bboss.elasticsearch.rest.hostNames=127.0.0.1:9200 7 | #spring.elasticsearch.bboss.elasticsearch.rest.hostNames=10.180.211.27:9280,10.180.211.27:9281,10.180.211.27:9282 8 | ##https配置,添加https://协议头 9 | #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 10 | spring.elasticsearch.bboss.elasticsearch.dateFormat=yyyy.MM.dd 11 | spring.elasticsearch.bboss.elasticsearch.timeZone=Asia/Shanghai 12 | #在控制台输出脚本调试开关showTemplate,false关闭,true打开,同时log4j至少是info级别 13 | spring.elasticsearch.bboss.elasticsearch.showTemplate=true 14 | spring.elasticsearch.bboss.elasticsearch.discoverHost=false 15 | # dsl配置文件热加载扫描时间间隔,毫秒为单位,默认5秒扫描一次,<= 0时关闭扫描机制 16 | spring.elasticsearch.bboss.dslfile.refreshInterval = -1 17 | 18 | 19 | #设置slice scroll查询对应的线程数和等待队列数 20 | spring.elasticsearch.bboss.elasticsearch.sliceScrollThreadCount=100 21 | spring.elasticsearch.bboss.elasticsearch.sliceScrollThreadQueue=100 22 | spring.elasticsearch.bboss.elasticsearch.sliceScrollBlockedWaitTimeout=0 23 | 24 | #设置scroll查询对应的线程数和等待队列数 25 | spring.elasticsearch.bboss.elasticsearch.scrollThreadCount=200 26 | spring.elasticsearch.bboss.elasticsearch.scrollThreadQueue=200 27 | spring.elasticsearch.bboss.elasticsearch.scrollBlockedWaitTimeout=0 28 | 29 | ##es client http连接池配置 30 | spring.elasticsearch.bboss.http.timeoutConnection = 5000 31 | spring.elasticsearch.bboss.http.timeoutSocket = 5000 32 | spring.elasticsearch.bboss.http.connectionRequestTimeout=5000 33 | spring.elasticsearch.bboss.http.retryTime = 1 34 | spring.elasticsearch.bboss.http.retryInterval = 1000 35 | spring.elasticsearch.bboss.http.maxLineLength = -1 36 | spring.elasticsearch.bboss.http.maxHeaderCount = 200 37 | spring.elasticsearch.bboss.http.maxTotal = 400 38 | spring.elasticsearch.bboss.http.defaultMaxPerRoute = 200 39 | spring.elasticsearch.bboss.http.soReuseAddress = false 40 | spring.elasticsearch.bboss.http.soKeepAlive = false 41 | spring.elasticsearch.bboss.http.timeToLive = 3600000 42 | spring.elasticsearch.bboss.http.keepAlive = 3600000 43 | spring.elasticsearch.bboss.http.keystore = 44 | spring.elasticsearch.bboss.http.keyPassword = 45 | # ssl 主机名称校验,是否采用default配置, 46 | # 如果指定为default,就采用DefaultHostnameVerifier,否则采用 SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER 47 | spring.elasticsearch.bboss.http.hostnameVerifier = 48 | 49 | #每隔多少毫秒校验空闲connection,自动释放无效链接 50 | # -1 或者0不检查 51 | spring.elasticsearch.bboss.http.validateAfterInactivity=2000 52 | # 每次获取connection时校验连接,true,校验,false不校验,有性能开销,推荐采用 53 | # validateAfterInactivity来控制连接是否有效 54 | # 默认值false 55 | spring.elasticsearch.bboss.http.staleConnectionCheckEnabled=false 56 | #* 自定义重试控制接口,必须实现接口方法 57 | #* public interface CustomHttpRequestRetryHandler { 58 | #* public boolean retryRequest(IOException exception, int executionCount, HttpContext context,ClientConfiguration configuration); 59 | #* } 60 | #* 方法返回true,进行重试,false不重试 61 | spring.elasticsearch.bboss.http.customHttpRequestRetryHandler=org.frameworkset.spi.remote.http.ConnectionResetHttpRequestRetryHandler 62 | 63 | 64 | # 数据库数据源配置 65 | spring.elasticsearch.bboss.db.name = test 66 | spring.elasticsearch.bboss.db.user = root 67 | spring.elasticsearch.bboss.db.password = 123456 68 | spring.elasticsearch.bboss.db.driver = com.mysql.jdbc.Driver 69 | spring.elasticsearch.bboss.db.url = jdbc:mysql://localhost:3306/bboss 70 | spring.elasticsearch.bboss.db.usePool = false 71 | spring.elasticsearch.bboss.db.validateSQL = select 1 72 | 73 | -------------------------------------------------------------------------------- /src/main/resources/esmapper/scroll.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 15 | 16 | 19 | 20 | 33 | 34 | -------------------------------------------------------------------------------- /src/main/resources/log4j2.yaml: -------------------------------------------------------------------------------- 1 | Configuration: 2 | status: WARN 3 | Appenders: 4 | Console: 5 | name: Console 6 | target: SYSTEM_OUT 7 | PatternLayout: 8 | pattern: "%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" 9 | RollingFile: 10 | name: RollingFile 11 | fileName: eshelloword-spring-boot-starter.log 12 | filePattern: "eshelloword-spring-boot-starter-%d{yyyy-MM-dd}-%i.log" 13 | PatternLayout: 14 | pattern: "[%d{yyyy-MM-dd HH:mm:ss:SSS}] [%p] - %l - %m%n" 15 | Policies: 16 | # TimeBasedTriggeringPolicy: 17 | SizeBasedTriggeringPolicy: 18 | size: 10 MB 19 | DefaultRolloverStrategy: 20 | max: 5 21 | Loggers: 22 | Root: 23 | level: INFO 24 | AppenderRef: 25 | - ref: Console 26 | - ref: RollingFile 27 | -------------------------------------------------------------------------------- /src/test/java/org/bboss/elasticsearchtest/springboot/BBossES7StarterTestCase.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 1999-2018 Alibaba Group Holding Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.bboss.elasticsearchtest.springboot; 17 | 18 | 19 | import org.bboss.elasticsearchtest.springboot.crud.DocumentCRUD7; 20 | import org.junit.Test; 21 | import org.junit.runner.RunWith; 22 | import org.springframework.beans.factory.annotation.Autowired; 23 | import org.springframework.boot.test.context.SpringBootTest; 24 | import org.springframework.test.context.junit4.SpringRunner; 25 | 26 | /** 27 | * 单集群演示功能测试用例,spring boot配置项以spring.elasticsearch.bboss开头 28 | * 对应的配置文件为application.properties文件 29 | * @author yinbp [122054810@qq.com] 30 | */ 31 | @RunWith(SpringRunner.class) 32 | @SpringBootTest 33 | public class BBossES7StarterTestCase { 34 | 35 | @Autowired 36 | DocumentCRUD7 documentCRUD; 37 | 38 | @Test 39 | public void testBbossESStarter() throws Exception { 40 | // System.out.println(bbossESStarter); 41 | 42 | //验证环境,获取es状态 43 | // String response = serviceApiUtil.restClient().executeHttp("_cluster/state?pretty",ClientInterface.HTTP_GET); 44 | 45 | // System.out.println(response); 46 | //判断索引类型是否存在,false表示不存在,正常返回true表示存在 47 | // boolean exist = bbossESStarter.getRestClient().existIndiceType("twitter","_doc"); 48 | 49 | //判读索引是否存在,false表示不存在,正常返回true表示存在 50 | documentCRUD.testBbossESStarter(); 51 | 52 | } 53 | /** should install plugin in elasticsearch to run follow method : 54 | * https://github.com/NLPchina/elasticsearch-sql 55 | @Test 56 | public void testESSQLTranslate(){ 57 | ClientInterface clientUtil = bbossESStarter.getRestClient(); 58 | String dsl = //将sql转换为dsl 59 | clientUtil.executeHttp("/_sql/_explain",//sql请求 60 | "select operModule.keyword from dbdemo group by operModule.keyword ",ClientInterface.HTTP_POST);//返回的文档封装对象类型 61 | 62 | //获取总记录数 63 | System.out.println(dsl); 64 | } 65 | */ 66 | @Test 67 | public void testCRUD() throws Exception { 68 | 69 | //删除/创建文档索引表 70 | documentCRUD.testCreateIndice(); 71 | //添加/修改单个文档 72 | 73 | documentCRUD.testAddAndUpdateDocument(); 74 | //批量添加文档 75 | documentCRUD.testBulkAddDocument(); 76 | //检索文档 77 | documentCRUD.testSearch(); 78 | //批量修改文档 79 | documentCRUD.testBulkUpdateDocument(); 80 | 81 | //检索批量修改后的文档 82 | documentCRUD.testSearch(); 83 | //带list复杂参数的文档检索操作 84 | documentCRUD.testSearchArray(); 85 | //带from/size分页操作的文档检索操作 86 | documentCRUD.testPagineSearch(); 87 | //带sourcefilter的文档检索操作 88 | documentCRUD.testSearchSourceFilter(); 89 | 90 | documentCRUD.updateDemoIndice(); 91 | documentCRUD.testBulkAddDocuments(); 92 | } 93 | 94 | @Test 95 | public void testPerformaceCRUD() throws Exception { 96 | 97 | //删除/创建文档索引表 98 | documentCRUD.testCreateIndice(); 99 | 100 | documentCRUD.testBulkAddDocuments(); 101 | } 102 | 103 | } 104 | -------------------------------------------------------------------------------- /src/test/java/org/bboss/elasticsearchtest/springboot/BBossESStarterTestCase.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 1999-2018 Alibaba Group Holding Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.bboss.elasticsearchtest.springboot; 17 | 18 | 19 | import org.bboss.elasticsearchtest.springboot.crud.DocumentCRUD; 20 | import org.frameworkset.elasticsearch.boot.BBossESStarter; 21 | import org.frameworkset.elasticsearch.client.ClientInterface; 22 | import org.junit.Test; 23 | import org.junit.runner.RunWith; 24 | import org.springframework.beans.factory.annotation.Autowired; 25 | import org.springframework.boot.test.context.SpringBootTest; 26 | import org.springframework.test.context.junit4.SpringRunner; 27 | 28 | /** 29 | * 单集群演示功能测试用例,spring boot配置项以spring.elasticsearch.bboss开头 30 | * 对应的配置文件为application.properties文件 31 | * @author yinbp [122054810@qq.com] 32 | */ 33 | @RunWith(SpringRunner.class) 34 | @SpringBootTest 35 | public class BBossESStarterTestCase { 36 | @Autowired 37 | private BBossESStarter bbossESStarter; 38 | @Autowired 39 | DocumentCRUD documentCRUD; 40 | 41 | @Test 42 | public void testBbossESStarter() throws Exception { 43 | // System.out.println(bbossESStarter); 44 | 45 | //验证环境,获取es状态 46 | // String response = serviceApiUtil.restClient().executeHttp("_cluster/state?pretty",ClientInterface.HTTP_GET); 47 | 48 | // System.out.println(response); 49 | //判断索引类型是否存在,false表示不存在,正常返回true表示存在 50 | boolean exist = bbossESStarter.getRestClient().existIndiceType("twitter","tweet"); 51 | 52 | //判读索引是否存在,false表示不存在,正常返回true表示存在 53 | exist = bbossESStarter.getRestClient().existIndice("twitter"); 54 | 55 | exist = bbossESStarter.getRestClient().existIndice("agentinfo"); 56 | 57 | } 58 | 59 | @Test 60 | public void testESSQLTranslate(){ 61 | ClientInterface clientUtil = bbossESStarter.getRestClient(); 62 | String dsl = //将sql转换为dsl 63 | clientUtil.executeHttp("/_sql/_explain",//sql请求 64 | "select operModule.keyword from dbdemo group by operModule.keyword ",ClientInterface.HTTP_POST);//返回的文档封装对象类型 65 | 66 | //获取总记录数 67 | System.out.println(dsl); 68 | } 69 | 70 | @Test 71 | public void testCRUD() throws Exception { 72 | 73 | //删除/创建文档索引表 74 | documentCRUD.testCreateIndice(); 75 | //添加/修改单个文档 76 | 77 | documentCRUD.testAddAndUpdateDocument(); 78 | //批量添加文档 79 | documentCRUD.testBulkAddDocument(); 80 | //检索文档 81 | documentCRUD.testSearch(); 82 | //批量修改文档 83 | documentCRUD.testBulkUpdateDocument(); 84 | 85 | //检索批量修改后的文档 86 | documentCRUD.testSearch(); 87 | //带list复杂参数的文档检索操作 88 | documentCRUD.testSearchArray(); 89 | //带from/size分页操作的文档检索操作 90 | documentCRUD.testPagineSearch(); 91 | //带sourcefilter的文档检索操作 92 | documentCRUD.testSearchSourceFilter(); 93 | 94 | documentCRUD.updateDemoIndice(); 95 | documentCRUD.testBulkAddDocuments(); 96 | } 97 | 98 | @Test 99 | public void testPerformaceCRUD() throws Exception { 100 | 101 | //删除/创建文档索引表 102 | documentCRUD.testCreateIndice(); 103 | 104 | documentCRUD.testBulkAddDocuments(); 105 | } 106 | 107 | } 108 | -------------------------------------------------------------------------------- /src/test/java/org/bboss/elasticsearchtest/springboot/BulkProcessor7Test.java: -------------------------------------------------------------------------------- 1 | package org.bboss.elasticsearchtest.springboot; 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 org.bboss.elasticsearchtest.springboot.bulk.TestBulkProcessor7x; 19 | import org.frameworkset.elasticsearch.boot.BBossESStarter; 20 | import org.junit.Test; 21 | import org.junit.runner.RunWith; 22 | import org.slf4j.Logger; 23 | import org.slf4j.LoggerFactory; 24 | import org.springframework.beans.factory.annotation.Autowired; 25 | import org.springframework.boot.test.context.SpringBootTest; 26 | import org.springframework.test.context.junit4.SpringRunner; 27 | 28 | import java.util.ArrayList; 29 | 30 | import static java.lang.Thread.sleep; 31 | 32 | /** 33 | *

Description:

34 | *

35 | *

Copyright (c) 2018

36 | * @Date 2019/9/18 10:27 37 | * @author biaoping.yin 38 | * @version 1.0 39 | */ 40 | @RunWith(SpringRunner.class) 41 | @SpringBootTest 42 | public class BulkProcessor7Test { 43 | private Logger logger = LoggerFactory.getLogger(BulkProcessor7Test.class); 44 | @Autowired 45 | private BBossESStarter bbossESStarter; 46 | @Autowired 47 | private TestBulkProcessor7x testBulkProcessor7x; 48 | @Test 49 | public void testBulkProcessor7x(){ 50 | 51 | testBulkProcessor7x.buildBulkProcessor(); 52 | do { 53 | 54 | testBulkProcessor7x.testBulkDatas(); 55 | try { 56 | sleep(1000l); 57 | } catch (InterruptedException e) { 58 | e.printStackTrace(); 59 | } 60 | }while(true); 61 | 62 | 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/test/java/org/bboss/elasticsearchtest/springboot/BulkProcessorTest.java: -------------------------------------------------------------------------------- 1 | package org.bboss.elasticsearchtest.springboot; 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 org.bboss.elasticsearchtest.springboot.bulk.TestBulkProcessor; 19 | import org.frameworkset.elasticsearch.boot.BBossESStarter; 20 | import org.junit.Test; 21 | import org.junit.runner.RunWith; 22 | import org.slf4j.Logger; 23 | import org.slf4j.LoggerFactory; 24 | import org.springframework.beans.factory.annotation.Autowired; 25 | import org.springframework.boot.test.context.SpringBootTest; 26 | import org.springframework.test.context.junit4.SpringRunner; 27 | 28 | /** 29 | *

Description:

30 | *

31 | *

Copyright (c) 2018

32 | * @Date 2019/9/18 10:27 33 | * @author biaoping.yin 34 | * @version 1.0 35 | */ 36 | @RunWith(SpringRunner.class) 37 | @SpringBootTest 38 | public class BulkProcessorTest { 39 | private Logger logger = LoggerFactory.getLogger(BulkProcessorTest.class); 40 | @Autowired 41 | private BBossESStarter bbossESStarter; 42 | @Autowired 43 | private TestBulkProcessor testBulkProcessor; 44 | @Test 45 | public void testBulkProcessor7x(){ 46 | testBulkProcessor.buildBulkProcessor(); 47 | testBulkProcessor.testBulkDatas(); 48 | 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/test/java/org/bboss/elasticsearchtest/springboot/MultiBBossES7StartersTestCase.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 1999-2018 Alibaba Group Holding Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.bboss.elasticsearchtest.springboot; 17 | 18 | 19 | import org.bboss.elasticsearchtest.springboot.crud.MultiES7DocumentCRUD; 20 | import org.frameworkset.elasticsearch.boot.BBossESStarter; 21 | import org.junit.Test; 22 | import org.junit.runner.RunWith; 23 | import org.springframework.beans.factory.annotation.Autowired; 24 | import org.springframework.beans.factory.annotation.Qualifier; 25 | import org.springframework.boot.test.context.SpringBootTest; 26 | import org.springframework.test.context.ActiveProfiles; 27 | import org.springframework.test.context.junit4.SpringRunner; 28 | 29 | /** 30 | * 多集群演示功能测试用例,spring boot配置项以spring.elasticsearch.bboss.集群名称开头,例如: 31 | * spring.elasticsearch.bboss.default 默认es集群 32 | * spring.elasticsearch.bboss.logs logs es集群 33 | * 两个集群通过 org.bboss.elasticsearchtest.springboot.MultiESSTartConfigurer加载 34 | * 对应的配置文件为application-multi-datasource.properties文件 35 | * @author yinbp [122054810@qq.com] 36 | */ 37 | @RunWith(SpringRunner.class) 38 | @SpringBootTest 39 | @ActiveProfiles("multi-datasource") 40 | public class MultiBBossES7StartersTestCase { 41 | @Autowired 42 | @Qualifier("bbossESStarterDefault") 43 | private BBossESStarter bbossESStarterDefault; 44 | @Autowired 45 | @Qualifier("bbossESStarterLogs") 46 | private BBossESStarter bbossESStarterLogs; 47 | 48 | @Autowired 49 | MultiES7DocumentCRUD multiESDocumentCRUD; 50 | @Test 51 | public void testMultiBBossESStarters() throws Exception { 52 | 53 | 54 | 55 | //获取logs对应的Elasticsearch集群客户端,判读索引是否存在,false表示不存在,正常返回true表示存在 56 | boolean exist = bbossESStarterDefault.getRestClient().existIndice("twitter"); 57 | System.out.println("logs twitter:"+exist); 58 | //获取logs对应的Elasticsearch集群客户端,判断索引是否定义 59 | exist = bbossESStarterDefault.getRestClient("logs").existIndice("agentinfo"); 60 | System.out.println("logs agentinfo:"+exist); 61 | } 62 | 63 | @Test 64 | public void testCRUD() throws Exception { 65 | 66 | //删除/创建文档索引表 67 | multiESDocumentCRUD.testCreateIndice(); 68 | //添加/修改单个文档 69 | 70 | multiESDocumentCRUD.testAddAndUpdateDocument(); 71 | //批量添加文档 72 | multiESDocumentCRUD.testBulkAddDocument(); 73 | //检索文档,测试指定数据源api,指定数据源default 74 | multiESDocumentCRUD.testSearch("default"); 75 | //批量修改文档 76 | multiESDocumentCRUD.testBulkUpdateDocument(); 77 | 78 | //检索批量修改后的文档,测试指定数据源api,指定数据源log 79 | multiESDocumentCRUD.testSearch("logs"); 80 | //带list复杂参数的文档检索操作 81 | multiESDocumentCRUD.testSearchArray(); 82 | //带from/size分页操作的文档检索操作 83 | multiESDocumentCRUD.testPagineSearch(); 84 | //带sourcefilter的文档检索操作 85 | multiESDocumentCRUD.testSearchSourceFilter(); 86 | 87 | multiESDocumentCRUD.updateDemoIndice(); 88 | multiESDocumentCRUD.testBulkAddDocuments(); 89 | } 90 | 91 | @Test 92 | public void testPerformaceCRUD() throws Exception { 93 | 94 | //删除/创建文档索引表 95 | multiESDocumentCRUD.testCreateIndice(); 96 | 97 | multiESDocumentCRUD.testBulkAddDocuments(); 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/test/java/org/bboss/elasticsearchtest/springboot/MultiBBossESStartersTestCase.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 1999-2018 Alibaba Group Holding Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.bboss.elasticsearchtest.springboot; 17 | 18 | 19 | import org.bboss.elasticsearchtest.springboot.crud.MultiESDocumentCRUD; 20 | import org.frameworkset.elasticsearch.boot.BBossESStarter; 21 | import org.junit.Test; 22 | import org.junit.runner.RunWith; 23 | import org.springframework.beans.factory.annotation.Autowired; 24 | import org.springframework.beans.factory.annotation.Qualifier; 25 | import org.springframework.boot.test.context.SpringBootTest; 26 | import org.springframework.test.context.ActiveProfiles; 27 | import org.springframework.test.context.junit4.SpringRunner; 28 | 29 | /** 30 | * 多集群演示功能测试用例,spring boot配置项以spring.elasticsearch.bboss.集群名称开头,例如: 31 | * spring.elasticsearch.bboss.default 默认es集群 32 | * spring.elasticsearch.bboss.logs logs es集群 33 | * 两个集群通过 org.bboss.elasticsearchtest.springboot.MultiESSTartConfigurer加载 34 | * 对应的配置文件为application-multi-datasource.properties文件 35 | * @author yinbp [122054810@qq.com] 36 | */ 37 | @RunWith(SpringRunner.class) 38 | @SpringBootTest 39 | @ActiveProfiles("multi-datasource") 40 | public class MultiBBossESStartersTestCase { 41 | @Autowired 42 | @Qualifier("bbossESStarterDefault") 43 | private BBossESStarter bbossESStarterDefault; 44 | @Autowired 45 | @Qualifier("bbossESStarterLogs") 46 | private BBossESStarter bbossESStarterLogs; 47 | @Autowired 48 | MultiESDocumentCRUD multiESDocumentCRUD; 49 | @Test 50 | public void testMultiBBossESStarters() throws Exception { 51 | 52 | //验证环境,获取es状态 53 | // String response = bbossESStarterDefault.getRestClient().executeHttp("_cluster/state?pretty",ClientInterface.HTTP_GET); 54 | // System.out.println(response); 55 | 56 | 57 | //判断索引类型是否存在,false表示不存在,正常返回true表示存在 58 | boolean exist = bbossESStarterDefault.getRestClient().existIndiceType("twitter","tweet"); 59 | System.out.println("default twitter/tweet:"+exist); 60 | //获取logs对应的Elasticsearch集群客户端,并进行existIndiceType操作 61 | exist = bbossESStarterDefault.getRestClient("logs").existIndiceType("twitter","tweet"); 62 | System.out.println("logs twitter/tweet:"+exist); 63 | //获取logs对应的Elasticsearch集群客户端,判读索引是否存在,false表示不存在,正常返回true表示存在 64 | exist = bbossESStarterDefault.getRestClient("logs").existIndice("twitter"); 65 | System.out.println("logs twitter:"+exist); 66 | //获取logs对应的Elasticsearch集群客户端,判断索引是否定义 67 | exist = bbossESStarterDefault.getRestClient("logs").existIndice("agentinfo"); 68 | System.out.println("logs agentinfo:"+exist); 69 | } 70 | 71 | @Test 72 | public void testCRUD() throws Exception { 73 | 74 | //删除/创建文档索引表 75 | multiESDocumentCRUD.testCreateIndice(); 76 | //添加/修改单个文档 77 | 78 | multiESDocumentCRUD.testAddAndUpdateDocument(); 79 | //批量添加文档 80 | multiESDocumentCRUD.testBulkAddDocument(); 81 | //检索文档 82 | multiESDocumentCRUD.testSearch(); 83 | //批量修改文档 84 | multiESDocumentCRUD.testBulkUpdateDocument(); 85 | 86 | //检索批量修改后的文档 87 | multiESDocumentCRUD.testSearch(); 88 | //带list复杂参数的文档检索操作 89 | multiESDocumentCRUD.testSearchArray(); 90 | //带from/size分页操作的文档检索操作 91 | multiESDocumentCRUD.testPagineSearch(); 92 | //带sourcefilter的文档检索操作 93 | multiESDocumentCRUD.testSearchSourceFilter(); 94 | 95 | multiESDocumentCRUD.updateDemoIndice(); 96 | multiESDocumentCRUD.testBulkAddDocuments(); 97 | } 98 | 99 | @Test 100 | public void testPerformaceCRUD() throws Exception { 101 | 102 | //删除/创建文档索引表 103 | multiESDocumentCRUD.testCreateIndice(); 104 | 105 | multiESDocumentCRUD.testBulkAddDocuments(); 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/test/java/org/bboss/elasticsearchtest/springboot/MultiES7RestClientTest.java: -------------------------------------------------------------------------------- 1 | package org.bboss.elasticsearchtest.springboot; 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.ActiveProfiles; 31 | import org.springframework.test.context.junit4.SpringRunner; 32 | 33 | import java.text.DateFormat; 34 | import java.text.ParseException; 35 | import java.text.SimpleDateFormat; 36 | import java.util.Date; 37 | import java.util.HashMap; 38 | import java.util.List; 39 | import java.util.Map; 40 | 41 | /** 42 | * 多集群演示功能测试用例,spring boot配置项以spring.elasticsearch.bboss.集群名称开头,例如: 43 | * spring.elasticsearch.bboss.default 默认es集群 44 | * spring.elasticsearch.bboss.logs logs es集群 45 | * 两个集群通过 org.bboss.elasticsearchtest.springboot.MultiESSTartConfigurer加载 46 | * 对应的配置文件为application-multi-datasource.properties文件 47 | */ 48 | @RunWith(SpringRunner.class) 49 | @SpringBootTest 50 | @ActiveProfiles("multi-datasource") 51 | public class MultiES7RestClientTest { 52 | private final Logger logger = LoggerFactory.getLogger(MultiES7RestClientTest.class); 53 | @Autowired 54 | private BBossESStarter bbossESStarterDefault; 55 | //DSL config file path 56 | private final String mappath = "esmapper/demo7.xml"; 57 | @Test 58 | public void testMultiBBossESStarters() throws Exception { 59 | 60 | //验证环境,获取es状态 61 | // String response = bbossESStarterDefaultDefault.getRestClient().executeHttp("_cluster/state?pretty",ClientInterface.HTTP_GET); 62 | // System.out.println(response); 63 | 64 | 65 | //判断索引类型是否存在,false表示不存在,正常返回true表示存在 66 | boolean exist = bbossESStarterDefault.getRestClient().existIndiceType("twitter","tweet"); 67 | System.out.println("default twitter/tweet:"+exist); 68 | //获取logs对应的Elasticsearch集群客户端,并进行existIndiceType操作 69 | exist = bbossESStarterDefault.getRestClient("logs").existIndiceType("twitter","tweet"); 70 | System.out.println("logs twitter/tweet:"+exist); 71 | //获取logs对应的Elasticsearch集群客户端,判读索引是否存在,false表示不存在,正常返回true表示存在 72 | exist = bbossESStarterDefault.getRestClient("logs").existIndice("twitter"); 73 | System.out.println("logs twitter:"+exist); 74 | //获取logs对应的Elasticsearch集群客户端,判断索引是否定义 75 | exist = bbossESStarterDefault.getRestClient("logs").existIndice("agentinfo"); 76 | System.out.println("logs agentinfo:"+exist); 77 | } 78 | @Test 79 | public void test(){ 80 | this.dropAndCreateAndGetIndice(); 81 | addAndUpdateDocument(); 82 | searchAllPararrel(); 83 | this.search(); 84 | this.deleteDocuments(); 85 | } 86 | public void dropAndCreateAndGetIndice(){ 87 | //Create a client tool to load configuration files, single instance multithreaded security 88 | ClientInterface clientUtil = bbossESStarterDefault.getConfigRestClient("default",mappath); 89 | try { 90 | //To determine whether the indice demo exists, it returns true if it exists and false if it does not 91 | boolean exist = clientUtil.existIndice("demo"); 92 | 93 | //Delete mapping if the indice demo already exists 94 | if(exist) { 95 | String r = clientUtil.dropIndice("demo"); 96 | logger.debug("clientUtil.dropIndice(\"demo\") response:"+r); 97 | 98 | } 99 | //Create index demo 100 | clientUtil.createIndiceMapping("demo",//The indice name 101 | "createDemoIndice");//Index mapping DSL script name, defined createDemoIndice in esmapper/demo.xml 102 | 103 | String demoIndice = clientUtil.getIndice("demo");//Gets the newly created indice structure 104 | logger.info("after createIndiceMapping clientUtil.getIndice(\"demo\") response:"+demoIndice); 105 | } catch (ElasticSearchException e) { 106 | // TODO Auto-generated catch block 107 | e.printStackTrace(); 108 | } 109 | 110 | } 111 | 112 | 113 | 114 | public void addAndUpdateDocument() { 115 | //Build a create/modify/get/delete document client object, single instance multi-thread security 116 | ClientInterface clientUtil = bbossESStarterDefault.getRestClient(); 117 | //Build an object as index document 118 | Demo demo = new Demo(); 119 | 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 120 | demo.setAgentStarttime(new Date()); 121 | demo.setApplicationName("blackcatdemo2"); 122 | demo.setContentbody("this is content body2"); 123 | demo.setName("liudehua"); 124 | demo.setOrderId("NFZF15045871807281445364228"); 125 | demo.setContrastStatus(2); 126 | 127 | 128 | //Add the document and force refresh 129 | String response = clientUtil.addDocument("demo",//indice name 130 | demo,"refresh=true"); 131 | 132 | 133 | 134 | logger.debug("Print the result:addDocument-------------------------"); 135 | logger.debug(response); 136 | 137 | demo = new Demo(); 138 | 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 139 | demo.setAgentStarttime(new Date()); 140 | demo.setApplicationName("blackcatdemo3"); 141 | demo.setContentbody("this is content body3"); 142 | demo.setName("zhangxueyou"); 143 | demo.setOrderId("NFZF15045871807281445364228"); 144 | demo.setContrastStatus(3); 145 | demo.setAgentStarttime(new Date()); 146 | 147 | //Add the document and force refresh 148 | response = clientUtil.addDocument("demo",//indice name 149 | demo,"refresh=true"); 150 | 151 | //Get the document object according to the document id, and return the Demo object 152 | demo = clientUtil.getDocument("demo",//indice name 153 | "2",//document id 154 | Demo.class); 155 | 156 | //update document 157 | demo = new Demo(); 158 | 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 159 | demo.setAgentStarttime(new Date()); 160 | demo.setApplicationName("blackcatdemo2"); 161 | demo.setContentbody("this is modify content body2"); 162 | demo.setName("刘德华modify\t"); 163 | demo.setOrderId("NFZF15045871807281445364228"); 164 | demo.setContrastStatus(2); 165 | //Execute update and force refresh 166 | response = clientUtil.addDocument("demo",//index name 167 | demo,"refresh=true"); 168 | 169 | 170 | //Get the modified document object according to the document id and return the json message string 171 | response = clientUtil.getDocument("demo",//indice name 172 | "2");//document id 173 | logger.debug("Print the modified result:getDocument-------------------------"); 174 | logger.debug(response); 175 | 176 | 177 | 178 | 179 | logger.debug("Print the modified result:getDocument-------------------------"); 180 | logger.debug(response); 181 | 182 | 183 | } 184 | 185 | public void deleteDocuments(){ 186 | //Build a create/modify/get/delete document client object, single instance multi-thread security 187 | ClientInterface clientUtil = bbossESStarterDefault.getRestClient(); 188 | //Batch delete documents 189 | clientUtil.deleteDocuments("demo",//indice name 190 | new String[]{"2","3"});//Batch delete document ids 191 | } 192 | 193 | /** 194 | * Use slice parallel scoll query all documents of indice demo by 2 thread tasks. DEFAULT_FETCHSIZE is 5000 195 | */ 196 | public void searchAllPararrel(){ 197 | ClientInterface clientUtil = bbossESStarterDefault.getRestClient(); 198 | ESDatas esDatas = clientUtil.searchAllParallel("demo", Demo.class,2); 199 | } 200 | 201 | 202 | 203 | /** 204 | * Search the documents 205 | */ 206 | public DemoSearchResult search() { 207 | //Create a load DSL file client instance to retrieve documents, single instance multithread security 208 | ClientInterface clientUtil = bbossESStarterDefault.getConfigRestClient(mappath); 209 | //Set query conditions, pass variable parameter values via map,key for variable names in DSL 210 | //There are four variables in the DSL: 211 | // applicationName1 212 | // applicationName2 213 | // startTime 214 | // endTime 215 | Map params = new HashMap(); 216 | //Set the values of applicationName1 and applicationName2 variables 217 | params.put("applicationName1","blackcatdemo2"); 218 | params.put("applicationName2","blackcatdemo3"); 219 | DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 220 | //Set the time range, and accept the long value as the time parameter 221 | try { 222 | params.put("startTime",dateFormat.parse("2017-09-02 00:00:00").getTime()); 223 | } catch (ParseException e) { 224 | e.printStackTrace(); 225 | } 226 | params.put("endTime",new Date().getTime()); 227 | 228 | 229 | //Execute the query 230 | ESDatas esDatas = //ESDatas contains a collection of currently retrieved records, up to 1000 records, specified by the size attribute in the DSL 231 | clientUtil.searchList("demo/_search",//demo as the indice, _search as the search action 232 | "searchDatas",//DSL statement name defined in esmapper/demo.xml 233 | params,//Query parameters 234 | Demo.class);//Data object type Demo returned 235 | 236 | 237 | //Gets a list of result objects and returns max up to 1000 records (specified in DSL) 238 | List demos = esDatas.getDatas(); 239 | 240 | // String json = clientUtil.executeRequest("demo/_search",//demo as the index table, _search as the search action 241 | // "searchDatas",//DSL statement name defined in esmapper/demo.xml 242 | // params);//Query parameters 243 | 244 | // String json = com.frameworkset.util.SimpleStringUtil.object2json(demos); 245 | //Gets the total number of records 246 | long totalSize = esDatas.getTotalSize(); 247 | DemoSearchResult demoSearchResult = new DemoSearchResult(); 248 | demoSearchResult.setDemos(demos); 249 | demoSearchResult.setTotalSize(totalSize); 250 | return demoSearchResult; 251 | } 252 | } 253 | -------------------------------------------------------------------------------- /src/test/java/org/bboss/elasticsearchtest/springboot/MultiESRestClientTest.java: -------------------------------------------------------------------------------- 1 | package org.bboss.elasticsearchtest.springboot; 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.ActiveProfiles; 31 | import org.springframework.test.context.junit4.SpringRunner; 32 | 33 | import java.text.DateFormat; 34 | import java.text.ParseException; 35 | import java.text.SimpleDateFormat; 36 | import java.util.Date; 37 | import java.util.HashMap; 38 | import java.util.List; 39 | import java.util.Map; 40 | 41 | /** 42 | * 多集群演示功能测试用例,spring boot配置项以spring.elasticsearch.bboss.集群名称开头,例如: 43 | * spring.elasticsearch.bboss.default 默认es集群 44 | * spring.elasticsearch.bboss.logs logs es集群 45 | * 两个集群通过 org.bboss.elasticsearchtest.springboot.MultiESSTartConfigurer加载 46 | * 对应的配置文件为application-multi-datasource.properties文件 47 | */ 48 | @RunWith(SpringRunner.class) 49 | @SpringBootTest 50 | @ActiveProfiles("multi-datasource") 51 | public class MultiESRestClientTest { 52 | private Logger logger = LoggerFactory.getLogger(MultiESRestClientTest.class); 53 | @Autowired 54 | private BBossESStarter bbossESStarterDefault; 55 | //DSL config file path 56 | private String mappath = "esmapper/demo.xml"; 57 | @Test 58 | public void testMultiBBossESStarters() throws Exception { 59 | 60 | //验证环境,获取es状态 61 | // String response = bbossESStarterDefaultDefault.getRestClient().executeHttp("_cluster/state?pretty",ClientInterface.HTTP_GET); 62 | // System.out.println(response); 63 | 64 | 65 | //判断索引类型是否存在,false表示不存在,正常返回true表示存在 66 | boolean exist = bbossESStarterDefault.getRestClient().existIndiceType("twitter","tweet"); 67 | System.out.println("default twitter/tweet:"+exist); 68 | //获取logs对应的Elasticsearch集群客户端,并进行existIndiceType操作 69 | exist = bbossESStarterDefault.getRestClient("logs").existIndiceType("twitter","tweet"); 70 | System.out.println("logs twitter/tweet:"+exist); 71 | //获取logs对应的Elasticsearch集群客户端,判读索引是否存在,false表示不存在,正常返回true表示存在 72 | exist = bbossESStarterDefault.getRestClient("logs").existIndice("twitter"); 73 | System.out.println("logs twitter:"+exist); 74 | //获取logs对应的Elasticsearch集群客户端,判断索引是否定义 75 | exist = bbossESStarterDefault.getRestClient("logs").existIndice("agentinfo"); 76 | System.out.println("logs agentinfo:"+exist); 77 | } 78 | @Test 79 | public void test(){ 80 | this.dropAndCreateAndGetIndice(); 81 | addAndUpdateDocument(); 82 | searchAllPararrel(); 83 | this.search(); 84 | this.deleteDocuments(); 85 | } 86 | public void dropAndCreateAndGetIndice(){ 87 | //Create a client tool to load configuration files, single instance multithreaded security 88 | ClientInterface clientUtil = bbossESStarterDefault.getConfigRestClient(mappath); 89 | try { 90 | //To determine whether the indice demo exists, it returns true if it exists and false if it does not 91 | boolean exist = clientUtil.existIndice("demo"); 92 | 93 | //Delete mapping if the indice demo already exists 94 | if(exist) { 95 | String r = clientUtil.dropIndice("demo"); 96 | logger.debug("clientUtil.dropIndice(\"demo\") response:"+r); 97 | 98 | } 99 | //Create index demo 100 | clientUtil.createIndiceMapping("demo",//The indice name 101 | "createDemoIndice");//Index mapping DSL script name, defined createDemoIndice in esmapper/demo.xml 102 | 103 | String demoIndice = clientUtil.getIndice("demo");//Gets the newly created indice structure 104 | logger.info("after createIndiceMapping clientUtil.getIndice(\"demo\") response:"+demoIndice); 105 | } catch (ElasticSearchException e) { 106 | // TODO Auto-generated catch block 107 | e.printStackTrace(); 108 | } 109 | 110 | } 111 | 112 | 113 | 114 | public void addAndUpdateDocument() { 115 | //Build a create/modify/get/delete document client object, single instance multi-thread security 116 | ClientInterface clientUtil = bbossESStarterDefault.getRestClient(); 117 | //Build an object as index document 118 | Demo demo = new Demo(); 119 | 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 120 | demo.setAgentStarttime(new Date()); 121 | demo.setAgentStarttimezh(new Date()); 122 | demo.setApplicationName("blackcatdemo2"); 123 | demo.setContentbody("this is content body2"); 124 | demo.setName("liudehua"); 125 | demo.setOrderId("NFZF15045871807281445364228"); 126 | demo.setContrastStatus(2); 127 | 128 | 129 | //Add the document and force refresh 130 | String response = clientUtil.addDocument("demo",//indice name 131 | "demo",//idnex type 132 | demo,"refresh=true"); 133 | 134 | 135 | 136 | logger.debug("Print the result:addDocument-------------------------"); 137 | logger.debug(response); 138 | 139 | demo = new Demo(); 140 | 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 141 | demo.setAgentStarttime(new Date()); 142 | demo.setApplicationName("blackcatdemo3"); 143 | demo.setContentbody("this is content body3"); 144 | demo.setName("zhangxueyou"); 145 | demo.setOrderId("NFZF15045871807281445364228"); 146 | demo.setContrastStatus(3); 147 | demo.setAgentStarttime(new Date()); 148 | demo.setAgentStarttimezh(new Date()); 149 | 150 | //Add the document and force refresh 151 | response = clientUtil.addDocument("demo",//indice name 152 | "demo",//idnex type 153 | demo,"refresh=true"); 154 | 155 | //Get the document object according to the document id, and return the Demo object 156 | demo = clientUtil.getDocument("demo",//indice name 157 | "demo",//idnex type 158 | "2",//document id 159 | Demo.class); 160 | 161 | //update document 162 | demo = new Demo(); 163 | 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 164 | demo.setAgentStarttime(new Date()); 165 | demo.setApplicationName("blackcatdemo2"); 166 | demo.setContentbody("this is modify content body2"); 167 | demo.setName("刘德华modify\t"); 168 | demo.setOrderId("NFZF15045871807281445364228"); 169 | demo.setContrastStatus(2); 170 | demo.setAgentStarttimezh(new Date()); 171 | //Execute update and force refresh 172 | response = clientUtil.addDocument("demo",//index name 173 | "demo",//idnex type 174 | demo,"refresh=true"); 175 | 176 | 177 | //Get the modified document object according to the document id and return the json message string 178 | response = clientUtil.getDocument("demo",//indice name 179 | "demo",//idnex type 180 | "2");//document id 181 | logger.debug("Print the modified result:getDocument-------------------------"); 182 | logger.debug(response); 183 | 184 | 185 | 186 | 187 | logger.debug("Print the modified result:getDocument-------------------------"); 188 | logger.debug(response); 189 | 190 | 191 | } 192 | 193 | public void deleteDocuments(){ 194 | //Build a create/modify/get/delete document client object, single instance multi-thread security 195 | ClientInterface clientUtil = bbossESStarterDefault.getRestClient(); 196 | //Batch delete documents 197 | clientUtil.deleteDocuments("demo",//indice name 198 | "demo",//idnex type 199 | new String[]{"2","3"});//Batch delete document ids 200 | } 201 | 202 | /** 203 | * Use slice parallel scoll query all documents of indice demo by 2 thread tasks. DEFAULT_FETCHSIZE is 5000 204 | */ 205 | public void searchAllPararrel(){ 206 | ClientInterface clientUtil = bbossESStarterDefault.getRestClient(); 207 | ESDatas esDatas = clientUtil.searchAllParallel("demo", Demo.class,2); 208 | } 209 | 210 | 211 | 212 | /** 213 | * Search the documents 214 | */ 215 | public DemoSearchResult search() { 216 | //Create a load DSL file client instance to retrieve documents, single instance multithread security 217 | ClientInterface clientUtil = bbossESStarterDefault.getConfigRestClient(mappath); 218 | //Set query conditions, pass variable parameter values via map,key for variable names in DSL 219 | //There are four variables in the DSL: 220 | // applicationName1 221 | // applicationName2 222 | // startTime 223 | // endTime 224 | Map params = new HashMap(); 225 | //Set the values of applicationName1 and applicationName2 variables 226 | params.put("applicationName1","blackcatdemo2"); 227 | params.put("applicationName2","blackcatdemo3"); 228 | DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 229 | //Set the time range, and accept the long value as the time parameter 230 | try { 231 | params.put("startTime",dateFormat.parse("2017-09-02 00:00:00").getTime()); 232 | } catch (ParseException e) { 233 | e.printStackTrace(); 234 | } 235 | params.put("endTime",new Date().getTime()); 236 | 237 | 238 | //Execute the query 239 | ESDatas esDatas = //ESDatas contains a collection of currently retrieved records, up to 1000 records, specified by the size attribute in the DSL 240 | clientUtil.searchList("demo/_search",//demo as the indice, _search as the search action 241 | "searchDatas",//DSL statement name defined in esmapper/demo.xml 242 | params,//Query parameters 243 | Demo.class);//Data object type Demo returned 244 | 245 | 246 | //Gets a list of result objects and returns max up to 1000 records (specified in DSL) 247 | List demos = esDatas.getDatas(); 248 | 249 | // String json = clientUtil.executeRequest("demo/_search",//demo as the index table, _search as the search action 250 | // "searchDatas",//DSL statement name defined in esmapper/demo.xml 251 | // params);//Query parameters 252 | 253 | // String json = com.frameworkset.util.SimpleStringUtil.object2json(demos); 254 | //Gets the total number of records 255 | long totalSize = esDatas.getTotalSize(); 256 | DemoSearchResult demoSearchResult = new DemoSearchResult(); 257 | demoSearchResult.setDemos(demos); 258 | demoSearchResult.setTotalSize(totalSize); 259 | return demoSearchResult; 260 | } 261 | } 262 | -------------------------------------------------------------------------------- /src/test/java/org/bboss/elasticsearchtest/springboot/RestClient7Test.java: -------------------------------------------------------------------------------- 1 | package org.bboss.elasticsearchtest.springboot; 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.frameworkset.elasticsearch.scroll.HandlerInfo; 25 | import org.frameworkset.elasticsearch.scroll.ScrollHandler; 26 | import org.junit.Test; 27 | import org.junit.runner.RunWith; 28 | import org.slf4j.Logger; 29 | import org.slf4j.LoggerFactory; 30 | import org.springframework.beans.factory.annotation.Autowired; 31 | import org.springframework.boot.test.context.SpringBootTest; 32 | import org.springframework.test.context.junit4.SpringRunner; 33 | 34 | import java.text.DateFormat; 35 | import java.text.ParseException; 36 | import java.text.SimpleDateFormat; 37 | import java.util.Date; 38 | import java.util.HashMap; 39 | import java.util.List; 40 | import java.util.Map; 41 | 42 | /** 43 | *

Description:

44 | *

45 | *

Copyright (c) 2018

46 | * @Date 2019/9/18 10:27 47 | * @author biaoping.yin 48 | * @version 1.0 49 | */ 50 | @RunWith(SpringRunner.class) 51 | @SpringBootTest 52 | public class RestClient7Test { 53 | private Logger logger = LoggerFactory.getLogger(RestClient7Test.class); 54 | @Autowired 55 | private BBossESStarter bbossESStarter; 56 | //DSL config file path 57 | private String mappath = "esmapper/demo7.xml"; 58 | @Test 59 | public void testException(){ 60 | ClientInterface clientUtil = bbossESStarter.getRestClient(); 61 | try { 62 | clientUtil.getDocument("demo", (String) null); 63 | } 64 | catch (Exception e){ 65 | e.printStackTrace(); 66 | } 67 | } 68 | 69 | @Test 70 | public void testException1(){ 71 | ClientInterface clientUtil = bbossESStarter.getRestClient(); 72 | 73 | try { 74 | clientUtil.getDocument("demo",""); 75 | } 76 | catch (Exception e){ 77 | e.printStackTrace(); 78 | } 79 | } 80 | /** 81 | * 并行方式执行slice scroll操作:将一个es的数据导入另外一个es数据,需要在application.properties文件中定义default和es233的两个集群 82 | */ 83 | @Test 84 | public void testSimpleSliceScrollApiParralHandlerExportDsl() { 85 | ClientInterface clientUtil522 = bbossESStarter.getConfigRestClient("default","esmapper/scroll.xml");//定义一个对应源集群default的客户端组件实例,并且加载配置了scrollSliceQuery dsl的xml配置文件 86 | 87 | final ClientInterface clientUtil234 = bbossESStarter.getRestClient("es233"); //定义一个对应目标集群es233的客户端组件实例 88 | //scroll slice分页检索,max对应并行度,与源表shards数一致即可 89 | int max = 6; 90 | Map params = new HashMap(); 91 | params.put("sliceMax", max);//最多6个slice,不能大于share数,必须使用sliceMax作为变量名称 92 | params.put("size", 5000);//每批5000条记录 93 | //采用自定义handler函数处理每个slice scroll的结果集后,sliceResponse中只会包含总记录数,不会包含记录集合 94 | //scroll上下文有效期1分钟,从源集群索引demo中查询数据 95 | ESDatas sliceResponse = clientUtil522.scrollSliceParallel("demo/_search", 96 | "scrollSliceQuery", params,"1m",Map.class, new ScrollHandler() { 97 | public void handle(ESDatas response, HandlerInfo handlerInfo) throws Exception {//自己处理每次scroll的结果,注意结果是异步检索的 98 | List datas = response.getDatas(); 99 | clientUtil234.addDocuments("index233","indextype233",datas); 100 | //将分批查询的数据导入目标集群索引index233,索引类型为indextype233,如果是elasticsearch 7以上的版本,可以去掉索引类型参数,例如: 101 | //clientUtil234.addDocuments("index233",datas); 102 | long totalSize = response.getTotalSize(); 103 | System.out.println("totalSize:"+totalSize+",datas.size:"+datas.size()); 104 | } 105 | }); 106 | 107 | long totalSize = sliceResponse.getTotalSize(); 108 | System.out.println("totalSize:"+totalSize); 109 | 110 | } 111 | /** 112 | * 并行方式执行slice scroll操作:将一个es的数据导入另外一个es数据,需要在application.properties文件中定义default和es233的两个集群 113 | */ 114 | @Test 115 | public void testSimpleSliceScrollApiParralHandlerExport() { 116 | ClientInterface clientUtil522 = bbossESStarter.getRestClient("default");//定义一个对应目标集群default的客户端组件实例 117 | 118 | final ClientInterface clientUtil234 = bbossESStarter.getRestClient("es233"); //定义一个对应源集群es233的客户端组件实例 119 | 120 | //从源集群索引demo中按每批10000笔记录查询数据,在handler中通过addDocuments将批量检索出的数据导入目标库 121 | ESDatas sliceResponse = clientUtil522.searchAllParallel("demo",10000, new ScrollHandler() { 122 | public void handle(ESDatas response, HandlerInfo handlerInfo) throws Exception {//自己处理每次scroll的结果,注意结果是异步检索的 123 | List datas = response.getDatas(); 124 | clientUtil234.addDocuments("index233","indextype233",datas); 125 | //将分批查询的数据导入目标集群索引index233,索引类型为indextype233,如果是elasticsearch 7以上的版本,可以去掉索引类型参数,例如: 126 | //clientUtil234.addDocuments("index233",datas); 127 | long totalSize = response.getTotalSize(); 128 | System.out.println("totalSize:"+totalSize+",datas.size:"+datas.size()); 129 | } 130 | },Map.class //指定检索的文档封装类型 131 | ,6);//6个工作线程并发导入 132 | 133 | long totalSize = sliceResponse.getTotalSize(); 134 | System.out.println("totalSize:"+totalSize); 135 | 136 | } 137 | @Test 138 | public void test(){ 139 | this.dropAndCreateAndGetIndice(); 140 | addAndUpdateDocument(); 141 | searchAllPararrel(); 142 | this.search(); 143 | this.deleteDocuments(); 144 | } 145 | public void dropAndCreateAndGetIndice(){ 146 | //Create a client tool to load configuration files, single instance multithreaded security 147 | ClientInterface clientUtil = bbossESStarter.getConfigRestClient(mappath); 148 | try { 149 | //To determine whether the indice demo exists, it returns true if it exists and false if it does not 150 | boolean exist = clientUtil.existIndice("demo"); 151 | 152 | //Delete mapping if the indice demo already exists 153 | if(exist) { 154 | String r = clientUtil.dropIndice("demo"); 155 | logger.debug("clientUtil.dropIndice(\"demo\") response:"+r); 156 | 157 | } 158 | //Create index demo 159 | clientUtil.createIndiceMapping("demo",//The indice name 160 | "createDemoIndice");//Index mapping DSL script name, defined createDemoIndice in esmapper/demo.xml 161 | 162 | String demoIndice = clientUtil.getIndice("demo");//Gets the newly created indice structure 163 | logger.info("after createIndiceMapping clientUtil.getIndice(\"demo\") response:"+demoIndice); 164 | } catch (ElasticSearchException e) { 165 | // TODO Auto-generated catch block 166 | e.printStackTrace(); 167 | } 168 | 169 | } 170 | 171 | 172 | 173 | public void addAndUpdateDocument() { 174 | //Build a create/modify/get/delete document client object, single instance multi-thread security 175 | ClientInterface clientUtil = bbossESStarter.getRestClient(); 176 | //Build an object as index document 177 | Demo demo = new Demo(); 178 | 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 179 | demo.setAgentStarttime(new Date()); 180 | demo.setApplicationName("blackcatdemo2"); 181 | demo.setContentbody("this is content body2"); 182 | demo.setName("liudehua"); 183 | demo.setOrderId("NFZF15045871807281445364228"); 184 | demo.setContrastStatus(2); 185 | 186 | 187 | //Add the document and force refresh 188 | String response = clientUtil.addDocument("demo",//indice name 189 | demo,"refresh=true"); 190 | 191 | 192 | 193 | logger.debug("Print the result:addDocument-------------------------"); 194 | logger.debug(response); 195 | 196 | demo = new Demo(); 197 | 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 198 | demo.setAgentStarttime(new Date()); 199 | demo.setApplicationName("blackcatdemo3"); 200 | demo.setContentbody("this is content body3"); 201 | demo.setName("zhangxueyou"); 202 | demo.setOrderId("NFZF15045871807281445364228"); 203 | demo.setContrastStatus(3); 204 | demo.setAgentStarttime(new Date()); 205 | demo.setAgentStarttimezh(new Date()); 206 | 207 | //Add the document and force refresh 208 | response = clientUtil.addDocument("demo",//indice name 209 | demo,"refresh=true"); 210 | 211 | //Get the document object according to the document id, and return the Demo object 212 | demo = clientUtil.getDocument("demo",//indice name 213 | "2",//document id 214 | Demo.class); 215 | 216 | //update document 217 | demo = new Demo(); 218 | 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 219 | demo.setAgentStarttime(new Date()); 220 | demo.setApplicationName("blackcatdemo2"); 221 | demo.setContentbody("this is modify content body2"); 222 | demo.setName("刘德华modify\t"); 223 | demo.setOrderId("NFZF15045871807281445364228"); 224 | demo.setContrastStatus(2); 225 | demo.setAgentStarttimezh(new Date()); 226 | //Execute update and force refresh 227 | response = clientUtil.addDocument("demo",//index name 228 | demo,"refresh=true"); 229 | 230 | 231 | //Get the modified document object according to the document id and return the json message string 232 | response = clientUtil.getDocument("demo",//indice name 233 | "2");//document id 234 | logger.debug("Print the modified result:getDocument-------------------------"); 235 | logger.debug(response); 236 | 237 | 238 | 239 | 240 | logger.debug("Print the modified result:getDocument-------------------------"); 241 | logger.debug(response); 242 | 243 | 244 | } 245 | 246 | public void deleteDocuments(){ 247 | //Build a create/modify/get/delete document client object, single instance multi-thread security 248 | ClientInterface clientUtil = bbossESStarter.getRestClient(); 249 | //Batch delete documents 250 | clientUtil.deleteDocuments("demo",//indice name 251 | new String[]{"2","3"});//Batch delete document ids 252 | } 253 | 254 | /** 255 | * Use slice parallel scoll query all documents of indice demo by 2 thread tasks. DEFAULT_FETCHSIZE is 5000 256 | */ 257 | public void searchAllPararrel(){ 258 | ClientInterface clientUtil = bbossESStarter.getRestClient(); 259 | ESDatas esDatas = clientUtil.searchAllParallel("demo", Demo.class,2); 260 | } 261 | 262 | 263 | 264 | /** 265 | * Search the documents 266 | */ 267 | public DemoSearchResult search() { 268 | //Create a load DSL file client instance to retrieve documents, single instance multithread security 269 | ClientInterface clientUtil = bbossESStarter.getConfigRestClient(mappath); 270 | //Set query conditions, pass variable parameter values via map,key for variable names in DSL 271 | //There are four variables in the DSL: 272 | // applicationName1 273 | // applicationName2 274 | // startTime 275 | // endTime 276 | Map params = new HashMap(); 277 | //Set the values of applicationName1 and applicationName2 variables 278 | params.put("applicationName1","blackcatdemo2"); 279 | params.put("applicationName2","blackcatdemo3"); 280 | DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 281 | //Set the time range, and accept the long value as the time parameter 282 | try { 283 | params.put("startTime",dateFormat.parse("2017-09-02 00:00:00").getTime()); 284 | } catch (ParseException e) { 285 | e.printStackTrace(); 286 | } 287 | params.put("endTime",new Date().getTime()); 288 | 289 | 290 | //Execute the query 291 | ESDatas esDatas = //ESDatas contains a collection of currently retrieved records, up to 1000 records, specified by the size attribute in the DSL 292 | clientUtil.searchList("demo/_search",//demo as the indice, _search as the search action 293 | "searchDatas",//DSL statement name defined in esmapper/demo.xml 294 | params,//Query parameters 295 | Demo.class);//Data object type Demo returned 296 | 297 | 298 | //Gets a list of result objects and returns max up to 1000 records (specified in DSL) 299 | List demos = esDatas.getDatas(); 300 | 301 | // String json = clientUtil.executeRequest("demo/_search",//demo as the index table, _search as the search action 302 | // "searchDatas",//DSL statement name defined in esmapper/demo.xml 303 | // params);//Query parameters 304 | 305 | // String json = com.frameworkset.util.SimpleStringUtil.object2json(demos); 306 | //Gets the total number of records 307 | long totalSize = esDatas.getTotalSize(); 308 | DemoSearchResult demoSearchResult = new DemoSearchResult(); 309 | demoSearchResult.setDemos(demos); 310 | demoSearchResult.setTotalSize(totalSize); 311 | return demoSearchResult; 312 | } 313 | } 314 | -------------------------------------------------------------------------------- /src/test/java/org/bboss/elasticsearchtest/springboot/RestClientTest.java: -------------------------------------------------------------------------------- 1 | package org.bboss.elasticsearchtest.springboot; 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:

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/org/bboss/elasticsearchtest/springboot/ScriptImpl7Test.java: -------------------------------------------------------------------------------- 1 | package org.bboss.elasticsearchtest.springboot;/* 2 | * Copyright 2008 biaoping.yin 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import com.frameworkset.util.SimpleStringUtil; 18 | import org.bboss.elasticsearchtest.springboot.script.ScriptImpl7; 19 | import org.frameworkset.elasticsearch.serial.SerialUtil; 20 | import org.junit.Test; 21 | import org.junit.runner.RunWith; 22 | import org.springframework.beans.factory.annotation.Autowired; 23 | import org.springframework.boot.test.context.SpringBootTest; 24 | import org.springframework.test.context.junit4.SpringRunner; 25 | 26 | import java.util.HashMap; 27 | import java.util.Map; 28 | @RunWith(SpringRunner.class) 29 | @SpringBootTest 30 | public class ScriptImpl7Test { 31 | @Autowired 32 | private ScriptImpl7 script; 33 | @Test 34 | public void test(){ 35 | script.updateDocumentByScriptPath(); 36 | } 37 | 38 | @Test 39 | public void test1(){ 40 | script.updateDocumentByScriptQueryPath(); 41 | } 42 | 43 | public static void main(String[] args){ 44 | Map value = new HashMap(); 45 | value.put("aaa","\r\n\""); 46 | String _value = SerialUtil.object2json(value); 47 | value.put("aaa",_value); 48 | _value = SerialUtil.object2json(value); 49 | System.out.println(_value); 50 | value = SimpleStringUtil.json2Object(_value,HashMap.class); 51 | System.out.println(_value); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/test/java/org/bboss/elasticsearchtest/springboot/ScriptImplTest.java: -------------------------------------------------------------------------------- 1 | package org.bboss.elasticsearchtest.springboot;/* 2 | * Copyright 2008 biaoping.yin 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import com.frameworkset.util.SimpleStringUtil; 18 | import org.bboss.elasticsearchtest.springboot.script.ScriptImpl7; 19 | import org.frameworkset.elasticsearch.serial.SerialUtil; 20 | import org.junit.Test; 21 | import org.junit.runner.RunWith; 22 | import org.springframework.beans.factory.annotation.Autowired; 23 | import org.springframework.boot.test.context.SpringBootTest; 24 | import org.springframework.test.context.junit4.SpringRunner; 25 | 26 | import java.util.HashMap; 27 | import java.util.Map; 28 | @RunWith(SpringRunner.class) 29 | @SpringBootTest 30 | public class ScriptImplTest { 31 | @Autowired 32 | private ScriptImpl7 script; 33 | @Test 34 | public void test(){ 35 | script.updateDocumentByScriptPath(); 36 | } 37 | 38 | @Test 39 | public void test1(){ 40 | script.updateDocumentByScriptQueryPath(); 41 | } 42 | 43 | public static void main(String[] args){ 44 | Map value = new HashMap(); 45 | value.put("aaa","\r\n\""); 46 | String _value = SerialUtil.object2json(value); 47 | value.put("aaa",_value); 48 | _value = SerialUtil.object2json(value); 49 | System.out.println(_value); 50 | value = SimpleStringUtil.json2Object(_value,HashMap.class); 51 | System.out.println(_value); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/test/java/org/bboss/elasticsearchtest/springboot/SimpleBBossESStarterTestCase.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 1999-2018 Alibaba Group Holding Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.bboss.elasticsearchtest.springboot; 17 | 18 | 19 | import org.frameworkset.elasticsearch.boot.BBossESStarter; 20 | import org.frameworkset.elasticsearch.client.ClientInterface; 21 | import org.frameworkset.elasticsearch.entity.ESDatas; 22 | import org.frameworkset.elasticsearch.entity.MetaMap; 23 | import org.frameworkset.elasticsearch.entity.PitId; 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.util.ArrayList; 33 | import java.util.HashMap; 34 | import java.util.List; 35 | import java.util.Map; 36 | 37 | /** 38 | * 单集群演示功能测试用例,spring boot配置项以spring.elasticsearch.bboss开头 39 | * 对应的配置文件为application.properties文件 40 | * @author yinbp [122054810@qq.com] 41 | */ 42 | @RunWith(SpringRunner.class) 43 | @SpringBootTest 44 | public class SimpleBBossESStarterTestCase { 45 | private static Logger logger = LoggerFactory.getLogger(SimpleBBossESStarterTestCase.class); 46 | @Autowired 47 | private BBossESStarter bbossESStarter; 48 | 49 | 50 | @Test 51 | public void testBbossESStarter() throws Exception { 52 | // System.out.println(bbossESStarter); 53 | 54 | //验证环境,获取es状态 55 | // String response = serviceApiUtil.restClient().executeHttp("_cluster/state?pretty",ClientInterface.HTTP_GET); 56 | 57 | // System.out.println(response); 58 | //判断索引类型是否存在,false表示不存在,正常返回true表示存在 59 | boolean exist = bbossESStarter.getRestClient().existIndiceType("twitter","tweet"); 60 | 61 | //判读索引是否存在,false表示不存在,正常返回true表示存在 62 | exist = bbossESStarter.getRestClient().existIndice("twitter"); 63 | 64 | exist = bbossESStarter.getRestClient().existIndice("agentinfo"); 65 | 66 | } 67 | 68 | @Test 69 | public void testESSQLTranslate(){ 70 | ClientInterface clientUtil = bbossESStarter.getRestClient(); 71 | String dsl = //将sql转换为dsl 72 | clientUtil.executeHttp("/_sql/_explain",//sql请求 73 | "select operModule.keyword from dbdemo group by operModule.keyword ",ClientInterface.HTTP_POST);//返回的文档封装对象类型 74 | 75 | //获取总记录数 76 | System.out.println(dsl); 77 | } 78 | 79 | 80 | @Test 81 | public void testPitIdSearchAfter(){ 82 | ClientInterface clientUtil = bbossESStarter.getConfigRestClient("esmapper/demo7.xml"); 83 | //申请pitid 84 | PitId pitId = clientUtil.requestPitId("dbdemofull","1m"); 85 | logger.info("pitId.getId() {}",pitId.getId()); 86 | Map params = new HashMap(); 87 | params.put("size",100); 88 | params.put("user","admin"); 89 | String pid = pitId.getId(); 90 | 91 | String prePid = null; 92 | List pids = new ArrayList<>(); 93 | pids.add(pid); 94 | do { 95 | 96 | params.put("pid",pid); 97 | prePid = pid; 98 | ESDatas datas = clientUtil.searchList("/_search", "queryPidSearchAfter", params, MetaMap.class); 99 | pid = datas.getPitId(); 100 | pids.add(pid); 101 | List metaMaps = datas.getDatas(); 102 | if(metaMaps != null && metaMaps.size() > 0 ){ 103 | MetaMap metaMap = metaMaps.get(metaMaps.size() - 1); 104 | Object[] sort = metaMap.getSort(); 105 | params.put("timestamp",sort[0]); 106 | params.put("_shard_doc",sort[1]); 107 | } 108 | 109 | if(metaMaps.size() < 100){ 110 | //达到最后一页,分页查询结束 111 | break; 112 | } 113 | logger.info("datas.getPitId() {}", pid); 114 | // logger.info(clientUtil.deletePitId(prePid)); 115 | 116 | }while (true); 117 | String pre = null; 118 | for(int i =0 ; i < pids.size(); i ++){ 119 | if(pre == null) 120 | pre = pids.get(i); 121 | else{ 122 | System.out.println("pre:"+pre + "\r\n" + "now:"+pids.get(i) + "\r\n" + "now equals pre:"+pre.equals(pids.get(i)) ); 123 | pre = pids.get(i); 124 | } 125 | logger.info(clientUtil.deletePitId(pids.get(i))); 126 | } 127 | 128 | } 129 | 130 | 131 | } 132 | -------------------------------------------------------------------------------- /src/test/java/org/bboss/elasticsearchtest/springboot/thirddslcontainer/TestThirdDslContainer.java: -------------------------------------------------------------------------------- 1 | package org.bboss.elasticsearchtest.springboot.thirddslcontainer; 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.frameworkset.common.poolman.SQLExecutor; 19 | import com.frameworkset.common.poolman.util.SQLUtil; 20 | import org.frameworkset.elasticsearch.ElasticSearchHelper; 21 | import org.frameworkset.elasticsearch.boot.BBossESStarter; 22 | import org.frameworkset.elasticsearch.client.ClientInterface; 23 | import org.frameworkset.elasticsearch.template.*; 24 | import org.junit.Before; 25 | import org.junit.Test; 26 | import org.junit.runner.RunWith; 27 | import org.slf4j.Logger; 28 | import org.slf4j.LoggerFactory; 29 | import org.springframework.beans.factory.annotation.Autowired; 30 | import org.springframework.boot.test.context.SpringBootTest; 31 | import org.springframework.test.context.junit4.SpringRunner; 32 | 33 | import java.sql.SQLException; 34 | import java.text.ParseException; 35 | import java.util.HashMap; 36 | import java.util.List; 37 | import java.util.Map; 38 | 39 | /** 40 | *

Description: Example for elasticsearch 5,6

41 | *

42 | *

Copyright (c) 2018

43 | * @Date 2020/1/23 19:52 44 | * @author biaoping.yin 45 | * @version 1.0 46 | */ 47 | @RunWith(SpringRunner.class) 48 | @SpringBootTest 49 | public class TestThirdDslContainer { 50 | @Autowired 51 | private BBossESStarter bbossESStarter; 52 | private static Logger logger = LoggerFactory.getLogger(TestThirdDslContainer.class); 53 | @Before 54 | public void init() throws SQLException { 55 | /** 56 | * "org.sqlite.JDBC", 57 | * "jdbc:sqlite://" + dbpath.getCanonicalPath(), 58 | * "root", "root", 59 | * null,//"false", 60 | * null,// "READ_UNCOMMITTED", 61 | * "select 1", 62 | * dbJNDIName, 63 | * 10, 64 | * 10, 65 | * 20, 66 | * true, 67 | * false, 68 | * null, false, false 69 | */ 70 | //定义保存dsl的数据源testdslconfig 71 | SQLUtil.startPool("testdslconfig",//数据源名称 72 | "org.sqlite.JDBC", 73 | "jdbc:sqlite:testdslconfig" , 74 | "root", "root", 75 | null,//"false", 76 | null,// "READ_UNCOMMITTED", 77 | "select 1", 78 | "test-jndi", 79 | 10, 80 | 10, 81 | 20, 82 | true, 83 | false, 84 | null, true, false 85 | ); 86 | 87 | //在sqlite数据源testdslconfig中创建保存dsl语句的数据库表dslconfig 88 | String createStatusTableSQL = new StringBuilder() 89 | .append("create table dslconfig (ID string,name string,namespace string,dslTemplate TEXT,vtpl number(1),multiparser number(1) ") 90 | .append(",referenceNamespace string,referenceTemplateName string,PRIMARY KEY (ID))").toString(); 91 | 92 | try { 93 | String exist = "select 1 from dslconfig"; 94 | //SQLExecutor.updateWithDBName("gencode","drop table BBOSS_GENCODE"); 95 | 96 | SQLExecutor.queryObjectWithDBName(int.class,"testdslconfig", exist); 97 | logger.info("重建建dslconfig表:"+createStatusTableSQL+"。"); 98 | SQLExecutor.updateWithDBName("testdslconfig","drop table dslconfig"); 99 | SQLExecutor.updateWithDBName("testdslconfig",createStatusTableSQL); 100 | logger.info("重建建dslconfig表成功。"); 101 | } catch (Exception e) { 102 | 103 | logger.info("dslconfig table 不存在,创建dslconfig表:"+createStatusTableSQL+"。"); 104 | try { 105 | SQLExecutor.updateWithDBName("testdslconfig",createStatusTableSQL); 106 | logger.info("创建dslconfig表成功:"+createStatusTableSQL+"。"); 107 | } catch (SQLException e1) { 108 | logger.info("创建dslconfig表失败:"+createStatusTableSQL+"。",e1); 109 | e1.printStackTrace(); 110 | } 111 | } 112 | 113 | //初始化dsl配置:将配置文件中的sql转存到数据库中 114 | String dslpath = "esmapper/demo.xml"; 115 | final String namespace = "testnamespace";//一个命名空间的dsl可以对应为一个ClientInterface实例 116 | AOPTemplateContainerImpl aopTemplateContainer = ElasticSearchHelper.getAOPTemplateContainerImpl(dslpath); 117 | int perKeyDSLStructionCacheSize = aopTemplateContainer.getPerKeyDSLStructionCacheSize(); 118 | boolean alwaysCacheDslStruction = aopTemplateContainer.isAlwaysCacheDslStruction(); 119 | List templateMetaList = aopTemplateContainer.getTemplateMetas(namespace);//将demo.xml文件中配置的dsl转换为属于namespace命名空间的对象列表 120 | 121 | //保存dsl到表dslconfig 122 | SQLExecutor.insertBeans("testdslconfig", 123 | "insert into dslconfig(ID,name,namespace,dslTemplate,vtpl,multiparser,referenceNamespace,referenceTemplateName) " + 124 | "values(#[id]," + //主键 125 | "#[name]," + //dsl名称 126 | "#[namespace]," + //dsl所属命名空间 127 | "#[dslTemplate]," + //dsl语句 128 | "#[vtpl]," + //一般设置为true, dsl语句中是否包含velocity语法内容,包含为true,否则为false(避免进行velocity语法解析,提升性能),默认为true 129 | "#[multiparser]," + // 一般设置为true,dsl如果包含velocity动态语法,是否需要对每次动态生成的dsl进行模板变量#[xxxx]语法解析,true 需要,false不需要,默认true 130 | "#[referenceNamespace]," + // 如果对应的配置是一个引用,则需要通过referenceNamespace指定引用的dsl所属的命名空间 131 | "#[referenceTemplateName])",// 如果对应的配置是一个引用,则需要通过referenceTemplateName指定引用的dsl对应的名称name 132 | templateMetaList); 133 | } 134 | @Test 135 | public void testThirdDslContainer(){ 136 | //创建一个从数据库加载命名空间为testnamespace的所有dsl语句的ClientInterface组件实例 137 | ClientInterface clientInterface = bbossESStarter.getConfigRestClient(new BaseTemplateContainerImpl("testnamespace") { 138 | @Override 139 | protected Map loadTemplateMetas(String namespace) { 140 | try { 141 | List templateMetas = SQLExecutor.queryListWithDBName(BaseTemplateMeta.class, 142 | "testdslconfig","select * from dslconfig where namespace = ?",namespace); 143 | if(templateMetas == null){ 144 | return null; 145 | } 146 | else{ 147 | Map templateMetaMap = new HashMap(templateMetas.size()); 148 | for(BaseTemplateMeta baseTemplateMeta: templateMetas){ 149 | templateMetaMap.put(baseTemplateMeta.getName(),baseTemplateMeta); 150 | } 151 | return templateMetaMap; 152 | } 153 | } catch (Exception e) { 154 | throw new DSLParserException(e); 155 | } 156 | } 157 | 158 | @Override 159 | protected long getLastModifyTime(String namespace) { 160 | // 获取dsl更新时间戳:模拟每次都更新,返回当前时间戳 161 | // 如果检测到时间戳有变化,框架就将调用loadTemplateMetas方法加载最新的dsl配置 162 | return System.currentTimeMillis(); 163 | } 164 | }); 165 | /** 166 | * 使用clientinterface操作elasticsearch 167 | */ 168 | try{ 169 | testHighlightSearch(clientInterface); 170 | } 171 | catch (Exception e){ 172 | logger.error("",e); 173 | } 174 | try{ 175 | testCRUD(clientInterface); 176 | } 177 | catch (Exception e){ 178 | logger.error("",e); 179 | } 180 | // 脚本和片段引用测试 181 | testScriptImpl( clientInterface); 182 | } 183 | private void testScriptImpl(ClientInterface clientInterface) { 184 | ScriptImpl scriptImpl = new ScriptImpl(clientInterface); 185 | scriptImpl.updateDocumentByScriptPath(); 186 | scriptImpl.updateDocumentByScriptQueryPath(); 187 | } 188 | private void testHighlightSearch(ClientInterface clientInterface) throws ParseException { 189 | HighlightSearch highlightSearch = new HighlightSearch(clientInterface); 190 | highlightSearch.initIndiceAndData(); 191 | highlightSearch.highlightSearch(); 192 | highlightSearch.highlightSearchOther(); 193 | } 194 | private void testCRUD(ClientInterface clientInterface) throws ParseException { 195 | DocumentCRUD documentCRUD = new DocumentCRUD(clientInterface); 196 | //删除/创建文档索引表 197 | documentCRUD.testCreateIndice(); 198 | //添加/修改单个文档 199 | documentCRUD.testAddAndUpdateDocument(); 200 | //批量添加文档 201 | documentCRUD.testBulkAddDocument(); 202 | //检索文档 203 | documentCRUD.testSearch(); 204 | //批量修改文档 205 | documentCRUD.testBulkUpdateDocument(); 206 | 207 | //检索批量修改后的文档 208 | documentCRUD.testSearch(); 209 | //带list复杂参数的文档检索操作 210 | documentCRUD.testSearchArray(); 211 | //带from/size分页操作的文档检索操作 212 | documentCRUD.testPagineSearch(); 213 | //带sourcefilter的文档检索操作 214 | documentCRUD.testSearchSourceFilter(); 215 | 216 | documentCRUD.updateDemoIndice(); 217 | documentCRUD.testBulkAddDocuments(); 218 | for(int i = 0; i < 10; i ++){ 219 | documentCRUD.testBulkAddUUIDDocuments(i,10); 220 | } 221 | } 222 | } 223 | -------------------------------------------------------------------------------- /src/test/java/org/bboss/elasticsearchtest/springboot/thirddslcontainer/TestThirdDslContainer7.java: -------------------------------------------------------------------------------- 1 | package org.bboss.elasticsearchtest.springboot.thirddslcontainer; 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.frameworkset.common.poolman.SQLExecutor; 19 | import com.frameworkset.common.poolman.util.SQLUtil; 20 | import org.frameworkset.elasticsearch.ElasticSearchHelper; 21 | import org.frameworkset.elasticsearch.boot.BBossESStarter; 22 | import org.frameworkset.elasticsearch.client.ClientInterface; 23 | import org.frameworkset.elasticsearch.template.*; 24 | import org.junit.Before; 25 | import org.junit.Test; 26 | import org.junit.runner.RunWith; 27 | import org.slf4j.Logger; 28 | import org.slf4j.LoggerFactory; 29 | import org.springframework.beans.factory.annotation.Autowired; 30 | import org.springframework.boot.test.context.SpringBootTest; 31 | import org.springframework.test.context.junit4.SpringRunner; 32 | 33 | import java.sql.SQLException; 34 | import java.text.ParseException; 35 | import java.util.HashMap; 36 | import java.util.List; 37 | import java.util.Map; 38 | 39 | /** 40 | *

Description: Example for elasticsearch 7

41 | *

42 | *

Copyright (c) 2018

43 | * @Date 2020/1/23 19:52 44 | * @author biaoping.yin 45 | * @version 1.0 46 | */ 47 | @RunWith(SpringRunner.class) 48 | @SpringBootTest 49 | public class TestThirdDslContainer7 { 50 | @Autowired 51 | private BBossESStarter bbossESStarter; 52 | private static Logger logger = LoggerFactory.getLogger(TestThirdDslContainer7.class); 53 | @Before 54 | public void init() throws SQLException { 55 | /** 56 | * "org.sqlite.JDBC", 57 | * "jdbc:sqlite://" + dbpath.getCanonicalPath(), 58 | * "root", "root", 59 | * null,//"false", 60 | * null,// "READ_UNCOMMITTED", 61 | * "select 1", 62 | * dbJNDIName, 63 | * 10, 64 | * 10, 65 | * 20, 66 | * true, 67 | * false, 68 | * null, false, false 69 | */ 70 | //定义保存dsl的数据源testdslconfig 71 | SQLUtil.startPool("testdslconfig",//数据源名称 72 | "org.sqlite.JDBC", 73 | "jdbc:sqlite:testdslconfig" , 74 | "root", "root", 75 | null,//"false", 76 | null,// "READ_UNCOMMITTED", 77 | "select 1", 78 | "test-jndi", 79 | 10, 80 | 10, 81 | 20, 82 | true, 83 | false, 84 | null, true, false 85 | ); 86 | 87 | //在sqlite数据源testdslconfig中创建保存dsl语句的数据库表dslconfig 88 | String createStatusTableSQL = new StringBuilder() 89 | .append("create table dslconfig (ID string,name string,namespace string,dslTemplate TEXT,vtpl number(1),multiparser number(1) ") 90 | .append(",referenceNamespace string,referenceTemplateName string,PRIMARY KEY (ID))").toString(); 91 | 92 | try { 93 | String exist = "select 1 from dslconfig"; 94 | //SQLExecutor.updateWithDBName("gencode","drop table BBOSS_GENCODE"); 95 | 96 | //测试看效果,通过重建表清空数据,也可以通过删除数据,演示达到效果即可(秀一把bboss的持久层功能) 97 | SQLExecutor.queryObjectWithDBName(int.class,"testdslconfig", exist); 98 | logger.info("重建建dslconfig表:"+createStatusTableSQL+"。"); 99 | SQLExecutor.updateWithDBName("testdslconfig","drop table dslconfig"); 100 | SQLExecutor.updateWithDBName("testdslconfig",createStatusTableSQL); 101 | logger.info("重建建dslconfig表成功。"); 102 | } catch (Exception e) { 103 | 104 | logger.info("dslconfig table 不存在,创建dslconfig表:"+createStatusTableSQL+"。"); 105 | try { 106 | SQLExecutor.updateWithDBName("testdslconfig",createStatusTableSQL); 107 | logger.info("创建dslconfig表成功:"+createStatusTableSQL+"。"); 108 | } catch (SQLException e1) { 109 | logger.info("创建dslconfig表失败:"+createStatusTableSQL+"。",e1); 110 | e1.printStackTrace(); 111 | } 112 | } 113 | 114 | //将配置文件中的sql转存到数据库中 115 | String dslpath = "esmapper/demo7.xml"; 116 | final String namespace = "testnamespace7";//一个命名空间的dsl可以对应为一个ClientInterface实例 117 | AOPTemplateContainerImpl aopTemplateContainer = ElasticSearchHelper.getAOPTemplateContainerImpl(dslpath); 118 | int perKeyDSLStructionCacheSize = aopTemplateContainer.getPerKeyDSLStructionCacheSize(); 119 | boolean alwaysCacheDslStruction = aopTemplateContainer.isAlwaysCacheDslStruction(); 120 | List templateMetaList = aopTemplateContainer.getTemplateMetas(namespace);//将demo.xml文件中配置的dsl转换为属于namespace命名空间的对象列表 121 | 122 | //保存dsl到表dslconfig 123 | SQLExecutor.insertBeans("testdslconfig", 124 | "insert into dslconfig(ID,name,namespace,dslTemplate,vtpl,multiparser,referenceNamespace,referenceTemplateName) " + 125 | "values(#[id]," + //主键 126 | "#[name]," + //dsl名称 127 | "#[namespace]," + //dsl所属命名空间 128 | "#[dslTemplate]," + //dsl语句 129 | "#[vtpl]," + //一般设置为true, dsl语句中是否包含velocity语法内容,包含为true,否则为false(避免进行velocity语法解析,提升性能),默认为true 130 | "#[multiparser]," + // 一般设置为true,dsl如果包含velocity动态语法,是否需要对每次动态生成的dsl进行模板变量#[xxxx]语法解析,true 需要,false不需要,默认true 131 | "#[referenceNamespace]," + // 如果对应的配置是一个引用,则需要通过referenceNamespace指定引用的dsl所属的命名空间 132 | "#[referenceTemplateName])",// 如果对应的配置是一个引用,则需要通过referenceTemplateName指定引用的dsl对应的名称name 133 | templateMetaList); 134 | } 135 | @Test 136 | public void testThirdDslContainer(){ 137 | //创建一个从数据库加载命名空间为clientInterface7的所有dsl语句的ClientInterface组件实例 138 | ClientInterface clientInterface = bbossESStarter.getConfigRestClient(new BaseTemplateContainerImpl("testnamespace7") { 139 | @Override 140 | protected Map loadTemplateMetas(String namespace) { 141 | try { 142 | List templateMetas = SQLExecutor.queryListWithDBName(BaseTemplateMeta.class,"testdslconfig","select * from dslconfig where namespace = ?",namespace); 143 | if(templateMetas == null){ 144 | return null; 145 | } 146 | else{ 147 | Map templateMetaMap = new HashMap(templateMetas.size()); 148 | for(BaseTemplateMeta baseTemplateMeta: templateMetas){ 149 | templateMetaMap.put(baseTemplateMeta.getName(),baseTemplateMeta); 150 | } 151 | return templateMetaMap; 152 | } 153 | } catch (Exception e) { 154 | throw new DSLParserException(e); 155 | } 156 | } 157 | 158 | @Override 159 | protected long getLastModifyTime(String namespace) { 160 | // 模拟每次都更新,返回当前时间戳 161 | return System.currentTimeMillis(); 162 | } 163 | }); 164 | try{ 165 | testHighlightSearch(clientInterface); 166 | } 167 | catch (Exception e){ 168 | logger.error("",e); 169 | } 170 | try{ 171 | testCRUD(clientInterface); 172 | } 173 | catch (Exception e){ 174 | logger.error("",e); 175 | } 176 | testScriptImpl( clientInterface); 177 | } 178 | 179 | private void testScriptImpl(ClientInterface clientInterface) { 180 | ScriptImpl7 scriptImpl7 = new ScriptImpl7(clientInterface); 181 | scriptImpl7.updateDocumentByScriptPath(); 182 | scriptImpl7.updateDocumentByScriptQueryPath(); 183 | } 184 | private void testHighlightSearch(ClientInterface clientInterface) throws ParseException { 185 | HighlightSearch7 highlightSearch = new HighlightSearch7(clientInterface); 186 | highlightSearch.initIndiceAndData(); 187 | highlightSearch.highlightSearch(); 188 | highlightSearch.highlightSearchOther(); 189 | } 190 | private void testCRUD(ClientInterface clientInterface) throws ParseException { 191 | DocumentCRUD7 documentCRUD = new DocumentCRUD7(clientInterface); 192 | //删除/创建文档索引表 193 | documentCRUD.testCreateIndice(); 194 | //添加/修改单个文档 195 | documentCRUD.testAddAndUpdateDocument(); 196 | //批量添加文档 197 | documentCRUD.testBulkAddDocument(); 198 | //检索文档 199 | documentCRUD.testSearch(); 200 | //批量修改文档 201 | documentCRUD.testBulkUpdateDocument(); 202 | 203 | //检索批量修改后的文档 204 | documentCRUD.testSearch(); 205 | //带list复杂参数的文档检索操作 206 | documentCRUD.testSearchArray(); 207 | //带from/size分页操作的文档检索操作 208 | documentCRUD.testPagineSearch(); 209 | //带sourcefilter的文档检索操作 210 | documentCRUD.testSearchSourceFilter(); 211 | 212 | documentCRUD.updateDemoIndice(); 213 | documentCRUD.testBulkAddDocuments(); 214 | for(int i = 0; i < 10; i ++){ 215 | documentCRUD.testBulkAddUUIDDocuments(i,10); 216 | } 217 | } 218 | } 219 | --------------------------------------------------------------------------------