【问题标题】:how to fix NullPointerException while loading document to Elasticsearch 7.3如何在将文档加载到 Elasticsearch 7.3 时修复 NullPointerException
【发布时间】:2020-05-26 18:55:59
【问题描述】:

我想将 JSON 字符串加载到 Elasticsearch 7.3 版。

以下是我为此使用的代码。

    private RestHighLevelClient restHighLevelClient;
    String jsonString="//here the complete JSON string";
    JSONObject jsonObject = new JSONObject(cojsonStringntent1.toString());
    HashMap<String, Object> hashMap = new Gson().fromJson(jsonObject.toString(), HashMap.class);

    IndexRequest indexRequest = new IndexRequest("index", "type").source(hashMap);
    restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);

例外: 线程“主”java.lang.NullPointerException 中的异常 在线restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);

如果我通过 POSTMEN 发布相同的 jsonString,那么它将被完美地加载到 ELASTICSEARCH。

【问题讨论】:

  • 能否提供您的 JSON 字符串和邮递员请求 JSON 以便我自己尝试?
  • 似乎缺少restHighLevelClient 的初始化
  • @Lily,如果您能够解决问题,请告诉我,如果您能够解决问题,请不要犹豫,如果您能够解决问题,请投票并接受答案,以便我们了解您得到了解决方案。
  • @Lily 很长时间以来您都没有接受并支持我的答案,如果您的问题得到解决,如果您能接受并支持答案,那就太好了

标签: json elasticsearch resthighlevelclient


【解决方案1】:

如果你没有使用spring(因为它没有提到),你可以使用下面的简单代码来创建一个resthighlevelclient

在下面的代码中,我正在从配置文件中读取 elasticsearch 配置,请随意将其更改为您读取属性或配置的方式,或者如果您只是想快速测试它,硬编码主机的值和端口

RestHighLevelClient restHighLevelClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost(configuration.getElasticsearchConfig().getHost(),
                        configuration.getElasticsearchConfig().getPort(),
                        "http")));

【讨论】:

    【解决方案2】:

    根据您的示例代码,您的 restHighLevelClient 确实根本没有被初始化。请在下面找到如何解决此问题的代码 sn-p:

        @Bean
    public RestHighLevelClient elasticRestClient () {
        String[] httpHosts = httpHostsProperty.split(";");
        HttpHost[] httpHostsAsArray = new HttpHost[httpHosts.length];
        int index = 0;
    
        for (String httpHostAsString : httpHosts) {
            HttpHost httpHost = new HttpHost(httpHostAsString.split(":")[0], new Integer(httpHostAsString.split(":")[1]), "http");
            httpHostsAsArray[index++] = httpHost;
        }
    
        RestClientBuilder restClientBuilder = RestClient.builder(httpHostsAsArray)
                .setRequestConfigCallback(builder -> builder
                        .setConnectTimeout(connectTimeOutInMs)
                        .setSocketTimeout(socketTimeOutInMs)
                );
    
        return new RestHighLevelClient(restClientBuilder);
    }
    

    并且您的 impl 类使用自动装配的 RestHighLevelClient bean:

        @Autowired
    private RestHighLevelClient restClient;
    

    【讨论】:

      猜你喜欢
      • 2021-10-17
      • 2019-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-22
      • 2020-12-06
      • 1970-01-01
      相关资源
      最近更新 更多