Required Configuration in Solr to get the desired JSON format:
There are cases we need desired JSON format other than the usual format provided by SOLR. Let us see how to get a desired JSON formatted output from Solr.
Steps:
- 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.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" indent="yes" media-type="application/json"/>
<xsl:variable name="count" select="response/result/@numFound"/>
<xsl:template match="response">
<xsl:text>{"relatedContent":{"totalRecords": <xsl:value-of select="$count"/>
</xsl:text> <xsl:text>,"results":[</xsl:text>
<xsl:apply-templates select="result/doc"/>
<xsl:text>]}}</xsl:text>
</xsl:template>
<xsl:template match="result/doc">
<xsl:text>{"title":"</xsl:text><xsl:apply-templates
select="str[@name='title']"/>
<xsl:text>","imageReference":"</xsl:text>
<xsl:apply-templates select="arr[@name='imageReference']"/>
<xsl:text>","imageAltText":"</xsl:text>
<xsl:apply-templates select="str[@name='imageAltText']"/>
<xsl:text>","firstName":"</xsl:text>
<xsl:apply-templates select="str[@name='firstName']"/>
<xsl:text>","lastName":"</xsl:text><xsl:apply-templates
select="str[@name='lastName']"/>
<xsl:text>"}</xsl:text>
<!-- append comma to all elements except last element-->
<xsl:if test="position()!=last()">
<xsl:text>,</xsl:text>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
No comments:
Post a Comment
If you have any doubts or questions, please let us know.