Saturday, February 26, 2011

SolrJ cookbook - Indexing

In SolrJ, there are two approaches to index your document, either manually populate your SolrInputDocument, or add SolJ annotation Field in your POJO domain object.

1. indexing with annotated POJO Bean.
This approach is easy when you start project from scratch, or at least you can access the source code.

1.1 The POJO
import org.apache.solr.client.solrj.beans.Field;

public class Post {
        @Field("id")
 private String id;
        @Field("content")
 private String content;
 
 @Field("created")
 private Date created = new Date();

//getter and setter
}

1.2 indexing POJO Bean
@Service
public class SearchServiceSolr implements SearchService {
 @Autowired
 private SolrServer solrServer;

 @Override
 public void index(Object a) {
  try {
   solrServer.addBean(a);
   solrServer.commit();
  } catch (IOException e) {
   e.printStackTrace();
  } catch (SolrServerException e) {
   e.printStackTrace();
  }
 }
}

2.manually populate your SolrInputDocument
this is a flexible way, although more tedious works.
 Collection docs = new ArrayList();
 public void index(Post post) throws Exception {
  SolrInputDocument doc = new SolrInputDocument();
  doc.addField("id", post.getId());
  doc.addField("title", post.getTitle());
  doc.addField("content", post.getContent());

  docs.add(doc);
  solrServer.add(docs);
                //you can commit it later
  solrServer.commit();
}

0 comments: