Yangrui
Yangrui

Reputation: 1247

Retrieve JSON facet with SolrJ

I use SolrJ along with Json facet API to get facets. However my SolrJ query response object only contained documents, no facets. My facet is a nested structure. Does SolrJ currently support Json facets or I'll need to parse my self?

Furthermore, the facets on child objects only contained counts, no values. How can I get the facet terms, like France, Italy for the below example?

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

Upvotes: 0

Views: 1691

Answers (1)

Halis Yılboğa
Halis Yılboğa

Reputation: 900

You must parse your facet result since it is not too obvious to parse it. You may use response.getResponse().get("facets"); or you may request server directly and parse result by yourself.

direct request may done with method below.

   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 parser is in "javax.json" package but you have to use an implementation of methods which is maven repository for an implementation.

<!-- 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>

below is parsing result directly with java's json parser.

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;
    }

Upvotes: 0

Related Questions