2016-04-25 30 views
0

我使用SolrJ和Json構面API來獲取構面。然而,我的SolrJ查詢響應對象只包含文檔,沒有方面。我的方面是嵌套結構。 SolrJ目前是否支持Json方面,或者我需要解析我的自我?使用SolrJ檢索JSON構面

此外,子對象的構面只包含計數,沒有值。我如何獲得方面條款,如法國,意大利爲下面的例子?

facets={ 
    count=57477, 
    apparels={ 
     buckets= 
     { 
      val=Chanel, 
      count=6, 
      madeIn={ 
       count=6 
      } 
     } 
    } 
} 

回答

0

您必須解析您的方面結果,因爲解析它並不是太明顯。您可以使用response.getResponse().get("facets");或者您可以直接請求服務器並自行解析結果。

直接請求可以用下面的方法完成。

public static InputStream getInputStreamWithPost(final String url) throws Exception { 

    final URL obj = new URL(url); 
    final HttpURLConnection con = (HttpURLConnection) obj.openConnection(); 

    // optional default is POST 
    con.setRequestMethod("POST"); 

    // add request header 
    con.setRequestProperty("User-Agent", 
          "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB;  rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13 (.NET CLR 3.5.30729)"); 
    return con.getInputStream(); 
} 

Java的JSON解析器是「javax.json」方案,但你必須使用的這是一個實現 Maven倉庫方法的實現。

<!-- https://mvnrepository.com/artifact/org.glassfish/javax.json --> 
    <dependency> 
     <groupId>org.glassfish</groupId> 
     <artifactId>javax.json</artifactId> 
     <version>1.0.4</version> 
     <scope>provided</scope> 
    </dependency> 

下面直接用java的json解析器解析結果。

try (final JsonReader rdr = Json.createReader(inputStream)) { 

     final JsonObject jobject = rdr.readObject(); 
     JsonObject jobject1 = jobject.getJsonObject("facets"); 
     jobject1 = jobject1.getJsonObject(metadataName); 
     final JsonArray jsonArray = (jobject1.getJsonArray("buckets")); 

     for (int i = 0; i < jsonArray.size(); i++) { 
      final JsonObject jsonObject = jsonArray.getJsonObject(i); 
      System.out.println(jsonObject.getString("val")); 
      System.out.println(jsonObject.getInt("count")); 
     } 

     return jsonArray; 
    }