简体   繁体   中英

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.

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);

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}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM