【问题标题】:String json to elasticSearch SearchResponse object?字符串 json 到 elasticSearch SearchResponse 对象?
【发布时间】:2019-12-02 15:51:53
【问题描述】:

我有来自 elasticsearch rest 客户端的 json 响应。我想从该字符串(json)创建 elasticsearch SearchResponse 或 GetResponse 对象,以便我可以重用 grails-2.4.3 elasticsearch 插件中的非编组部分。有人可以帮我吗?

【问题讨论】:

    标签: grails elasticsearch


    【解决方案1】:

    我不确定这个问题是否仍然相关,但这个问题对我有用:

    String responseJson = "{\"took\":5,\"timed_out\":false,\"_shards\".....}";
    try {
      JsonXContentParser xContentParser = new JsonXContentParser(NamedXContentRegistry.EMPTY,
      new JsonFactory().createParser(responseJson));      
      SearchResponse response = SearchResponse.fromXContent(xContentParser);
      ... 
      Do Whatever
      ...
    } catch (IOException e) {
      handleException....
    }
    

    【讨论】:

      【解决方案2】:

      我确实设法找到了可以帮助你的东西。

      我写了一个这样的 JSON:

      XContentBuilder builder = XContentFactory.jsonBuilder();
      response.toXContent(builder, ToXContent.EMPTY_PARAMS);
      String result = Strings.toString(builder);
      

      然后我设法像这样阅读它:

       try {
           NamedXContentRegistry registry = new NamedXContentRegistry(getDefaultNamedXContents());
           XContentParser parser = JsonXContent.jsonXContent.createParser(registry, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, result);
           SearchResponse searchResponse = SearchResponse.fromXContent(parser);
       } catch (IOException e) {
           System.out.println("exception " + e);
       } catch (Exception e) {
           System.out.println("exception " + e);
       }
      
      public static List<NamedXContentRegistry.Entry> getDefaultNamedXContents() {
          Map<String, ContextParser<Object, ? extends Aggregation>> map = new HashMap<>();
          map.put(TopHitsAggregationBuilder.NAME, (p, c) -> ParsedTopHits.fromXContent(p, (String) c));
          map.put(StringTerms.NAME, (p, c) -> ParsedStringTerms.fromXContent(p, (String) c));
          List<NamedXContentRegistry.Entry> entries = map.entrySet().stream()
                  .map(entry -> new NamedXContentRegistry.Entry(Aggregation.class, new ParseField(entry.getKey()), entry.getValue()))
                  .collect(Collectors.toList());
          return entries;
      }
      

      希望它有效:)

      【讨论】:

        猜你喜欢
        • 2018-09-22
        • 1970-01-01
        • 1970-01-01
        • 2014-03-26
        • 2021-12-31
        • 2011-01-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多