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.
2 Answers
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);
2 Comments
Solr core name?{"add": {"doc":{"userName": "Bill", "stars": 4, "review_id": "-TsVN230RCkLYKBeLsuz7A", "type": "review"}} Or place it in a an array like `[ {your json} ]For indexing/adding to solr by Java, try this. Solr use REST like API to operate the index data.
public void postSolr() {
try{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost("http://localhost:8983/solr/update/json?wt=json&commit=true");
StringEntity entity = new StringEntity("{\"add\": { \"doc\": {\"id\": \"26\",\"keys\": \"java,php\"}}}", "UTF-8");
entity.setContentType("application/json");
post.setEntity(entity);
HttpResponse response = httpClient.execute(post);
HttpEntity httpEntity = response.getEntity();
InputStream in = httpEntity.getContent();
String encoding = httpEntity.getContentEncoding() == null ? "UTF-8" : httpEntity.getContentEncoding().getName();
encoding = encoding == null ? "UTF-8" : encoding;
String responseText = IOUtils.toString(in, encoding);
System.out.println("response Text is " + responseText);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
The response when successfully post:
response Text is {"responseHeader":{"status":0,"QTime":1352}}
2 Comments
?wt=json&commit=true after solr url helped me solve my problem. Otherwise, I was getting no result on executing the query.