├── elasticsearch-spring-boot-starter ├── src │ └── main │ │ └── resources │ │ └── META-INF │ │ └── spring.provides └── pom.xml ├── elasticsearch-spring-boot-autoconfigure ├── src │ └── main │ │ ├── resources │ │ └── META-INF │ │ │ └── spring.factories │ │ └── java │ │ └── com │ │ └── battcn │ │ └── boot │ │ └── elasticsearch │ │ ├── properties │ │ ├── ElasticsearchHttpClientProperties.java │ │ └── ElasticsearchRestClientProperties.java │ │ └── autoconfigure │ │ └── ElasticsearchRestAutoConfiguration.java └── pom.xml ├── samples └── elasticsearch-spring-boot-sample │ ├── src │ ├── main │ │ ├── java │ │ │ └── com │ │ │ │ └── battcn │ │ │ │ └── samples │ │ │ │ ├── entity │ │ │ │ └── Book.java │ │ │ │ ├── Application.java │ │ │ │ └── controller │ │ │ │ ├── IkPinYinPluginController.java │ │ │ │ └── BookController.java │ │ └── resources │ │ │ └── application.properties │ └── test │ │ └── java │ │ └── com │ │ └── test │ │ ├── ApplicationTests.java │ │ └── PluginTest.java │ └── pom.xml ├── .gitignore ├── README.md └── pom.xml /elasticsearch-spring-boot-starter/src/main/resources/META-INF/spring.provides: -------------------------------------------------------------------------------- 1 | provides: elasticsearch-spring-boot-autoconfigure,elasticsearch-rest-high-level-client,elasticsearch-rest-client,elasticsearch -------------------------------------------------------------------------------- /elasticsearch-spring-boot-autoconfigure/src/main/resources/META-INF/spring.factories: -------------------------------------------------------------------------------- 1 | # Auto Configure 2 | org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ 3 | com.battcn.boot.elasticsearch.autoconfigure.ElasticsearchRestAutoConfiguration 4 | -------------------------------------------------------------------------------- /samples/elasticsearch-spring-boot-sample/src/main/java/com/battcn/samples/entity/Book.java: -------------------------------------------------------------------------------- 1 | package com.battcn.samples.entity; 2 | 3 | import lombok.Data; 4 | 5 | import java.math.BigDecimal; 6 | 7 | /** 8 | * @author Levin 9 | */ 10 | @Data 11 | public class Book implements java.io.Serializable { 12 | 13 | private Long id; 14 | private String title; 15 | private BigDecimal price; 16 | 17 | 18 | } 19 | -------------------------------------------------------------------------------- /samples/elasticsearch-spring-boot-sample/src/test/java/com/test/ApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.test; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class ApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /samples/elasticsearch-spring-boot-sample/src/main/java/com/battcn/samples/Application.java: -------------------------------------------------------------------------------- 1 | package com.battcn.samples; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | /** 7 | * @author Levin 8 | */ 9 | @SpringBootApplication 10 | public class Application { 11 | 12 | 13 | public static void main(String[] args) { 14 | SpringApplication.run(Application.class, args); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | /target/ 3 | target 4 | !.mvn/wrapper/maven-wrapper.jar 5 | 6 | ### STS ### 7 | .apt_generated 8 | .classpath 9 | .factorypath 10 | .project 11 | .settings 12 | .springBeans 13 | .sts4-cache 14 | 15 | ### IntelliJ IDEA ### 16 | .idea 17 | *.iws 18 | *.iml 19 | *.ipr 20 | 21 | ### NetBeans ### 22 | /nbproject/private/ 23 | /nbbuild/ 24 | /dist/ 25 | /nbdist/ 26 | /.nb-gradle/ 27 | /build/ 28 | 29 | ### rebel ### 30 | .rebel.xml.bak 31 | .rebel-remote.xml.bak 32 | rebel-remote.xml 33 | rebel.xml 34 | *rebel* -------------------------------------------------------------------------------- /samples/elasticsearch-spring-boot-sample/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | #spring.redis.port=6380 2 | #spring.data.samples.cluster-name=samples 3 | #spring.data.samples.cluster-nodes=localhost:9200 4 | #spring.data.samples.repositories.enabled=true 5 | 6 | spring.swagger.base-package=com.battcn 7 | 8 | 9 | 10 | spring.elasticsearch.rest.cluster-name=elasticsearch 11 | spring.elasticsearch.rest.uris=http://localhost:9200 12 | 13 | spring.elasticsearch.rest.http-client.max-total=200 14 | spring.elasticsearch.rest.http-client.default-max-per-route=100 15 | spring.elasticsearch.rest.http-client.connect-timeout=10000 16 | spring.elasticsearch.rest.http-client.read-timeout=10000 17 | spring.elasticsearch.rest.http-client.connection-request-timeout=10000 -------------------------------------------------------------------------------- /elasticsearch-spring-boot-autoconfigure/src/main/java/com/battcn/boot/elasticsearch/properties/ElasticsearchHttpClientProperties.java: -------------------------------------------------------------------------------- 1 | package com.battcn.boot.elasticsearch.properties; 2 | 3 | import lombok.Data; 4 | import org.springframework.boot.context.properties.ConfigurationProperties; 5 | 6 | /** 7 | * @author Levin 8 | * @since 2019-07-03 9 | */ 10 | @Data 11 | @ConfigurationProperties(prefix = "spring.elasticsearch.rest.http-client") 12 | public class ElasticsearchHttpClientProperties { 13 | 14 | private Integer maxTotal; 15 | private Integer defaultMaxPerRoute; 16 | private Integer connectTimeout; 17 | private Integer readTimeout; 18 | private Integer connectionRequestTimeout; 19 | 20 | } 21 | -------------------------------------------------------------------------------- /elasticsearch-spring-boot-autoconfigure/src/main/java/com/battcn/boot/elasticsearch/properties/ElasticsearchRestClientProperties.java: -------------------------------------------------------------------------------- 1 | package com.battcn.boot.elasticsearch.properties; 2 | 3 | import lombok.Data; 4 | import org.springframework.boot.context.properties.ConfigurationProperties; 5 | 6 | import java.util.ArrayList; 7 | import java.util.Collections; 8 | import java.util.List; 9 | 10 | /** 11 | * @author Levin 12 | * @since 2019-07-03 13 | */ 14 | @Data 15 | @ConfigurationProperties(prefix = "spring.elasticsearch.rest") 16 | public class ElasticsearchRestClientProperties { 17 | 18 | /** 19 | * Elasticsearch cluster name. 20 | */ 21 | private String clusterName = "elasticsearch"; 22 | /** 23 | * Comma-separated list of the Elasticsearch instances to use. 24 | */ 25 | private List uris = new ArrayList<>(Collections.singletonList("http://localhost:9200")); 26 | 27 | /** 28 | * Credentials username. 29 | */ 30 | private String username; 31 | 32 | /** 33 | * Credentials password. 34 | */ 35 | private String password; 36 | 37 | public List getUris() { 38 | return this.uris; 39 | } 40 | 41 | 42 | } 43 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 简介 # 2 | 3 | 4 | > 源码地址 5 | 6 | - GitHub:[https://github.com/battcn/elasticsearch-spring-boot](https://github.com/battcn/elasticsearch-spring-boot "https://github.com/battcn/elasticsearch-spring-boot") 7 | - 码云:[https://gitee.com/battcn/elasticsearch-spring-boot/](https://gitee.com/battcn/elasticsearch-spring-boot/ "https://gitee.com/battcn/spring-boot-starter-swagger/") 8 | 9 | `elasticsearch-spring-boot-starter` 是一款建立在 `elasticsearch-rest-high-level-client` 基础之上的工具包 10 | 11 | > 项目介绍 12 | 13 | - **`elasticsearch-spring-boot-autoconfigure` :具体代码** 14 | - **`elasticsearch-spring-boot-starter` : 自动装配 elasticsearch 的扩展包** 15 | 16 | 17 | **如果该项目对您有帮助,欢迎 Fork 和 Star,有疑问可以加 `QQ:1837307557`一起交流 ,如发现项目BUG可以提交`Issue`** 18 | 19 | # 使用 # 20 | 21 | - 在`pom.xml`中引入依赖: 22 | 23 | ``` xml 24 | 25 | 1.8 26 | 27 | 7.1.1 28 | 29 | 30 | 31 | com.battcn 32 | elasticsearch-spring-boot-starter 33 | 1.0.1.RELEASE 34 | 35 | ``` 36 | 37 | 38 | ### properties ### 39 | 40 | 41 | ``` 42 | spring.elasticsearch.rest.cluster-name=elasticsearch 43 | spring.elasticsearch.rest.uris=http://localhost:9200 44 | spring.elasticsearch.rest.http-client.max-total=200 45 | spring.elasticsearch.rest.http-client.default-max-per-route=100 46 | spring.elasticsearch.rest.http-client.connect-timeout=10000 47 | spring.elasticsearch.rest.http-client.read-timeout=10000 48 | spring.elasticsearch.rest.http-client.connection-request-timeout=10000 49 | ``` 50 | 51 | 52 | # 贡献者 # 53 | 54 | Levin:1837307557@qq.com 55 | 56 | - 个人博文:[http://blog.battcn.com](http://blog.battcn.com "http://blog.battcn.com") 57 | 58 | 59 | # 如何参与 # 60 | 61 | 有兴趣的可以联系本人(Pull Request),参与进来一起开发 62 | -------------------------------------------------------------------------------- /elasticsearch-spring-boot-starter/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.battcn 7 | elasticsearch-spring-boot 8 | 1.0.1.RELEASE 9 | 10 | com.battcn 11 | elasticsearch-spring-boot-starter 12 | elasticsearch-spring-boot-starter 13 | jar 14 | ${project.parent.version} 15 | 16 | 17 | 1.8 18 | 19 | 20 | 21 | 22 | 23 | com.battcn 24 | elasticsearch-spring-boot-autoconfigure 25 | ${project.parent.version} 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | ${project.basedir}/src/main/resources 34 | META-INF/resources/ 35 | 36 | 37 | 38 | 39 | 40 | org.apache.maven.plugins 41 | maven-compiler-plugin 42 | 43 | ${java.version} 44 | ${java.version} 45 | ${project.build.sourceEncoding} 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /samples/elasticsearch-spring-boot-sample/src/test/java/com/test/PluginTest.java: -------------------------------------------------------------------------------- 1 | package com.test; 2 | 3 | import com.google.common.collect.Lists; 4 | import org.elasticsearch.action.index.IndexRequest; 5 | import org.elasticsearch.common.xcontent.XContentBuilder; 6 | import org.elasticsearch.common.xcontent.json.JsonXContent; 7 | import org.junit.Test; 8 | 9 | import java.io.IOException; 10 | 11 | public class PluginTest { 12 | 13 | @Test 14 | public void test1() throws IOException { 15 | IndexRequest indexRequest = new IndexRequest(); 16 | XContentBuilder builder = JsonXContent.contentBuilder() 17 | .startObject() 18 | .startObject("mappings") 19 | .startObject("properties") 20 | .startObject("title") 21 | .field("type", "text") 22 | .field("analyzer", "ik_pinyin_analyzer") 23 | .endObject() 24 | .startObject("content") 25 | .field("type", "text") 26 | .field("index", "analyzed") 27 | .field("analyzer", "ik_max_word") 28 | .endObject() 29 | .startObject("desc").field("type", "keyword").endObject() 30 | .endObject() 31 | .endObject() 32 | .startObject("aliases").endObject() 33 | .startObject("settings") 34 | .startObject("analysis") 35 | .startObject("analyzer") 36 | .startObject("ik_pinyin_analyzer") 37 | .field("type", "text") 38 | .field("tokenizer", "ik_max_word") 39 | .field("filter", Lists.newArrayList("ik_pinyin", "word_delimiter")) 40 | .endObject() 41 | .endObject() 42 | .endObject() 43 | .startObject("filter").startObject("ik_pinyin").field("type", "pinyin").endObject().endObject() 44 | .endObject() 45 | .endObject(); 46 | indexRequest.source(builder); 47 | String source = indexRequest.source().utf8ToString(); 48 | System.out.println(source); 49 | } 50 | 51 | 52 | } 53 | -------------------------------------------------------------------------------- /samples/elasticsearch-spring-boot-sample/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.1.6.RELEASE 9 | 10 | com.battcn 11 | elasticsearch-spring-boot-sample 12 | 1.0.1.RELEASE 13 | elasticsearch-spring-boot-sample 14 | 15 | 16 | 1.8 17 | 7.1.1 18 | 19 | 20 | 21 | 22 | com.alibaba 23 | fastjson 24 | 1.2.56 25 | 26 | 27 | com.battcn 28 | elasticsearch-spring-boot-starter 29 | 1.0.1.RELEASE 30 | 31 | 32 | com.battcn 33 | swagger-spring-boot-starter 34 | 2.1.5-RELEASE 35 | 36 | 37 | org.springframework.boot 38 | spring-boot-starter-web 39 | 40 | 41 | org.springframework.boot 42 | spring-boot-starter-data-redis 43 | 44 | 45 | org.projectlombok 46 | lombok 47 | true 48 | 49 | 50 | org.springframework.boot 51 | spring-boot-starter-test 52 | test 53 | 54 | 55 | 56 | 57 | 58 | 59 | org.springframework.boot 60 | spring-boot-maven-plugin 61 | 62 | 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /elasticsearch-spring-boot-autoconfigure/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.battcn 7 | elasticsearch-spring-boot 8 | 1.0.1.RELEASE 9 | 10 | com.battcn 11 | elasticsearch-spring-boot-autoconfigure 12 | elasticsearch-spring-boot-autoconfigure 13 | jar 14 | ${project.parent.version} 15 | 16 | 17 | 18 | UTF-8 19 | 1.8 20 | 2.1.6.RELEASE 21 | 22 | true 23 | 24 | 25 | 26 | 27 | 28 | org.slf4j 29 | slf4j-api 30 | 31 | 32 | org.elasticsearch 33 | elasticsearch 34 | 35 | 36 | org.elasticsearch.client 37 | elasticsearch-rest-client 38 | 39 | 40 | org.elasticsearch.client 41 | elasticsearch-rest-high-level-client 42 | 43 | 44 | org.springframework.boot 45 | spring-boot-configuration-processor 46 | true 47 | 48 | 49 | org.projectlombok 50 | lombok 51 | true 52 | 53 | 54 | org.springframework.boot 55 | spring-boot-starter-test 56 | test 57 | 58 | 59 | org.springframework.boot 60 | spring-boot-autoconfigure 61 | 62 | 63 | 64 | 65 | 66 | 67 | org.springframework.boot 68 | spring-boot-maven-plugin 69 | 70 | 71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /samples/elasticsearch-spring-boot-sample/src/main/java/com/battcn/samples/controller/IkPinYinPluginController.java: -------------------------------------------------------------------------------- 1 | package com.battcn.samples.controller; 2 | 3 | import com.google.common.collect.Lists; 4 | import com.google.common.collect.Maps; 5 | import io.swagger.annotations.Api; 6 | import lombok.AllArgsConstructor; 7 | import lombok.extern.slf4j.Slf4j; 8 | import org.elasticsearch.client.RequestOptions; 9 | import org.elasticsearch.client.RestHighLevelClient; 10 | import org.elasticsearch.client.indices.CreateIndexRequest; 11 | import org.elasticsearch.client.indices.CreateIndexResponse; 12 | import org.elasticsearch.common.xcontent.XContentBuilder; 13 | import org.elasticsearch.common.xcontent.json.JsonXContent; 14 | import org.springframework.web.bind.annotation.PathVariable; 15 | import org.springframework.web.bind.annotation.PostMapping; 16 | import org.springframework.web.bind.annotation.RequestMapping; 17 | import org.springframework.web.bind.annotation.RestController; 18 | 19 | import java.io.IOException; 20 | import java.util.Map; 21 | 22 | /** 23 | * IK + PinYin 分词器插件 24 | * 25 | * @author Levin 26 | */ 27 | @Slf4j 28 | @RestController 29 | @RequestMapping("/plugins") 30 | @AllArgsConstructor 31 | @Api(tags = "2.0.0", description = "插件使用", value = "插件使用") 32 | public class IkPinYinPluginController { 33 | 34 | 35 | private final RestHighLevelClient restHighLevelClient; 36 | 37 | @PostMapping("/{index}/map") 38 | public CreateIndexResponse index1(@PathVariable String index) throws IOException { 39 | CreateIndexRequest indexRequest = new CreateIndexRequest(index); 40 | 41 | Map settings = Maps.newHashMap(); 42 | Map analysis = Maps.newHashMap(); 43 | 44 | Map analyzer = Maps.newHashMap(); 45 | 46 | Map ikPinyinAnalyzer = Maps.newHashMap(); 47 | ikPinyinAnalyzer.put("type", "custom"); 48 | ikPinyinAnalyzer.put("tokenizer", "ik_max_word"); 49 | ikPinyinAnalyzer.put("filter", Lists.newArrayList("ik_pinyin", "word_delimiter")); 50 | analyzer.put("ik_pinyin_analyzer", ikPinyinAnalyzer); 51 | 52 | Map filter = Maps.newHashMap(); 53 | Map pinyin = Maps.newHashMap(); 54 | pinyin.put("type", "pinyin"); 55 | filter.put("ik_pinyin", pinyin); 56 | 57 | analysis.put("filter", filter); 58 | analysis.put("analyzer", analyzer); 59 | settings.put("analysis", analysis); 60 | indexRequest.settings(settings); 61 | 62 | Map mapping = Maps.newHashMap(); 63 | Map properties = Maps.newHashMap(); 64 | Map id = Maps.newHashMap(); 65 | id.put("type", "integer"); 66 | Map username = Maps.newHashMap(); 67 | username.put("type", "text"); 68 | username.put("analyzer", "ik_pinyin_analyzer"); 69 | Map description = Maps.newHashMap(); 70 | description.put("type", "text"); 71 | description.put("analyzer", "ik_pinyin_analyzer"); 72 | properties.put("id", id); 73 | properties.put("username", username); 74 | properties.put("description", description); 75 | mapping.put("properties", properties); 76 | indexRequest.mapping(mapping); 77 | return restHighLevelClient.indices().create(indexRequest, RequestOptions.DEFAULT); 78 | } 79 | 80 | 81 | @PostMapping("/{index}/object") 82 | public CreateIndexResponse index2(@PathVariable String index) throws IOException { 83 | CreateIndexRequest indexRequest = new CreateIndexRequest(index); 84 | XContentBuilder settings = JsonXContent.contentBuilder().startObject() 85 | .startObject("analysis") 86 | .startObject("analyzer") 87 | .startObject("ik_pinyin_analyzer") 88 | .field("type", "custom") 89 | .field("tokenizer", "ik_max_word") 90 | .field("filter ", Lists.newArrayList("ik_pinyin", "word_delimiter")) 91 | .endObject() 92 | .endObject() 93 | .startObject("filter").startObject("ik_pinyin").field("type", "pinyin").endObject().endObject() 94 | .endObject().endObject(); 95 | indexRequest.settings(settings); 96 | 97 | XContentBuilder mapping = JsonXContent.contentBuilder().startObject() 98 | .startObject("properties") 99 | .startObject("title").field("type", "text").field("analyzer", "ik_pinyin_analyzer").endObject() 100 | .startObject("content").field("type", "text").field("analyzer", "ik_pinyin_analyzer").endObject() 101 | .endObject().endObject(); 102 | indexRequest.mapping(mapping); 103 | return restHighLevelClient.indices().create(indexRequest, RequestOptions.DEFAULT); 104 | 105 | 106 | } 107 | 108 | } 109 | -------------------------------------------------------------------------------- /elasticsearch-spring-boot-autoconfigure/src/main/java/com/battcn/boot/elasticsearch/autoconfigure/ElasticsearchRestAutoConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.battcn.boot.elasticsearch.autoconfigure; 2 | 3 | import com.battcn.boot.elasticsearch.properties.ElasticsearchHttpClientProperties; 4 | import com.battcn.boot.elasticsearch.properties.ElasticsearchRestClientProperties; 5 | import lombok.extern.slf4j.Slf4j; 6 | import org.apache.http.HttpHost; 7 | import org.apache.http.auth.AuthScope; 8 | import org.apache.http.auth.Credentials; 9 | import org.apache.http.auth.UsernamePasswordCredentials; 10 | import org.apache.http.client.CredentialsProvider; 11 | import org.apache.http.impl.client.BasicCredentialsProvider; 12 | import org.apache.http.impl.nio.reactor.IOReactorConfig; 13 | import org.elasticsearch.client.*; 14 | import org.springframework.beans.factory.ObjectProvider; 15 | import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; 16 | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; 17 | import org.springframework.boot.autoconfigure.elasticsearch.rest.RestClientBuilderCustomizer; 18 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 19 | import org.springframework.boot.context.properties.PropertyMapper; 20 | import org.springframework.context.annotation.Bean; 21 | import org.springframework.context.annotation.Configuration; 22 | 23 | import java.io.IOException; 24 | 25 | 26 | /** 27 | * @author Levin 28 | * @since 2019-07-03 29 | */ 30 | @Slf4j 31 | @Configuration 32 | @EnableConfigurationProperties({ElasticsearchRestClientProperties.class, ElasticsearchHttpClientProperties.class}) 33 | public class ElasticsearchRestAutoConfiguration { 34 | 35 | private ObjectProvider builderCustomizers; 36 | 37 | public ElasticsearchRestAutoConfiguration(ObjectProvider builderCustomizers) { 38 | this.builderCustomizers = builderCustomizers; 39 | } 40 | 41 | 42 | @Bean 43 | @ConditionalOnMissingBean 44 | public RestClient restClient(RestClientBuilder builder) { 45 | return builder.build(); 46 | } 47 | 48 | @Bean 49 | @ConditionalOnMissingBean 50 | public RestClientBuilder restClientBuilder(ElasticsearchRestClientProperties restClientProperties, ElasticsearchHttpClientProperties httpClientProperties) { 51 | HttpHost[] hosts = restClientProperties.getUris().stream().map(HttpHost::create).toArray(HttpHost[]::new); 52 | 53 | 54 | RestClientBuilder builder = RestClient.builder(hosts); 55 | PropertyMapper map = PropertyMapper.get(); 56 | map.from(restClientProperties::getUsername).whenHasText().to((username) -> { 57 | CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); 58 | Credentials credentials = new UsernamePasswordCredentials(restClientProperties.getUsername(), restClientProperties.getPassword()); 59 | credentialsProvider.setCredentials(AuthScope.ANY, credentials); 60 | // 设置 http 客户端回调 61 | RestClientBuilder.HttpClientConfigCallback httpClientConfigCallback = httpClientBuilder -> 62 | httpClientBuilder.setDefaultIOReactorConfig( 63 | IOReactorConfig.custom() 64 | .setIoThreadCount(Runtime.getRuntime().availableProcessors() * 5) 65 | .build()) 66 | .setMaxConnTotal(httpClientProperties.getMaxTotal()) 67 | .setMaxConnPerRoute(httpClientProperties.getDefaultMaxPerRoute()) 68 | .setDefaultCredentialsProvider(credentialsProvider); 69 | builder.setHttpClientConfigCallback(httpClientConfigCallback); 70 | }); 71 | builder.setRequestConfigCallback(requestConfigBuilder -> requestConfigBuilder 72 | .setConnectionRequestTimeout(httpClientProperties.getConnectionRequestTimeout()) 73 | .setConnectTimeout(httpClientProperties.getConnectTimeout()) 74 | .setSocketTimeout(httpClientProperties.getReadTimeout())) 75 | .setFailureListener(new RestClient.FailureListener() { 76 | @Override 77 | public void onFailure(Node node) { 78 | log.error("elasticsearch server occur error."); 79 | super.onFailure(node); 80 | } 81 | }); 82 | this.builderCustomizers.orderedStream().forEach((customizer) -> customizer.customize(builder)); 83 | return builder; 84 | } 85 | 86 | @Configuration 87 | @ConditionalOnClass(RestHighLevelClient.class) 88 | public static class RestHighLevelClientConfiguration { 89 | 90 | @Bean 91 | @ConditionalOnMissingBean 92 | public RestHighLevelClient restHighLevelClient(RestClientBuilder restClientBuilder) throws IOException { 93 | RestHighLevelClient client = new RestHighLevelClient(restClientBuilder); 94 | boolean ping = client.ping(RequestOptions.DEFAULT); 95 | if (ping) { 96 | log.info("elasticsearch server connected"); 97 | } 98 | return client; 99 | } 100 | 101 | } 102 | 103 | 104 | } 105 | -------------------------------------------------------------------------------- /samples/elasticsearch-spring-boot-sample/src/main/java/com/battcn/samples/controller/BookController.java: -------------------------------------------------------------------------------- 1 | package com.battcn.samples.controller; 2 | 3 | import com.alibaba.fastjson.JSON; 4 | import com.alibaba.fastjson.JSONObject; 5 | import com.battcn.samples.entity.Book; 6 | import io.swagger.annotations.Api; 7 | import lombok.AllArgsConstructor; 8 | import lombok.extern.slf4j.Slf4j; 9 | import org.elasticsearch.action.ActionListener; 10 | import org.elasticsearch.action.DocWriteResponse; 11 | import org.elasticsearch.action.get.GetRequest; 12 | import org.elasticsearch.action.get.GetResponse; 13 | import org.elasticsearch.action.get.MultiGetRequest; 14 | import org.elasticsearch.action.get.MultiGetResponse; 15 | import org.elasticsearch.action.index.IndexRequest; 16 | import org.elasticsearch.action.index.IndexResponse; 17 | import org.elasticsearch.action.search.SearchRequest; 18 | import org.elasticsearch.action.search.SearchResponse; 19 | import org.elasticsearch.action.support.replication.ReplicationResponse; 20 | import org.elasticsearch.client.RequestOptions; 21 | import org.elasticsearch.client.RestHighLevelClient; 22 | import org.elasticsearch.common.unit.TimeValue; 23 | import org.elasticsearch.common.xcontent.XContentType; 24 | import org.elasticsearch.index.query.QueryBuilders; 25 | import org.elasticsearch.search.builder.SearchSourceBuilder; 26 | import org.elasticsearch.search.fetch.subphase.FetchSourceContext; 27 | import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder; 28 | import org.elasticsearch.search.sort.SortOrder; 29 | import org.springframework.web.bind.annotation.*; 30 | 31 | import java.io.IOException; 32 | 33 | /** 34 | * @author Levin 35 | */ 36 | @Slf4j 37 | @RestController 38 | @RequestMapping("/books") 39 | @AllArgsConstructor 40 | @Api(tags = "1.0.0", description = "书籍信息", value = "书籍信息") 41 | public class BookController { 42 | 43 | private final RestHighLevelClient restHighLevelClient; 44 | 45 | @GetMapping("/{index}/{id}") 46 | public Book find(@PathVariable String index, @PathVariable String id) throws IOException { 47 | GetRequest getRequest = new GetRequest(index, id); 48 | GetResponse response = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT); 49 | return JSONObject.parseObject(response.getSourceAsBytes(), Book.class); 50 | } 51 | 52 | @PostMapping("/{index}") 53 | public IndexResponse add(@PathVariable String index, @RequestBody Book book) throws IOException { 54 | IndexRequest request = new IndexRequest(index).id(book.getId() + "").source(JSON.toJSONString(book), XContentType.JSON); 55 | // 设置 10 秒的超时时间 56 | request.timeout(TimeValue.timeValueSeconds(10)); 57 | //ShardId shardId = new ShardId(new Index("my-shard", "uuid"), 10); 58 | //request.setShardId(shardId); 59 | IndexResponse indexResponse = restHighLevelClient.index(request, RequestOptions.DEFAULT); 60 | DocWriteResponse.Result indexResponseResult = indexResponse.getResult(); 61 | if (indexResponseResult == DocWriteResponse.Result.CREATED) { 62 | // 处理(如果需要)第一次创建文档的情况 63 | } else if (indexResponseResult == DocWriteResponse.Result.UPDATED) { 64 | //处理(如果需要)文档被重写的情况,因为它已经存在 65 | } 66 | ReplicationResponse.ShardInfo shardInfo = indexResponse.getShardInfo(); 67 | if (shardInfo.getTotal() != shardInfo.getSuccessful()) { 68 | 69 | } 70 | if (shardInfo.getFailed() > 0) { 71 | for (ReplicationResponse.ShardInfo.Failure failure : 72 | shardInfo.getFailures()) { 73 | String reason = failure.reason(); 74 | log.warn("失败原因 {}", reason); 75 | } 76 | } 77 | return indexResponse; 78 | 79 | } 80 | 81 | @GetMapping("/query") 82 | public MultiGetResponse query() throws IOException { 83 | 84 | SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); 85 | // 设置 query 查询方式 86 | sourceBuilder.query(QueryBuilders.termQuery("user", "kimchy")); 87 | // 过滤返回的 source 数据 88 | sourceBuilder.fetchSource(true); 89 | // 设置排序 90 | sourceBuilder.sort("id", SortOrder.DESC); 91 | String[] includeFields = new String[]{"title", "innerObject.*"}; 92 | String[] excludeFields = new String[]{"user"}; 93 | // 接受一个或多个通配符模式的数组,以控制以更精细的方式包含或排除哪些字段: 94 | sourceBuilder.fetchSource(includeFields, excludeFields); 95 | 96 | // 设置高亮 97 | HighlightBuilder highlightBuilder = new HighlightBuilder(); 98 | HighlightBuilder.Field highlightTitle = new HighlightBuilder.Field("title"); 99 | // 设置高亮的类型(选填) 100 | highlightTitle.highlighterType("unified"); 101 | // 将字段突出显示器添加到突出显示构建器 102 | highlightBuilder.field(highlightTitle); 103 | sourceBuilder.highlighter(highlightBuilder); 104 | // 设置分页 105 | sourceBuilder.from(1); 106 | sourceBuilder.size(10); 107 | // 谁知分数(类似权重) 108 | sourceBuilder.minScore(1.2F); 109 | 110 | SearchRequest searchRequest = new SearchRequest(); 111 | searchRequest.source(sourceBuilder); 112 | restHighLevelClient.searchAsync(searchRequest, RequestOptions.DEFAULT, new ActionListener() { 113 | @Override 114 | public void onResponse(SearchResponse searchResponse) { 115 | log.info("[成功的响应] - [{}]", searchResponse); 116 | } 117 | 118 | @Override 119 | public void onFailure(Exception e) { 120 | log.error("[失败的响应]", e); 121 | } 122 | }); 123 | 124 | 125 | MultiGetRequest request = new MultiGetRequest(); 126 | request.add(new MultiGetRequest.Item("books", "1")); 127 | request.add(new MultiGetRequest.Item("books", "2")); 128 | request.add(new MultiGetRequest.Item("books", "3") 129 | .fetchSourceContext(FetchSourceContext.DO_NOT_FETCH_SOURCE)); 130 | return restHighLevelClient.mget(request, RequestOptions.DEFAULT); 131 | } 132 | 133 | } 134 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.battcn 7 | elasticsearch-spring-boot 8 | 1.0.1.RELEASE 9 | https://github.com/battcn/elasticsearch-spring-boot-starter.git 10 | 基于 elasticsearch 高版本API做的一款扩展工具包 11 | elasticsearch-spring-boot 12 | pom 13 | 14 | 15 | elasticsearch-spring-boot-autoconfigure 16 | elasticsearch-spring-boot-starter 17 | 18 | 19 | 20 | battcn开源组 21 | http://blog.battcn.com 22 | 23 | 24 | 25 | 26 | 27 | The Apache Software License, Version 2.0 28 | http://www.apache.org/licenses/LICENSE-2.0.txt 29 | repo 30 | 31 | 32 | 33 | 34 | http://blog.battcn.com 35 | git@github.com:battcn/elasticsearch-spring-boot.git 36 | https://github.com/battcn/elasticsearch-spring-boot.git 37 | 38 | 39 | 40 | 41 | 唐亚峰 - battcn 42 | 1837307557@qq.com 43 | http://blog.battcn.com 44 | 45 | Java 开发工程师 46 | 47 | 48 | 49 | 50 | 51 | 52 | UTF-8 53 | 1.8 54 | 7.1.1 55 | 2.1.6.RELEASE 56 | 57 | true 58 | 3.0.1 59 | 2.10.4 60 | 1.6 61 | 62 | 63 | 64 | 65 | 66 | org.elasticsearch 67 | elasticsearch 68 | ${elasticsearch.version} 69 | 70 | 71 | org.elasticsearch.client 72 | elasticsearch-rest-client 73 | ${elasticsearch.version} 74 | 75 | 76 | org.elasticsearch.client 77 | elasticsearch-rest-high-level-client 78 | ${elasticsearch.version} 79 | 80 | 81 | org.springframework.boot 82 | spring-boot-dependencies 83 | ${spring-boot.version} 84 | pom 85 | import 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | oss 94 | https://oss.sonatype.org/content/repositories/snapshots/ 95 | 96 | 97 | oss 98 | https://oss.sonatype.org/service/local/staging/deploy/maven2/ 99 | 100 | 101 | 102 | 103 | 104 | 105 | oss 106 | 107 | 108 | 109 | 110 | org.apache.maven.plugins 111 | maven-resources-plugin 112 | 113 | UTF-8 114 | 115 | 116 | 117 | org.apache.maven.plugins 118 | maven-source-plugin 119 | 120 | 121 | attach-sources 122 | 123 | jar 124 | 125 | 126 | 127 | 128 | 129 | 130 | org.apache.maven.plugins 131 | maven-compiler-plugin 132 | 133 | ${java.version} 134 | ${java.version} 135 | ${project.build.sourceEncoding} 136 | 137 | 138 | 139 | 140 | org.apache.maven.plugins 141 | maven-source-plugin 142 | ${maven-source-plugin.version} 143 | 144 | 145 | package 146 | 147 | jar-no-fork 148 | 149 | 150 | 151 | 152 | 153 | 154 | org.apache.maven.plugins 155 | maven-javadoc-plugin 156 | 157 | 158 | package 159 | 160 | jar 161 | 162 | 163 | 164 | 165 | 166 | 167 | org.apache.maven.plugins 168 | maven-gpg-plugin 169 | ${maven-gpg-plugin.version} 170 | 171 | 172 | verify 173 | 174 | sign 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | oss 185 | https://oss.sonatype.org/content/repositories/snapshots/ 186 | 187 | 188 | oss 189 | https://oss.sonatype.org/service/local/staging/deploy/maven2/ 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | org.apache.maven.plugins 201 | maven-resources-plugin 202 | 203 | UTF-8 204 | 205 | 206 | 207 | org.apache.maven.plugins 208 | maven-source-plugin 209 | 210 | 211 | attach-sources 212 | 213 | jar 214 | 215 | 216 | 217 | 218 | 219 | 220 | org.apache.maven.plugins 221 | maven-compiler-plugin 222 | 223 | ${java.version} 224 | ${java.version} 225 | ${project.build.sourceEncoding} 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | --------------------------------------------------------------------------------