javacurlsolrsolrj

How to Add/Update in Solr


I am trying to access solr using a java program and add/update records using it (which essentially creates a HttpUrlConnection and Posts json data using curl).

While I should be able to receive response in my java program, I am getting a File not found error. Being a total newbie to this, the error doesnt seem to make sense to me.

Here is part of my code

 String url = "http://localhost:8983/solr/jcg/update?stream.body";
 URL obj = new URL(url);
 HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
 conn.setRequestProperty("Content-Type:", "application/json");
 conn.setRequestProperty("Accept", "*/*");
 conn.setDoOutput(true);
 conn.setRequestMethod("POST");
 String data ="{\"id\":\"978-0641723445\",\"apple_t\":\"set\":\"abc\"}";
 OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
 out.write(data);
 out.close();
 System.out.println(url+data);
 new InputStreamReader(conn.getInputStream());
 System.out.println("input"+conn.getInputStream());
 System.out.println(conn.getContent());
 } catch (Exception e) {
e.printStackTrace();
}

Any other approaches/inputs are welcome. Could somebody help to decipher the error?


Solution

  • HttpURLConnection Version

    try{    
        String url = "http://localhost:8983/solr/jcg/update/json?commit=true";
        URL obj = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Accept", "*/*");
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        String data ="[{\"id\":\"978-0641723445\",\"apple_t\":{\"set\":\"abc\"}}]";
        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
        out.write(data);
        out.close();
        System.out.println("input: "+conn.getInputStream());
    } catch (Exception e) {
        e.printStackTrace();
    }
    

    Using solrj. I used version 5.3.0.

    Add New Document

    String urlString = "http://localhost:8983/solr/jcg";
    SolrClient client = new HttpSolrClient(urlString);
    SolrInputDocument doc1 = new SolrInputDocument();
    doc1.addField( "id", "new-document-id" );
    Collection<SolrInputDocument> docs = new ArrayList<SolrInputDocument>();
    docs.add( doc1 );
    client.add( docs );
    client.commit();
    client.close();
    

    Update Existing Document

    String urlString = "http://localhost:8983/solr/jcg";
    SolrClient client = new HttpSolrClient(urlString);
    SolrInputDocument doc1 = new SolrInputDocument();
    Map<String, String> operations = new HashMap<String, String>();
    operations.put("set", "abc");
    doc1.addField("id", "978-0641723445");
    doc1.addField("apple_t", operations);
    Collection<SolrInputDocument> docs = new ArrayList<SolrInputDocument>();
    docs.add( doc1 );
    client.add( docs );
    client.commit();
    client.close();