栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

使用Springboot 查询es库

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用Springboot 查询es库

方式一: 1、pom文件依赖
 
            org.elasticsearch.client
            elasticsearch-rest-high-level-client
            6.8.15
        
        
            org.elasticsearch
            elasticsearch
            6.8.15
        
        
            org.apache.commons
            commons-pool2
            2.9.0
        

2、application.yml 配置
#查询配置
snat-es-config:
  indexes: sq_*
  esIp: 127.0.0.1
  esPort: 9200
  username: admin
  password: admin
3、获取配置文件的config的信息
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
​

​
@Configuration
@Data
@ConfigurationProperties(prefix = "snat-es-config")
public class SnatConfig {
​
    
    private String indexes;
​
    
    private String esIp;
​
    
    private int esPort;
    
    private String userName;
    
    private String passWord;
​
}

4、构建Client
    public RestHighLevelClient getClient() {
        RestHighLevelClient client = null;
        String userName = snatConfig.getUserName();
        String userPwd = snatConfig.getPassWord();
        String ip = snatConfig.getEsIp();
        int port = snatConfig.getEsPort();
​
        try {
            
            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(userName, userPwd));
            
            RestClientBuilder builder = RestClient.builder(new HttpHost(ip, port))
                    .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                        @Override
                        public HttpAsyncClientBuilder customizeHttpClient(
                                HttpAsyncClientBuilder httpClientBuilder) {
                            return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                        }
                    });
            client = new RestHighLevelClient(builder);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return client;
    }
5、实现查询业务
   @Test
    public void getSnatDataTest01() throws IOException {
​
​
       RestHighLevelClient client = getClient();
       // 根据索引创建查询请求
       SearchRequest searchRequest = new SearchRequest("sq_*");
​
       SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
​
       // 构建查询语句 可以写多个参数
       searchSourceBuilder.query(QueryBuilders.queryStringQuery("127.0.0.1"))
       .sort("timestamp", SortOrder.fromString("desc"));
       System.out.println("searchSourceBuilder =" + searchSourceBuilder);
       searchRequest.source(searchSourceBuilder);
       SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
       SearchHits hits = response.getHits();
        //将数据打印出来
       System.out.println(JSONObject.toJSON(hits));
    }
6、可能出现的异常
java.lang.NoSuchFieldError: IGNORE_DEPRECATIONS     说明你的pom依赖是 7版本的(依赖版本不对)

方式二:

前提:代码中存在通过HTTP请求的工具,可以直接通过API调用es库来获取数据

 @Test
    public void getSnatDataTest02() throws IOException {
​
        String sandforadBody = "{n" +
                "  "from": 0,n" +
                "  "size": 150,n" +
                "  "query": {n" +
                "    "bool": {n" +
                "      "must": [n" +
                "        {n" +
                "          "query_string": {n" +
                "            "query": "10.42.141.32",n" +
                "            "fields": [],n" +
                "            "use_dis_max": true,n" +
                "            "tie_breaker": 0,n" +
                "            "default_operator": "or",n" +
                "            "auto_generate_phrase_queries": false,n" +
                "            "max_determinized_states": 10000,n" +
                "            "allow_leading_wildcard": true,n" +
                "            "enable_position_increments": true,n" +
                "            "fuzziness": "AUTO",n" +
                "            "fuzzy_prefix_length": 0,n" +
                "            "fuzzy_max_expansions": 50,n" +
                "            "phrase_slop": 0,n" +
                "            "escape": false,n" +
                "            "split_on_whitespace": true,n" +
                "            "boost": 1n" +
                "          }n" +
                "        }n" +
                "      ],n" +
                "      "filter": [n" +
                "        {n" +
                "          "bool": {n" +
                "            "must": [n" +
                "              {n" +
                "                "range": {n" +
                "                  "timestamp": {n" +
                "                    "from": "1970-01-01 00:00:00.000",n" +
                "                    "to": "2022-04-27 08:36:36.120",n" +
                "                    "include_lower": true,n" +
                "                    "include_upper": true,n" +
                "                    "boost": 1n" +
                "                  }n" +
                "                }n" +
                "              }n" +
                "            ],n" +
                "            "should": [n" +
                "              {n" +
                "                "query_string": {n" +
                "                  "query": "streams:5e8456c8df8b291d662c4638",n" +
                "                  "fields": [],n" +
                "                  "use_dis_max": true,n" +
                "                  "tie_breaker": 0,n" +
                "                  "default_operator": "or",n" +
                "                  "auto_generate_phrase_queries": false,n" +
                "                  "max_determinized_states": 10000,n" +
                "                  "enable_position_increments": true,n" +
                "                  "fuzziness": "AUTO",n" +
                "                  "fuzzy_prefix_length": 0,n" +
                "                  "fuzzy_max_expansions": 50,n" +
                "                  "phrase_slop": 0,n" +
                "                  "escape": false,n" +
                "                  "split_on_whitespace": true,n" +
                "                  "boost": 1n" +
                "                }n" +
                "              }n" +
                "            ],n" +
                "            "disable_coord": false,n" +
                "            "adjust_pure_negative": true,n" +
                "            "boost": 1n" +
                "          }n" +
                "        }n" +
                "      ],n" +
                "      "disable_coord": false,n" +
                "      "adjust_pure_negative": true,n" +
                "      "boost": 1n" +
                "    }n" +
                "  },n" +
                "  "sort": [n" +
                "    {n" +
                "      "timestamp": {n" +
                "        "order": "desc"n" +
                "      }n" +
                "    }n" +
                "  ],n" +
                "  "highlight": {n" +
                "    "fragment_size": 0,n" +
                "    "number_of_fragments": 0,n" +
                "    "require_field_match": false,n" +
                "    "fields": {n" +
                "      "*": {}n" +
                "    }n" +
                "  }n" +
                "}";
        String url = "http://192.168.113.99:9200/sq_*/_search";
        //初始化
        HttpRequest sandforadHttpRequest = HttpRequestImpl.getInstance();
        HttpRequestBodyBuilder bodyBuilder = HttpRequestBodyBuilderImpl.getInstance();
        final RequestBody requestBody = bodyBuilder.json(sandforadBody);
        Response post = sandforadHttpRequest.post(url, requestBody);
        String stringPost = post.body().string();
        System.out.println(stringPost);
    }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/842754.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号