当前位置:   article > 正文

springboot使用ES查询_spriongboot查询es数据库

spriongboot查询es数据库
  1. 第一步:导入依赖
  2. <!--es缓存依赖-->
  3. <dependency>
  4. <groupId>org.elasticsearch.client</groupId>
  5. <artifactId>elasticsearch-rest-high-level-client</artifactId>
  6. </dependency>
  7. <dependency>
  8. <groupId>com.alibaba</groupId>
  9. <artifactId>fastjson</artifactId>
  10. <version>1.2.83</version>
  11. </dependency>
  12. 第二步:创建文档需要的实体类
  13. package com.example.demousermanagement.beans;
  14. import lombok.AllArgsConstructor;
  15. import lombok.Data;
  16. import lombok.NoArgsConstructor;
  17. @Data
  18. @AllArgsConstructor
  19. @NoArgsConstructor
  20. public class Products {
  21. private String id;
  22. private String type;
  23. private String name;
  24. private String desc;
  25. }
  26. 第三步:测试---创建索引、用分词器创建索引、添加单个文档、添加多个文档、查询
  27. @Slf4j
  28. @SpringBootTest
  29. class DemoUserManagementApplicationTests {
  30. //声明es客户端
  31. private RestHighLevelClient highLevelClient;
  32. public RestHighLevelClient restClient() {
  33. log.info("Elasticsearch init start ......");
  34. RestHighLevelClient restClient = null;
  35. try {
  36. final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  37. credentialsProvider.setCredentials(AuthScope.ANY,
  38. new UsernamePasswordCredentials("elastic", "123456MQL"));
  39. SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
  40. // 信任所有
  41. public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
  42. return true;
  43. }
  44. }).build();
  45. SSLIOSessionStrategy sessionStrategy = new SSLIOSessionStrategy(sslContext, NoopHostnameVerifier.INSTANCE);
  46. restClient = new RestHighLevelClient(
  47. RestClient.builder(
  48. new HttpHost("localhost", 9200, "https"))
  49. .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
  50. public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
  51. httpClientBuilder.disableAuthCaching();
  52. httpClientBuilder.setSSLStrategy(sessionStrategy);
  53. httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
  54. return httpClientBuilder;
  55. }
  56. }));
  57. } catch (Exception e) {
  58. log.error("elasticsearch TransportClient create error!!", e);
  59. }
  60. return restClient;
  61. }
  62. @BeforeEach
  63. void setUp(){
  64. //初始化客户端
  65. highLevelClient = restClient();
  66. }
  67. @AfterEach
  68. void tearDown() throws IOException {
  69. highLevelClient.close();
  70. }
  71. @Test
  72. void addIndex() throws IOException {
  73. //创建索引--相当于数据库
  74. CreateIndexRequest request = new CreateIndexRequest("products");
  75. final CreateIndexResponse createIndexResponse = highLevelClient.indices().create(request, RequestOptions.DEFAULT);
  76. log.info(createIndexResponse.toString());
  77. }
  78. /**
  79. * 使用ik分词器创建索引--相当于数据库
  80. */
  81. @Test
  82. public void testIK() throws IOException {
  83. String source = "{\n" +
  84. "\t\"mappings\": {\n" +
  85. "\t\t\"properties\": {\n" +
  86. "\t\t\t\"desc\": {\n" +
  87. "\t\t\t\t\"type\": \"text\",\n" +
  88. "\t\t\t\t\"fields\": {\n" +
  89. "\t\t\t\t\t\"keyword\": {\n" +
  90. "\t\t\t\t\t\t\"type\": \"keyword\",\n" +
  91. "\t\t\t\t\t\t\"ignore_above\": 256\n" +
  92. "\t\t\t\t\t}\n" +
  93. "\t\t\t\t}\n" +
  94. "\t\t\t},\n" +
  95. "\t\t\t\"id\": {\n" +
  96. "\t\t\t\t\"type\": \"long\"\n" +
  97. "\t\t\t},\n" +
  98. "\t\t\t\"name\": {\n" +
  99. "\t\t\t\t\"type\": \"text\",\n" +
  100. "\t\t\t\t\"fields\": {\n" +
  101. "\t\t\t\t\t\"keyword\": {\n" +
  102. "\t\t\t\t\t\t\"type\": \"keyword\",\n" +
  103. "\t\t\t\t\t\t\"ignore_above\": 256\n" +
  104. "\t\t\t\t\t}\n" +
  105. "\t\t\t\t}\n" +
  106. "\t\t\t},\n" +
  107. "\t\t\t\"type\": {\n" +
  108. "\t\t\t\t\"type\": \"text\",\n" +
  109. "\t\t\t\t\"fields\": {\n" +
  110. "\t\t\t\t\t\"keyword\": {\n" +
  111. "\t\t\t\t\t\t\"type\": \"keyword\",\n" +
  112. "\t\t\t\t\t\t\"ignore_above\": 256\n" +
  113. "\t\t\t\t\t}\n" +
  114. "\t\t\t\t}\n" +
  115. "\t\t\t}\n" +
  116. "\t\t}\n" +
  117. "\t}\n" +
  118. "}";
  119. //创建索引
  120. CreateIndexRequest request = new CreateIndexRequest("products");
  121. //给请求对象设置参数
  122. request.source(source, XContentType.JSON);
  123. final CreateIndexResponse createIndexResponse = highLevelClient.indices().create(request, RequestOptions.DEFAULT);
  124. log.info(createIndexResponse.toString());
  125. }
  126. /**
  127. * 创建文档--相当于添加单条表记录
  128. */
  129. @Test
  130. public void testDoc() throws IOException {
  131. try {
  132. IndexRequest request = new IndexRequest("products").id("9");
  133. String json = "{\n" +
  134. "\t\"name\": \"pear32\",\n" +
  135. "\t\"type\": \"9fruit9\",\n" +
  136. "\t\"desc\": \"good foot pear32\"\n" +
  137. "}";
  138. request.source(json, XContentType.JSON);
  139. final IndexResponse index = highLevelClient.index(request, RequestOptions.DEFAULT);
  140. log.info(index.toString());
  141. } catch (Exception e) {
  142. String msg = e.getMessage();
  143. if (!msg.contains("201 Created") && !msg.contains("200 OK")) {
  144. throw e;
  145. }
  146. }
  147. }
  148. /**
  149. * 批量添加文档--相当于批量添加表记录
  150. */
  151. @Test
  152. public void testBulk() throws IOException {
  153. try{
  154. List<Products> list = new ArrayList<>();
  155. list.add(new Products("3", "aaa", "bbb", "ccc"));
  156. list.add(new Products("4", "eee", "fff", "ggg"));
  157. list.add(new Products("5", "hhh", "ggg", "kkk"));
  158. //创建批量请求对象
  159. BulkRequest bulk = new BulkRequest();
  160. for (Products products : list) {
  161. IndexRequest request = new IndexRequest("products").id(products.getId());
  162. String json = JSON.toJSONString(products);
  163. request.source(json, XContentType.JSON);
  164. bulk.add(request);
  165. }
  166. highLevelClient.bulk(bulk, RequestOptions.DEFAULT);
  167. }catch (Exception e){
  168. String msg = e.getMessage();
  169. if (!msg.contains("201 Created") && !msg.contains("200 OK")) {
  170. throw e;
  171. }
  172. }
  173. }
  174. /**
  175. * 根据id查询文档
  176. */
  177. @Test
  178. public void testQueryDocById() throws IOException {
  179. GetRequest request = new GetRequest("products", "3");
  180. GetResponse documentFields = highLevelClient.get(request, RequestOptions.DEFAULT);
  181. String sourceAsString = documentFields.getSourceAsString();
  182. log.info("----" + sourceAsString);
  183. }
  184. /**
  185. * 跟俊其他条件查询
  186. */
  187. @Test
  188. public void testQueryDocByConditions() throws IOException {
  189. //获取条件对象
  190. SearchRequest request = new SearchRequest("products");
  191. //设置文档查询条件
  192. SearchSourceBuilder builder = new SearchSourceBuilder();
  193. builder.query(QueryBuilders.termQuery("type", "aaa"));
  194. request.source(builder);
  195. //执行查询
  196. SearchResponse response = highLevelClient.search(request, RequestOptions.DEFAULT);
  197. SearchHits hits = response.getHits();
  198. for (SearchHit hit : hits) {
  199. String sourceAsString = hit.getSourceAsString();
  200. Products products = JSON.parseObject(sourceAsString, Products.class);
  201. log.info(products.toString());
  202. }
  203. }
  204. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/409873
推荐阅读
相关标签
  

闽ICP备14008679号