Friday, November 05, 2010

Simple SOLR example code to index & search metadata

Roughly three years back, I did some a prototype to index/search unstructured content inside enterprise. At that time we are using Autonomy. So nobody cared. Basically all search engines does some kind of structured content searches & major focus on unstructured content i.e. PDF files to WS word document etc. So coming to the point, again I was asked to some prototyping. This time I am looking to solr framework because my C++ business tire makes requests to index/searches for content (mostly un structured content.) after downloading Solr, looking for some good examples. At the end, I started writing the following. I will port this kind of example with using CURL.


protected URL solrUrl;
public CommonsHttpSolrServer solr = null;

public SolrServer startSolrServer() throws MalformedURLException,
SolrServerException
{
solr = new CommonsHttpSolrServer("http://localhost:8983/solr/");
solr.setParser(new XMLResponseParser());

return solr;
}

public TestQueryTool()
{
//will add more junk later
}


public static void main(String[] args)
{

TestQueryTool t = new TestQueryTool();
try
{
//1)start & work with existing SOLR instance
t.startSolrServer();

// 2)Now index content ( files later. metadata)
t.indexBOAsDocument("uid1","bolt", "0001");
t.indexBOAsDocument("uid2","nut", "0002");

//3)now perform search
t.performSearch("uid");

} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SolrServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}


private void indexBOAsDocument(String uid, String id, String name)throws SolrServerException
{
SolrInputDocument doc = new SolrInputDocument();

doc.addField("id", uid);
doc.addField("part_name", name);
doc.addField("part_id", id);

try {
solr.add(doc);
solr.commit();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


public void performSearch(String qstring) throws SolrServerException
{
SolrQuery query = new SolrQuery();
//query.setQuery( "*:*" );

query.setQuery("id:uid* OR part_name:nut");

query.addSortField( "part_name", SolrQuery.ORDER.desc);
QueryResponse response = solr.query(query);
SolrDocumentList docs = response.getResults();
info("docs size is ="+docs.size());
Iterator iter =docs.iterator();

while (iter.hasNext()) {
SolrDocument resultDoc = iter.next();

String part_name = (String) resultDoc.getFieldValue("part_name");
String id = (String) resultDoc.getFieldValue("id"); //id is the uniqueKey field
// Now you got id, part_name. End of story
}

}

No comments: