Search code examples
javasolrsolrj

Add json data to solr from java


I want to add data to solr 4.0 using java. I have the following array List<Map<String, Object>> docs = new ArrayList<>();. I am converting the array to json object using GSON method. I want to commit this data to solr. How do i do that? I have read solrj but not getting idea how to get it to work.


Solution

  • With the solrj client you create SolrInputDocument objects and post them to SolrServer instance be it a HttpSolrServer or a EmbeddedSolrServer. The SolrInputDocument is a name value pair collection the would be equivalent to the json you are trying to post. As described at https://wiki.apache.org/solr/Solrj#Adding_Data_to_Solr

    If you truly want to send JSON to a Solr server you could use something like the HTTPClient to post the JSON to http://solrHost.com:8983/solr/update/json.

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost postRequest = new HttpPost("http://solrHost.com:8983/solr/update/json");
    StringEntity input = new StringEntity("{\"firstName\":\"Bob\",\"lastName\":\"Williams\"}");
    input.setContentType("application/json");
    postRequest.setEntity(input);
    HttpResponse response = httpClient.execute(postRequest);