将json数据添加到java中的solr

时间:2013-02-18 06:41:10

标签: java solr solrj

我想使用java将数据添加到solr 4.0。我有以下数组List<Map<String, Object>> docs = new ArrayList<>();。我正在使用GSON方法将数组转换为json对象。我想将这些数据提交给solr。我怎么做?我已经阅读了solrj,但没有想到如何让它发挥作用。

2 个答案:

答案 0 :(得分:4)

使用solrj客户端,您可以创建SolrInputDocument对象并将它们发布到SolrServer实例,无论是HttpSolrServer还是EmbeddedSolrServer。 SolrInputDocument是一个名称值对集合,它等同于您尝试发布的json。如https://wiki.apache.org/solr/Solrj#Adding_Data_to_Solr

所述

如果您真的想将JSON发送到Solr服务器,您可以使用类似HTTPClient的东西将JSON发布到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);

答案 1 :(得分:2)

要通过Java索引/添加到solr,请尝试此操作。 Solr使用REST之类的API来操作索引数据。

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

成功发布时的回复:

响应文字为{“responseHeader”:{“status”:0,“QTime”:1352}}