Sunday, 21 December 2014

JSON tips for SOLR

 Below given set of configuration tips while working with Solr output as JSON

1 How to set the Solr output to JSON?

set media-type as below.
 <xsl:output method="text" indent="no" media-type="application/json"/>

 Below line to be added in solrconfig.xml (if multi core configuration, add below line in solrconfig.xml of each core)
<queryResponseWriter name="xslt" class="org.apache.solr.response.XSLTResponseWriter"/>

Given below a sample JSON response writer. Save it in your /core/conf/xslt folder.

The query should have ‘&wt=xslt&tr=json.xsl’ appended to invoke the required JSON format.


2 How to disable displaying an attribute if its value is zero.

    <xsl:if test="articleDate != ''">
    <xsl:text>","articleDate":"</xsl:text><xsl:apply-templates select="str[@name='articleDate']"/>
    </xsl:if>

3 How to get total number of results of search returned

If the xml/json returned having nodes, <result>, below expression gives the count

<xsl:variable name="count" select="result/@numFound"/>

  Now print the value as

<xsl:value-of select="$count"/></xsl:text>


4 How to add comma to JSON element except last element

Check for the position then insert comma using below logic

        <xsl:if test="position()!=last()">
       <xsl:text>,</xsl:text>
      </xsl:if>

5) Check for a value greater than
     
      <xsl:if test="$count &gt; 8">
        <xsl:text><xsl:value-of select="$count"/> is greater than 8</xsl:text>
      </xsl:if>
     
         
6) check if  a value exists,
     
      <xsl:if test="str[@name='id']">
                    <xsl:text> id exists</xsl:text>               
              
    </xsl:if>

No comments:

Post a Comment