diff --git a/src/main/java/io/github/ehlxr/es/utils/JsonUtils.java b/src/main/java/io/github/ehlxr/es/utils/JsonUtils.java new file mode 100644 index 0000000..b80025c --- /dev/null +++ b/src/main/java/io/github/ehlxr/es/utils/JsonUtils.java @@ -0,0 +1,254 @@ +/* + * The MIT License (MIT) + * + * Copyright © 2020 xrv + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package io.github.ehlxr.es.utils; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.*; +import org.elasticsearch.common.Strings; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @author ehlxr + * @since 2021-03-07 18:57. + */ +public class JsonUtils { + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + private static final String STANDARD_FORMAT = "yyyy-MM-dd HH:mm:ss"; + + static { + // 对象的所有字段全部列入 + OBJECT_MAPPER.setSerializationInclusion(JsonInclude.Include.ALWAYS); + // 取消默认转换 timestamps 形式 + OBJECT_MAPPER.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); + // 忽略空 bean 转 JSON 的错误 + OBJECT_MAPPER.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); + // 所有的日期格式都统一为以下的样式:yyyy-MM-dd HH:mm:ss + OBJECT_MAPPER.setDateFormat(new SimpleDateFormat(STANDARD_FORMAT)); + // 忽略在 JSON 字符串中存在,但是在 java 对象中不存在对应属性的情况 + OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + } + + public static ObjectMapper om() { + return OBJECT_MAPPER; + } + + /** + * 对象转为 JsonNode 实例 + * + * @param obj 要转换的对象 + * @param 要转换的对象类型 + * @return {@link JsonNode}实例 + */ + public static JsonNode obj2JsonNode(T obj) { + try { + return OBJECT_MAPPER.readTree(obj2String(obj)); + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + } + + /** + * 对象转为 JSON 字符串 + * + * @param obj 要转换的对象 + * @param 要转换的对象类型 + * @return JSON 字符串 + */ + public static String obj2String(T obj) { + if (obj == null) { + return ""; + } + try { + return obj instanceof String ? (String) obj : OBJECT_MAPPER.writeValueAsString(obj); + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + } + + /** + * 对象转为格式化的 JSON 字符串 + * + * @param obj 要转换的对象 + * @param 要转换的对象类型 + * @return 格式化的 JSON 字符串 + */ + public static String obj2StringPretty(T obj) { + if (obj == null) { + return ""; + } + try { + return obj instanceof String ? (String) obj : OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(obj); + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + } + + /** + * 字符串转换为自定义对象 + * + * @param str 要转换的字符串 + * @param clazz 自定义对象的 class 对象 + * @param 自定义对象类型 + * @return 自定义对象 + */ + public static T string2Obj(String str, Class clazz) { + if (Strings.isNullOrEmpty(str) || clazz == null) { + throw new RuntimeException("json string to obj param should not empty"); + } + try { + return clazz.equals(String.class) ? (T) str : OBJECT_MAPPER.readValue(str, clazz); + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + } + + /** + * 字符串转换为自定义对象 + * + * @param str 要转换的字符串 + * @param typeReference 集合对象 typeReference + * @param 集合对象类型 + * @return 自定义对象 + */ + public static T string2Obj(String str, TypeReference typeReference) { + if (Strings.isNullOrEmpty(str) || typeReference == null) { + throw new RuntimeException("json string to obj param should not empty"); + } + try { + return typeReference.getType().equals(String.class) ? (T) str : OBJECT_MAPPER.readValue(str, typeReference); + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + } + + /** + * 字符串转换为自定义对象 + * + * @param str 要转换的字符串 + * @param collectionClazz 集合 class + * @param elementClazzes 集合对象 class + * @param 集合对象类型 + * @return 自定义对象 + */ + public static T string2Obj(String str, Class collectionClazz, Class... elementClazzes) { + JavaType javaType = OBJECT_MAPPER.getTypeFactory().constructParametricType(collectionClazz, elementClazzes); + try { + return OBJECT_MAPPER.readValue(str, javaType); + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + } + + /** + * 测试类 + */ + static class User { + private Integer id; + private String email; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + } + + public static void main(String[] args) { + try { + User user1 = new User(); + user1.setId(1); + user1.setEmail("xrv@live.com"); + + String userJsonstr = JsonUtils.obj2String(user1); + System.out.println(userJsonstr); + + String userJsonPretty = JsonUtils.obj2StringPretty(user1); + System.out.println(userJsonPretty); + + User user2 = JsonUtils.string2Obj(userJsonstr, User.class); + user2.setId(2); + user2.setEmail("ehlxr.me@gmail.com"); + + List userList = new ArrayList<>(); + userList.add(user1); + userList.add(user2); + String userListJson = JsonUtils.obj2String(userList); + System.out.println(userListJson); + + List userListBean = JsonUtils.string2Obj(userListJson, new TypeReference>() { + }); + if (userListBean != null) { + userListBean.forEach(user -> System.out.println(user.getId() + " : " + user.getEmail())); + } + List userListBean2 = JsonUtils.string2Obj(userListJson, List.class, User.class); + if (userListBean2 != null) { + userListBean2.forEach(user -> System.out.println(user.getId() + " : " + user.getEmail())); + } + + // Map body = ImmutableMap.of("mobile", "13211111222", "realName", "realName"); + Map body = new HashMap() { + { + put("mobile", "13211111222"); + put("realName", "realName"); + + } + }; + + + String obj2String = JsonUtils.obj2String(body); + System.out.println(obj2String); + + Map stringStringMap = JsonUtils.string2Obj(obj2String, new TypeReference>() { + }); + + stringStringMap.forEach((k, v) -> System.out.println(k + " : " + v)); + + JsonNode jsonNode = JsonUtils.obj2JsonNode(userList); + System.out.println(jsonNode.path(0)); + } catch (Exception e) { + e.printStackTrace(); + } + + } +} + + diff --git a/src/test/java/io/github/ehlxr/es/SpringbootEsApplicationTests.java b/src/test/java/io/github/ehlxr/es/SpringbootEsApplicationTests.java index a0bb1a8..efae391 100644 --- a/src/test/java/io/github/ehlxr/es/SpringbootEsApplicationTests.java +++ b/src/test/java/io/github/ehlxr/es/SpringbootEsApplicationTests.java @@ -1,9 +1,23 @@ package io.github.ehlxr.es; +import io.github.ehlxr.es.utils.JsonUtils; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.ToString; +import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; +import org.elasticsearch.action.bulk.BulkRequest; +import org.elasticsearch.action.bulk.BulkResponse; +import org.elasticsearch.action.index.IndexRequest; +import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; +import org.elasticsearch.action.support.master.AcknowledgedResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; +import org.elasticsearch.client.indices.GetIndexRequest; +import org.elasticsearch.common.unit.TimeValue; +import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.aggregations.AggregationBuilders; import org.elasticsearch.search.aggregations.Aggregations; @@ -16,6 +30,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.io.IOException; +import java.util.stream.IntStream; @SpringBootTest class SpringbootEsApplicationTests { @@ -23,8 +38,62 @@ class SpringbootEsApplicationTests { @Autowired private RestHighLevelClient restHighLevelClient; + @Data + @AllArgsConstructor + @NoArgsConstructor + @ToString + static class User { + private String name; + private Integer gender; + private Integer age; + private String email; + } + @Test - void searchData() throws IOException { + void indexTest() throws IOException { + IndexRequest request = new IndexRequest("my_idx"); + request.id("10"); + request.ifSeqNo(); + request.source(JsonUtils.obj2String(new User("zhansan", 1, 23, "zhansan@test.com")), XContentType.JSON); + + IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT); + System.out.println(response); + } + + @Test + void deleteIndexTest() throws IOException { + GetIndexRequest getIndexRequest = new GetIndexRequest("my_idx"); + boolean exists = restHighLevelClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT); + if (exists) { + DeleteIndexRequest request = new DeleteIndexRequest("my_idx"); + request.timeout(TimeValue.timeValueMinutes(2)); + + AcknowledgedResponse response = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT); + System.out.println(response.isAcknowledged()); + } + } + + @Test + void bulkTest() throws IOException { + BulkRequest request = new BulkRequest("my_idx"); + + IntStream.range(0, 10).forEach(i -> { + IndexRequest indexRequest = new IndexRequest("my_idx") + .id("" + i) + .source(JsonUtils.obj2String(new User("zhansan" + 1, i % 2, 20 + i, i + "zhansan@test.com")), XContentType.JSON); + + System.out.println(indexRequest.toString()); + request.add(indexRequest); + }); + + + BulkResponse response = restHighLevelClient.bulk(request, RequestOptions.DEFAULT); + System.out.println(response.hasFailures()); + } + + + @Test + void searchTest() throws IOException { /* * GET bank/_search * {