@@ -1,8 +1,8 @@ | |||||
# spring-boot-demo-elasticsearch-rest-high-level-client | # spring-boot-demo-elasticsearch-rest-high-level-client | ||||
> 此 demo 主要演示了 Spring Boot 如何集成 `elasticsearch-rest-high-level-client` 完成对 ElasticSearch 的基本CURD 操作 | |||||
> 此 demo 主要演示了 Spring Boot 如何集成 `elasticsearch-rest-high-level-client` 完成对 `ElasticSearch 7.x` 版本的基本 CURD 操作 | |||||
## elasticsearch 升级 | |||||
## Elasticsearch 升级 | |||||
先升级到 6.8,索引创建,设置 mapping 等操作加参数:include_type_name=true,然后滚动升级到 7,旧索引可以用 type 访问。具体可以参考: | 先升级到 6.8,索引创建,设置 mapping 等操作加参数:include_type_name=true,然后滚动升级到 7,旧索引可以用 type 访问。具体可以参考: | ||||
@@ -12,17 +12,18 @@ https://www.elastic.co/guide/en/elasticsearch/reference/7.0/removal-of-types.htm | |||||
## 注意 | ## 注意 | ||||
作者编写本demo时,ElasticSearch版本为 `7.3.0`,使用 docker 运行,下面是所有步骤: | |||||
作者编写本 demo 时,ElasticSearch 版本为 `7.3.0`,使用 docker 运行,下面是所有步骤: | |||||
1. 下载镜像:`docker pull elasticsearch:7.3.0` | |||||
1.下载镜像:`docker pull elasticsearch:7.3.0` | |||||
2. 下载安装 `docker-compose` | |||||
``` | |||||
2.下载安装 `docker-compose`,参考文档: https://docs.docker.com/compose/install/ | |||||
```bash | |||||
sudo curl -L "https://github.com/docker/compose/releases/download/1.24.1/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose | sudo curl -L "https://github.com/docker/compose/releases/download/1.24.1/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose | ||||
参考文档: https://docs.docker.com/compose/install/ | |||||
``` | ``` | ||||
2. 编写docker-compose 文件 | |||||
3.编写docker-compose 文件 | |||||
```yaml | ```yaml | ||||
version: "3" | version: "3" | ||||
@@ -47,8 +48,7 @@ services: | |||||
max-size: "50m" | max-size: "50m" | ||||
``` | ``` | ||||
3. 启动: `docker-compose -f elasticsearch.yaml up -d` | |||||
4.启动: `docker-compose -f elasticsearch.yaml up -d` | |||||
## pom.xml | ## pom.xml | ||||
@@ -108,7 +108,6 @@ services: | |||||
<dependency> | <dependency> | ||||
<groupId>cn.hutool</groupId> | <groupId>cn.hutool</groupId> | ||||
<artifactId>hutool-all</artifactId> | <artifactId>hutool-all</artifactId> | ||||
<version>4.6.6</version> | |||||
</dependency> | </dependency> | ||||
<!-- elasticsearch --> | <!-- elasticsearch --> | ||||
@@ -151,8 +150,17 @@ services: | |||||
</dependencies> | </dependencies> | ||||
</project> | |||||
<build> | |||||
<finalName>spring-boot-demo-elasticsearch-rest-high-level-client</finalName> | |||||
<plugins> | |||||
<plugin> | |||||
<groupId>org.springframework.boot</groupId> | |||||
<artifactId>spring-boot-maven-plugin</artifactId> | |||||
</plugin> | |||||
</plugins> | |||||
</build> | |||||
</project> | |||||
``` | ``` | ||||
## Person.java | ## Person.java | ||||
@@ -217,7 +225,6 @@ public class Person implements Serializable { | |||||
private String remark; | private String remark; | ||||
} | } | ||||
``` | ``` | ||||
## PersonService.java | ## PersonService.java | ||||
@@ -291,7 +298,6 @@ public interface PersonService { | |||||
List<Person> searchList(String index); | List<Person> searchList(String index); | ||||
} | } | ||||
``` | ``` | ||||
## PersonServiceImpl.java | ## PersonServiceImpl.java | ||||
@@ -303,7 +309,7 @@ package com.xkcoding.elasticsearch.service.impl; | |||||
import cn.hutool.core.bean.BeanUtil; | import cn.hutool.core.bean.BeanUtil; | ||||
import com.xkcoding.elasticsearch.model.Person; | import com.xkcoding.elasticsearch.model.Person; | ||||
import com.xkcoding.elasticsearch.service.BaseElasticsearchService; | |||||
import com.xkcoding.elasticsearch.service.base.BaseElasticsearchService; | |||||
import com.xkcoding.elasticsearch.service.PersonService; | import com.xkcoding.elasticsearch.service.PersonService; | ||||
import org.elasticsearch.action.index.IndexRequest; | import org.elasticsearch.action.index.IndexRequest; | ||||
import org.elasticsearch.action.search.SearchResponse; | import org.elasticsearch.action.search.SearchResponse; | ||||
@@ -327,7 +333,6 @@ import java.util.Map; | |||||
@Service | @Service | ||||
public class PersonServiceImpl extends BaseElasticsearchService implements PersonService { | public class PersonServiceImpl extends BaseElasticsearchService implements PersonService { | ||||
@Override | @Override | ||||
public void createIndex(String index) { | public void createIndex(String index) { | ||||
createIndexRequest(index); | createIndexRequest(index); | ||||
@@ -390,7 +395,6 @@ public class PersonServiceImpl extends BaseElasticsearchService implements Perso | |||||
return personList; | return personList; | ||||
} | } | ||||
} | } | ||||
``` | ``` | ||||
@@ -406,10 +410,10 @@ import com.xkcoding.elasticsearch.model.Person; | |||||
import com.xkcoding.elasticsearch.service.PersonService; | import com.xkcoding.elasticsearch.service.PersonService; | ||||
import org.junit.Test; | import org.junit.Test; | ||||
import org.junit.runner.RunWith; | import org.junit.runner.RunWith; | ||||
import org.springframework.beans.factory.annotation.Autowired; | |||||
import org.springframework.boot.test.context.SpringBootTest; | import org.springframework.boot.test.context.SpringBootTest; | ||||
import org.springframework.test.context.junit4.SpringRunner; | import org.springframework.test.context.junit4.SpringRunner; | ||||
import javax.annotation.Resource; | |||||
import java.util.ArrayList; | import java.util.ArrayList; | ||||
import java.util.Date; | import java.util.Date; | ||||
import java.util.List; | import java.util.List; | ||||
@@ -418,22 +422,30 @@ import java.util.List; | |||||
@SpringBootTest | @SpringBootTest | ||||
public class ElasticsearchApplicationTests { | public class ElasticsearchApplicationTests { | ||||
@Resource | |||||
@Autowired | |||||
private PersonService personService; | private PersonService personService; | ||||
/** | |||||
* 测试删除索引 | |||||
*/ | |||||
@Test | @Test | ||||
public void deleteIndexTest() { | public void deleteIndexTest() { | ||||
personService.deleteIndex(ElasticsearchConstant.INDEX_NAME); | personService.deleteIndex(ElasticsearchConstant.INDEX_NAME); | ||||
} | } | ||||
/** | |||||
* 测试创建索引 | |||||
*/ | |||||
@Test | @Test | ||||
public void createIndexTest() { | public void createIndexTest() { | ||||
personService.createIndex(ElasticsearchConstant.INDEX_NAME); | personService.createIndex(ElasticsearchConstant.INDEX_NAME); | ||||
} | } | ||||
/** | |||||
* 测试新增 | |||||
*/ | |||||
@Test | @Test | ||||
public void insertTest() { | public void insertTest() { | ||||
List<Person> list = new ArrayList<>(); | List<Person> list = new ArrayList<>(); | ||||
list.add(Person.builder().age(11).birthday(new Date()).country("CN").id(1L).name("哈哈").remark("test1").build()); | list.add(Person.builder().age(11).birthday(new Date()).country("CN").id(1L).name("哈哈").remark("test1").build()); | ||||
list.add(Person.builder().age(22).birthday(new Date()).country("US").id(2L).name("hiahia").remark("test2").build()); | list.add(Person.builder().age(22).birthday(new Date()).country("US").id(2L).name("hiahia").remark("test2").build()); | ||||
@@ -442,6 +454,9 @@ public class ElasticsearchApplicationTests { | |||||
personService.insert(ElasticsearchConstant.INDEX_NAME, list); | personService.insert(ElasticsearchConstant.INDEX_NAME, list); | ||||
} | } | ||||
/** | |||||
* 测试更新 | |||||
*/ | |||||
@Test | @Test | ||||
public void updateTest() { | public void updateTest() { | ||||
Person person = Person.builder().age(33).birthday(new Date()).country("ID_update").id(3L).name("呵呵update").remark("test3_update").build(); | Person person = Person.builder().age(33).birthday(new Date()).country("ID_update").id(3L).name("呵呵update").remark("test3_update").build(); | ||||
@@ -450,24 +465,29 @@ public class ElasticsearchApplicationTests { | |||||
personService.update(ElasticsearchConstant.INDEX_NAME, list); | personService.update(ElasticsearchConstant.INDEX_NAME, list); | ||||
} | } | ||||
/** | |||||
* 测试删除 | |||||
*/ | |||||
@Test | @Test | ||||
public void deleteTest() { | public void deleteTest() { | ||||
personService.delete(ElasticsearchConstant.INDEX_NAME, Person.builder().id(1L).build()); | personService.delete(ElasticsearchConstant.INDEX_NAME, Person.builder().id(1L).build()); | ||||
} | } | ||||
/** | |||||
* 测试查询 | |||||
*/ | |||||
@Test | @Test | ||||
public void searchListTest() { | public void searchListTest() { | ||||
List<Person> personList = personService.searchList(ElasticsearchConstant.INDEX_NAME); | List<Person> personList = personService.searchList(ElasticsearchConstant.INDEX_NAME); | ||||
System.out.println(personList); | System.out.println(personList); | ||||
} | } | ||||
} | } | ||||
``` | ``` | ||||
## 参考 | ## 参考 | ||||
1. ElasticSearch 官方文档:https://www.elastic.co/guide/en/elasticsearch/reference/current/index.html | |||||
2. Java High Level REST Client:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.3/java-rest-high.html | |||||
- ElasticSearch 官方文档:https://www.elastic.co/guide/en/elasticsearch/reference/current/index.html | |||||
- Java High Level REST Client:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.3/java-rest-high.html | |||||
@@ -53,7 +53,6 @@ | |||||
<dependency> | <dependency> | ||||
<groupId>cn.hutool</groupId> | <groupId>cn.hutool</groupId> | ||||
<artifactId>hutool-all</artifactId> | <artifactId>hutool-all</artifactId> | ||||
<version>4.6.6</version> | |||||
</dependency> | </dependency> | ||||
<!-- elasticsearch --> | <!-- elasticsearch --> | ||||
@@ -96,4 +95,14 @@ | |||||
</dependencies> | </dependencies> | ||||
<build> | |||||
<finalName>spring-boot-demo-elasticsearch-rest-high-level-client</finalName> | |||||
<plugins> | |||||
<plugin> | |||||
<groupId>org.springframework.boot</groupId> | |||||
<artifactId>spring-boot-maven-plugin</artifactId> | |||||
</plugin> | |||||
</plugins> | |||||
</build> | |||||
</project> | </project> |
@@ -1,4 +1,4 @@ | |||||
package com.xkcoding.elasticsearch.model; | |||||
package com.xkcoding.elasticsearch.common; | |||||
import lombok.Data; | import lombok.Data; | ||||
import org.springframework.lang.Nullable; | import org.springframework.lang.Nullable; |
@@ -1,4 +1,4 @@ | |||||
package com.xkcoding.elasticsearch.model; | |||||
package com.xkcoding.elasticsearch.common; | |||||
import lombok.AllArgsConstructor; | import lombok.AllArgsConstructor; | ||||
import lombok.Getter; | import lombok.Getter; |
@@ -1,5 +1,6 @@ | |||||
package com.xkcoding.elasticsearch.autoconfigure; | |||||
package com.xkcoding.elasticsearch.config; | |||||
import lombok.RequiredArgsConstructor; | |||||
import org.apache.http.HttpHost; | import org.apache.http.HttpHost; | ||||
import org.apache.http.auth.AuthScope; | import org.apache.http.auth.AuthScope; | ||||
import org.apache.http.auth.UsernamePasswordCredentials; | import org.apache.http.auth.UsernamePasswordCredentials; | ||||
@@ -8,14 +9,14 @@ import org.apache.http.impl.client.BasicCredentialsProvider; | |||||
import org.elasticsearch.client.RestClient; | import org.elasticsearch.client.RestClient; | ||||
import org.elasticsearch.client.RestClientBuilder; | import org.elasticsearch.client.RestClientBuilder; | ||||
import org.elasticsearch.client.RestHighLevelClient; | import org.elasticsearch.client.RestHighLevelClient; | ||||
import org.springframework.beans.factory.annotation.Autowired; | |||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; | ||||
import org.springframework.boot.context.properties.EnableConfigurationProperties; | import org.springframework.boot.context.properties.EnableConfigurationProperties; | ||||
import org.springframework.context.annotation.Bean; | import org.springframework.context.annotation.Bean; | ||||
import org.springframework.context.annotation.Configuration; | |||||
import org.springframework.util.Assert; | import org.springframework.util.Assert; | ||||
import org.springframework.util.StringUtils; | import org.springframework.util.StringUtils; | ||||
import javax.annotation.Resource; | |||||
import javax.validation.constraints.NotNull; | |||||
import java.util.ArrayList; | import java.util.ArrayList; | ||||
import java.util.List; | import java.util.List; | ||||
@@ -26,13 +27,12 @@ import java.util.List; | |||||
* @version v1.0 | * @version v1.0 | ||||
* @since 2019/9/15 22:59 | * @since 2019/9/15 22:59 | ||||
*/ | */ | ||||
@Configuration | |||||
@RequiredArgsConstructor(onConstructor_ = @Autowired) | |||||
@EnableConfigurationProperties(ElasticsearchProperties.class) | @EnableConfigurationProperties(ElasticsearchProperties.class) | ||||
public class ElasticsearchAutoConfiguration { | public class ElasticsearchAutoConfiguration { | ||||
@SuppressWarnings("NullableProblems") | |||||
@NotNull | |||||
@Resource | |||||
private ElasticsearchProperties elasticsearchProperties; | |||||
private final ElasticsearchProperties elasticsearchProperties; | |||||
private List<HttpHost> httpHosts = new ArrayList<>(); | private List<HttpHost> httpHosts = new ArrayList<>(); | ||||
@@ -48,8 +48,7 @@ public class ElasticsearchAutoConfiguration { | |||||
Assert.state(parts.length == 2, "Must be defined as 'host:port'"); | Assert.state(parts.length == 2, "Must be defined as 'host:port'"); | ||||
httpHosts.add(new HttpHost(parts[0], Integer.parseInt(parts[1]), elasticsearchProperties.getSchema())); | httpHosts.add(new HttpHost(parts[0], Integer.parseInt(parts[1]), elasticsearchProperties.getSchema())); | ||||
} catch (Exception e) { | } catch (Exception e) { | ||||
throw new IllegalStateException( | |||||
"Invalid ES nodes " + "property '" + node + "'", e); | |||||
throw new IllegalStateException("Invalid ES nodes " + "property '" + node + "'", e); | |||||
} | } | ||||
}); | }); | ||||
RestClientBuilder builder = RestClient.builder(httpHosts.toArray(new HttpHost[0])); | RestClientBuilder builder = RestClient.builder(httpHosts.toArray(new HttpHost[0])); | ||||
@@ -61,10 +60,10 @@ public class ElasticsearchAutoConfiguration { | |||||
/** | /** | ||||
* get restHistLevelClient | * get restHistLevelClient | ||||
* | * | ||||
* @author fxbin | |||||
* @param builder RestClientBuilder | |||||
* @param builder RestClientBuilder | |||||
* @param elasticsearchProperties elasticsearch default properties | * @param elasticsearchProperties elasticsearch default properties | ||||
* @return {@link org.elasticsearch.client.RestHighLevelClient} | * @return {@link org.elasticsearch.client.RestHighLevelClient} | ||||
* @author fxbin | |||||
*/ | */ | ||||
private static RestHighLevelClient getRestHighLevelClient(RestClientBuilder builder, ElasticsearchProperties elasticsearchProperties) { | private static RestHighLevelClient getRestHighLevelClient(RestClientBuilder builder, ElasticsearchProperties elasticsearchProperties) { | ||||
@@ -88,11 +87,9 @@ public class ElasticsearchAutoConfiguration { | |||||
if (!StringUtils.isEmpty(account.getUsername()) && !StringUtils.isEmpty(account.getUsername())) { | if (!StringUtils.isEmpty(account.getUsername()) && !StringUtils.isEmpty(account.getUsername())) { | ||||
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); | final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); | ||||
credentialsProvider.setCredentials(AuthScope.ANY, | |||||
new UsernamePasswordCredentials(account.getUsername(), account.getPassword())); | |||||
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(account.getUsername(), account.getPassword())); | |||||
} | } | ||||
return new RestHighLevelClient(builder); | return new RestHighLevelClient(builder); | ||||
} | } | ||||
} | } |
@@ -1,4 +1,4 @@ | |||||
package com.xkcoding.elasticsearch.autoconfigure; | |||||
package com.xkcoding.elasticsearch.config; | |||||
import lombok.AllArgsConstructor; | import lombok.AllArgsConstructor; | ||||
import lombok.Builder; | import lombok.Builder; | ||||
@@ -77,6 +77,9 @@ public class ElasticsearchProperties { | |||||
*/ | */ | ||||
private Account account = new Account(); | private Account account = new Account(); | ||||
/** | |||||
* 索引配置信息 | |||||
*/ | |||||
@Data | @Data | ||||
public static class Index { | public static class Index { | ||||
@@ -92,6 +95,9 @@ public class ElasticsearchProperties { | |||||
} | } | ||||
/** | |||||
* 认证账户 | |||||
*/ | |||||
@Data | @Data | ||||
public static class Account { | public static class Account { | ||||
@@ -1,6 +1,6 @@ | |||||
package com.xkcoding.elasticsearch.exception; | package com.xkcoding.elasticsearch.exception; | ||||
import com.xkcoding.elasticsearch.model.ResultCode; | |||||
import com.xkcoding.elasticsearch.common.ResultCode; | |||||
import lombok.Getter; | import lombok.Getter; | ||||
/** | /** | ||||
@@ -1,8 +1,8 @@ | |||||
package com.xkcoding.elasticsearch.service; | |||||
package com.xkcoding.elasticsearch.service.base; | |||||
import cn.hutool.core.bean.BeanUtil; | |||||
import com.xkcoding.elasticsearch.config.ElasticsearchProperties; | |||||
import com.xkcoding.elasticsearch.exception.ElasticsearchException; | import com.xkcoding.elasticsearch.exception.ElasticsearchException; | ||||
import com.xkcoding.elasticsearch.autoconfigure.ElasticsearchProperties; | |||||
import com.xkcoding.elasticsearch.util.BeanUtils; | |||||
import lombok.extern.slf4j.Slf4j; | import lombok.extern.slf4j.Slf4j; | ||||
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; | import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; | ||||
import org.elasticsearch.action.delete.DeleteRequest; | import org.elasticsearch.action.delete.DeleteRequest; | ||||
@@ -45,31 +45,26 @@ public abstract class BaseElasticsearchService { | |||||
RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder(); | RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder(); | ||||
// 默认缓冲限制为100MB,此处修改为30MB。 | // 默认缓冲限制为100MB,此处修改为30MB。 | ||||
builder.setHttpAsyncResponseConsumerFactory( | |||||
new HttpAsyncResponseConsumerFactory | |||||
.HeapBufferedResponseConsumerFactory(30 * 1024 * 1024)); | |||||
builder.setHttpAsyncResponseConsumerFactory(new HttpAsyncResponseConsumerFactory.HeapBufferedResponseConsumerFactory(30 * 1024 * 1024)); | |||||
COMMON_OPTIONS = builder.build(); | COMMON_OPTIONS = builder.build(); | ||||
} | } | ||||
/** | /** | ||||
* create elasticsearch index (asyc) | * create elasticsearch index (asyc) | ||||
* | * | ||||
* @author fxbin | |||||
* @param index elasticsearch index | * @param index elasticsearch index | ||||
* @author fxbin | |||||
*/ | */ | ||||
protected void createIndexRequest(String index) { | protected void createIndexRequest(String index) { | ||||
try { | try { | ||||
CreateIndexRequest request = new CreateIndexRequest(index); | CreateIndexRequest request = new CreateIndexRequest(index); | ||||
// Settings for this index | // Settings for this index | ||||
request.settings(Settings.builder() | |||||
.put("index.number_of_shards", elasticsearchProperties.getIndex().getNumberOfShards()) | |||||
.put("index.number_of_replicas", elasticsearchProperties.getIndex().getNumberOfReplicas())); | |||||
request.settings(Settings.builder().put("index.number_of_shards", elasticsearchProperties.getIndex().getNumberOfShards()).put("index.number_of_replicas", elasticsearchProperties.getIndex().getNumberOfReplicas())); | |||||
CreateIndexResponse createIndexResponse = client.indices().create(request, COMMON_OPTIONS); | CreateIndexResponse createIndexResponse = client.indices().create(request, COMMON_OPTIONS); | ||||
log.info(" whether all of the nodes have acknowledged the request : {}", createIndexResponse.isAcknowledged()); | log.info(" whether all of the nodes have acknowledged the request : {}", createIndexResponse.isAcknowledged()); | ||||
log.info(" Indicates whether the requisite number of shard copies were started for each shard in the index before timing out :{}", | |||||
createIndexResponse.isShardsAcknowledged()); | |||||
log.info(" Indicates whether the requisite number of shard copies were started for each shard in the index before timing out :{}", createIndexResponse.isShardsAcknowledged()); | |||||
} catch (IOException e) { | } catch (IOException e) { | ||||
throw new ElasticsearchException("创建索引 {" + index + "} 失败"); | throw new ElasticsearchException("创建索引 {" + index + "} 失败"); | ||||
} | } | ||||
@@ -78,8 +73,8 @@ public abstract class BaseElasticsearchService { | |||||
/** | /** | ||||
* delete elasticsearch index | * delete elasticsearch index | ||||
* | * | ||||
* @author fxbin | |||||
* @param index elasticsearch index name | * @param index elasticsearch index name | ||||
* @author fxbin | |||||
*/ | */ | ||||
protected void deleteIndexRequest(String index) { | protected void deleteIndexRequest(String index) { | ||||
DeleteIndexRequest deleteIndexRequest = buildDeleteIndexRequest(index); | DeleteIndexRequest deleteIndexRequest = buildDeleteIndexRequest(index); | ||||
@@ -93,37 +88,37 @@ public abstract class BaseElasticsearchService { | |||||
/** | /** | ||||
* build DeleteIndexRequest | * build DeleteIndexRequest | ||||
* | * | ||||
* @author fxbin | |||||
* @param index elasticsearch index name | * @param index elasticsearch index name | ||||
* @author fxbin | |||||
*/ | */ | ||||
private static DeleteIndexRequest buildDeleteIndexRequest (String index) { | |||||
private static DeleteIndexRequest buildDeleteIndexRequest(String index) { | |||||
return new DeleteIndexRequest(index); | return new DeleteIndexRequest(index); | ||||
} | } | ||||
/** | /** | ||||
* build IndexRequest | * build IndexRequest | ||||
* | * | ||||
* @author fxbin | |||||
* @param index elasticsearch index name | |||||
* @param id request object id | |||||
* @param index elasticsearch index name | |||||
* @param id request object id | |||||
* @param object request object | * @param object request object | ||||
* @return {@link org.elasticsearch.action.index.IndexRequest} | * @return {@link org.elasticsearch.action.index.IndexRequest} | ||||
* @author fxbin | |||||
*/ | */ | ||||
protected static IndexRequest buildIndexRequest(String index, String id, Object object) { | protected static IndexRequest buildIndexRequest(String index, String id, Object object) { | ||||
return new IndexRequest(index).id(id).source(BeanUtils.toMap(object), XContentType.JSON); | |||||
return new IndexRequest(index).id(id).source(BeanUtil.beanToMap(object), XContentType.JSON); | |||||
} | } | ||||
/** | /** | ||||
* exec updateRequest | * exec updateRequest | ||||
* | * | ||||
* @author fxbin | |||||
* @param index elasticsearch index name | |||||
* @param id Document id | |||||
* @param index elasticsearch index name | |||||
* @param id Document id | |||||
* @param object request object | * @param object request object | ||||
* @author fxbin | |||||
*/ | */ | ||||
protected void updateRequest(String index, String id, Object object) { | protected void updateRequest(String index, String id, Object object) { | ||||
try { | try { | ||||
UpdateRequest updateRequest = new UpdateRequest(index, id).doc(BeanUtils.toMap(object), XContentType.JSON); | |||||
UpdateRequest updateRequest = new UpdateRequest(index, id).doc(BeanUtil.beanToMap(object), XContentType.JSON); | |||||
client.update(updateRequest, COMMON_OPTIONS); | client.update(updateRequest, COMMON_OPTIONS); | ||||
} catch (IOException e) { | } catch (IOException e) { | ||||
throw new ElasticsearchException("更新索引 {" + index + "} 数据 {" + object + "} 失败"); | throw new ElasticsearchException("更新索引 {" + index + "} 数据 {" + object + "} 失败"); | ||||
@@ -133,9 +128,9 @@ public abstract class BaseElasticsearchService { | |||||
/** | /** | ||||
* exec deleteRequest | * exec deleteRequest | ||||
* | * | ||||
* @author fxbin | |||||
* @param index elasticsearch index name | * @param index elasticsearch index name | ||||
* @param id Document id | |||||
* @param id Document id | |||||
* @author fxbin | |||||
*/ | */ | ||||
protected void deleteRequest(String index, String id) { | protected void deleteRequest(String index, String id) { | ||||
try { | try { | ||||
@@ -149,9 +144,9 @@ public abstract class BaseElasticsearchService { | |||||
/** | /** | ||||
* search all | * search all | ||||
* | * | ||||
* @author fxbin | |||||
* @param index elasticsearch index name | * @param index elasticsearch index name | ||||
* @return {@link SearchResponse} | * @return {@link SearchResponse} | ||||
* @author fxbin | |||||
*/ | */ | ||||
protected SearchResponse search(String index) { | protected SearchResponse search(String index) { | ||||
SearchRequest searchRequest = new SearchRequest(index); | SearchRequest searchRequest = new SearchRequest(index); |
@@ -2,7 +2,7 @@ package com.xkcoding.elasticsearch.service.impl; | |||||
import cn.hutool.core.bean.BeanUtil; | import cn.hutool.core.bean.BeanUtil; | ||||
import com.xkcoding.elasticsearch.model.Person; | import com.xkcoding.elasticsearch.model.Person; | ||||
import com.xkcoding.elasticsearch.service.BaseElasticsearchService; | |||||
import com.xkcoding.elasticsearch.service.base.BaseElasticsearchService; | |||||
import com.xkcoding.elasticsearch.service.PersonService; | import com.xkcoding.elasticsearch.service.PersonService; | ||||
import org.elasticsearch.action.index.IndexRequest; | import org.elasticsearch.action.index.IndexRequest; | ||||
import org.elasticsearch.action.search.SearchResponse; | import org.elasticsearch.action.search.SearchResponse; | ||||
@@ -26,7 +26,6 @@ import java.util.Map; | |||||
@Service | @Service | ||||
public class PersonServiceImpl extends BaseElasticsearchService implements PersonService { | public class PersonServiceImpl extends BaseElasticsearchService implements PersonService { | ||||
@Override | @Override | ||||
public void createIndex(String index) { | public void createIndex(String index) { | ||||
createIndexRequest(index); | createIndexRequest(index); | ||||
@@ -1,49 +0,0 @@ | |||||
package com.xkcoding.elasticsearch.util; | |||||
import java.beans.BeanInfo; | |||||
import java.beans.Introspector; | |||||
import java.beans.PropertyDescriptor; | |||||
import java.lang.reflect.Method; | |||||
import java.util.Map; | |||||
/** | |||||
* BeanUtils | |||||
* | |||||
* @author fxbin | |||||
* @version 1.0v | |||||
* @since 2019/9/16 16:26 | |||||
*/ | |||||
public class BeanUtils { | |||||
/** | |||||
* Java Bean to Map | |||||
* | |||||
* @author fxbin | |||||
* @param object Object | |||||
* @return Map | |||||
*/ | |||||
public static Map<String,Object> toMap(Object object){ | |||||
Map<String, Object> map = MapUtils.newHashMap(); | |||||
try { | |||||
// 获取javaBean的BeanInfo对象 | |||||
BeanInfo beanInfo = Introspector.getBeanInfo(object.getClass(),Object.class); | |||||
// 获取属性描述器 | |||||
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); | |||||
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { | |||||
// 获取属性名 | |||||
String key = propertyDescriptor.getName(); | |||||
// 获取该属性的值 | |||||
Method readMethod = propertyDescriptor.getReadMethod(); | |||||
// 通过反射来调用javaBean定义的getName()方法 | |||||
Object value = readMethod.invoke(object); | |||||
map.put(key, value); | |||||
} | |||||
} catch (Exception e) { | |||||
e.printStackTrace(); | |||||
} | |||||
return map; | |||||
} | |||||
} |
@@ -1,70 +0,0 @@ | |||||
package com.xkcoding.elasticsearch.util; | |||||
import java.util.HashMap; | |||||
import java.util.LinkedHashMap; | |||||
/** | |||||
* MapUtils | |||||
* | |||||
* @author fxbin | |||||
* @version 1.0v | |||||
* @since 2019/9/16 16:26 | |||||
*/ | |||||
public class MapUtils { | |||||
/** 默认初始大小 */ | |||||
private static final int DEFAULT_INITIAL_CAPACITY = 16; | |||||
/** 默认增长因子,当Map的size达到 容量*增长因子时,开始扩充Map */ | |||||
private static final float DEFAULT_LOAD_FACTOR = 0.75f; | |||||
/** | |||||
* 新建一个HashMap | |||||
* | |||||
* @param <K> Key类型 | |||||
* @param <V> Value类型 | |||||
* @return HashMap对象 | |||||
*/ | |||||
public static <K, V> HashMap<K, V> newHashMap() { | |||||
return new HashMap<>(DEFAULT_INITIAL_CAPACITY); | |||||
} | |||||
/** | |||||
* 新建一个HashMap | |||||
* | |||||
* @param <K> Key类型 | |||||
* @param <V> Value类型 | |||||
* @param size 初始大小,由于默认负载因子0.75,传入的size会实际初始大小为size / 0.75 | |||||
* @param isOrder Map的Key是否有序,有序返回 {@link LinkedHashMap},否则返回 {@link HashMap} | |||||
* @return HashMap对象 | |||||
* @since 3.0.4 | |||||
*/ | |||||
public static <K, V> HashMap<K, V> newHashMap(int size, boolean isOrder) { | |||||
int initialCapacity = (int) (size / DEFAULT_LOAD_FACTOR); | |||||
return isOrder ? new LinkedHashMap<K, V>(initialCapacity) : new HashMap<K, V>(initialCapacity); | |||||
} | |||||
/** | |||||
* 新建一个HashMap | |||||
* | |||||
* @param <K> Key类型 | |||||
* @param <V> Value类型 | |||||
* @param size 初始大小,由于默认负载因子0.75,传入的size会实际初始大小为size / 0.75 | |||||
* @return HashMap对象 | |||||
*/ | |||||
public static <K, V> HashMap<K, V> newHashMap(int size) { | |||||
return newHashMap(size, false); | |||||
} | |||||
/** | |||||
* 新建一个HashMap | |||||
* | |||||
* @param <K> Key类型 | |||||
* @param <V> Value类型 | |||||
* @param isOrder Map的Key是否有序,有序返回 {@link LinkedHashMap},否则返回 {@link HashMap} | |||||
* @return HashMap对象 | |||||
*/ | |||||
public static <K, V> HashMap<K, V> newHashMap(boolean isOrder) { | |||||
return newHashMap(DEFAULT_INITIAL_CAPACITY, isOrder); | |||||
} | |||||
} |
@@ -1,3 +0,0 @@ | |||||
# Auto Configure | |||||
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ | |||||
com.xkcoding.elasticsearch.autoconfigure.ElasticsearchAutoConfiguration |
@@ -5,10 +5,10 @@ import com.xkcoding.elasticsearch.model.Person; | |||||
import com.xkcoding.elasticsearch.service.PersonService; | import com.xkcoding.elasticsearch.service.PersonService; | ||||
import org.junit.Test; | import org.junit.Test; | ||||
import org.junit.runner.RunWith; | import org.junit.runner.RunWith; | ||||
import org.springframework.beans.factory.annotation.Autowired; | |||||
import org.springframework.boot.test.context.SpringBootTest; | import org.springframework.boot.test.context.SpringBootTest; | ||||
import org.springframework.test.context.junit4.SpringRunner; | import org.springframework.test.context.junit4.SpringRunner; | ||||
import javax.annotation.Resource; | |||||
import java.util.ArrayList; | import java.util.ArrayList; | ||||
import java.util.Date; | import java.util.Date; | ||||
import java.util.List; | import java.util.List; | ||||
@@ -17,22 +17,30 @@ import java.util.List; | |||||
@SpringBootTest | @SpringBootTest | ||||
public class ElasticsearchApplicationTests { | public class ElasticsearchApplicationTests { | ||||
@Resource | |||||
@Autowired | |||||
private PersonService personService; | private PersonService personService; | ||||
/** | |||||
* 测试删除索引 | |||||
*/ | |||||
@Test | @Test | ||||
public void deleteIndexTest() { | public void deleteIndexTest() { | ||||
personService.deleteIndex(ElasticsearchConstant.INDEX_NAME); | personService.deleteIndex(ElasticsearchConstant.INDEX_NAME); | ||||
} | } | ||||
/** | |||||
* 测试创建索引 | |||||
*/ | |||||
@Test | @Test | ||||
public void createIndexTest() { | public void createIndexTest() { | ||||
personService.createIndex(ElasticsearchConstant.INDEX_NAME); | personService.createIndex(ElasticsearchConstant.INDEX_NAME); | ||||
} | } | ||||
/** | |||||
* 测试新增 | |||||
*/ | |||||
@Test | @Test | ||||
public void insertTest() { | public void insertTest() { | ||||
List<Person> list = new ArrayList<>(); | List<Person> list = new ArrayList<>(); | ||||
list.add(Person.builder().age(11).birthday(new Date()).country("CN").id(1L).name("哈哈").remark("test1").build()); | list.add(Person.builder().age(11).birthday(new Date()).country("CN").id(1L).name("哈哈").remark("test1").build()); | ||||
list.add(Person.builder().age(22).birthday(new Date()).country("US").id(2L).name("hiahia").remark("test2").build()); | list.add(Person.builder().age(22).birthday(new Date()).country("US").id(2L).name("hiahia").remark("test2").build()); | ||||
@@ -41,6 +49,9 @@ public class ElasticsearchApplicationTests { | |||||
personService.insert(ElasticsearchConstant.INDEX_NAME, list); | personService.insert(ElasticsearchConstant.INDEX_NAME, list); | ||||
} | } | ||||
/** | |||||
* 测试更新 | |||||
*/ | |||||
@Test | @Test | ||||
public void updateTest() { | public void updateTest() { | ||||
Person person = Person.builder().age(33).birthday(new Date()).country("ID_update").id(3L).name("呵呵update").remark("test3_update").build(); | Person person = Person.builder().age(33).birthday(new Date()).country("ID_update").id(3L).name("呵呵update").remark("test3_update").build(); | ||||
@@ -49,16 +60,21 @@ public class ElasticsearchApplicationTests { | |||||
personService.update(ElasticsearchConstant.INDEX_NAME, list); | personService.update(ElasticsearchConstant.INDEX_NAME, list); | ||||
} | } | ||||
/** | |||||
* 测试删除 | |||||
*/ | |||||
@Test | @Test | ||||
public void deleteTest() { | public void deleteTest() { | ||||
personService.delete(ElasticsearchConstant.INDEX_NAME, Person.builder().id(1L).build()); | personService.delete(ElasticsearchConstant.INDEX_NAME, Person.builder().id(1L).build()); | ||||
} | } | ||||
/** | |||||
* 测试查询 | |||||
*/ | |||||
@Test | @Test | ||||
public void searchListTest() { | public void searchListTest() { | ||||
List<Person> personList = personService.searchList(ElasticsearchConstant.INDEX_NAME); | List<Person> personList = personService.searchList(ElasticsearchConstant.INDEX_NAME); | ||||
System.out.println(personList); | System.out.println(personList); | ||||
} | } | ||||
} | } |