您的位置:首页 > 其它

Solrj 7.0.1 学习总结(一)使用solrj进行文档提交

2017-11-16 12:24 225 查看
在solrj 7.0.1 API中,没有SolrServer,所有的request都由SolrClient发送,用来处理与solr的连接和对话。

request以SolrRequests的形式发送,并以SolrResponses的形式返回。

使用solr中自带的jetty。

向solr中提交数据:

①方式一:

String baseUrl = "http://localhost:8983/solr/core";
HttpSolrClient solrClient = new HttpSolrClient.Builder(baseUrl).withConnectionTimeOut(10000)
.withSocketTimeout(60000).build();
SolrInputDocument document = new SolrInputDocument();
document.addField("id",1001);
document.addField("name","katherineeeee");
solrClient.add(document);
solrClient.commit();


②方式二:

String baseUrl = "http://localhost:8983/solr";
HttpSolrClient solrClient = new HttpSolrClient.Builder(baseUrl).withConnectionTimeOut(10000)
.withSocketTimeout(60000).build();
SolrInputDocument document = new SolrInputDocument();
document.addField("id",1001)
document.addField("name","katherineeeee");
solrClient.add("core",document);
solrClient.commit("core");


方式一与方式二的唯一区别在于baseUrl中是否明确指定core或者collection。

如果baseUrl中以指定core,但是使用SolrClient的add(String collection, SolrInputDocument doc)方法,则会出现以下错误

org.apache.solr.client.solrj.impl.HttpSolrClient$RemoteSolrException:

Error from server at http://192.168.37.130:8983/solr/core: Expected mime type application/octet-stream but got text/html.

<html>

<head>

<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>

<title>Error 404 Not Found</title>

</head>

<body><h2>HTTP ERROR 404</h2>

<p>Problem accessing /solr/core/core/update. Reason:

<pre>    Not Found</pre></p>

</body>

</html>


如果baseUrl中未指定core,但是使用add(SolrInputDocument doc)方法,则会出现以下错误

org.apache.solr.client.solrj.impl.HttpSolrClient$RemoteSolrException:**

<html>

<head>

<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>

<title>Error 404 Not Found</title>

</head>

<body><h2>HTTP ERROR 404</h2>

<p>Problem accessing /solr/update. Reason:

<pre>    Not Found</pre></p>

</body>

</html>


两种错误都会导致404。

③方式三:

Solrj支持@Field注解,指定bean的一个字段为field,schema.xml中必须有相应的field元素与之对应,否则报错。

public class Core{
@Field
private Integer id;
@Field
private String name;
}

可使用client的addBean()方法和commit()方法。
同样的,需要注意,如果在baseUrl中没有指定core,则在加入bean和commit时需要加入一个字符串参数,指明具体的core,否则找不到。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  solr