Wednesday, July 26, 2017

About SolrJ

Tags
What is SolrJ? when I Saw First , thought of something different when googling came to know that it is not different from Solr but we are contacting the Solr through the StandAlone Java Code . Its nothing but the API that talks to solr through its predefined methods.
When You guys worked on the Endeca, it is as similar as the "Presentation API" . What we have seen in myprevious posts is like the Assembler API or Directly calling the Solr Core for the Responses through the Query Paramaters.

Today I will Show how to write one simple java class that will give the Demo for the SolrJ , same like below Changes you can write for the other predefined methods as well.

package com.mycommercesearch.solr;

import java.io.IOException;
import java.net.MalformedURLException;

import org.apache.commons.codec.EncoderException;
import org.apache.commons.codec.net.URLCodec;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;

public class TestSolrQuery {
 @SuppressWarnings("rawtypes")
 public static void main(String[] args) throws MalformedURLException, SolrServerException {
  HttpSolrClient solrClient = new HttpSolrClient("http://localhost:8983/solr/refrence");

  SolrQuery query = new SolrQuery();
  URLCodec encoder = new URLCodec();

  try {
   query.setQuery(encoder.encode("planes"));

  } catch (EncoderException e1) {
   // TODO Auto-generated catch block
   e1.printStackTrace();
  }
  query.setStart(0);
  query.set("defType", "edismax");

  QueryResponse response = null;
  try {
   response = solrClient.query(query);
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  SolrDocumentList results = response.getResults();
  for (int i = 0; i < results.size(); ++i) {
   SolrDocument docuemnt = results.get(i);
   System.out.println("###################");
   String name = (String) docuemnt.getFieldValue("name");
   int quantity = (int) docuemnt.getFieldValue("quantity");
   String id = (String) docuemnt.getFieldValue("id");
   String productVendor = (String) docuemnt.getFieldValue("productVendor");
   String description = (String) docuemnt.getFieldValue("description");

   System.out.println("\n" + "id=" + id + "name=" + name + "quantity=" + quantity + "productVendor=" + productVendor + "description=");

  }
  try {
   solrClient.close();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}


Happy Learning !!!!!