论坛首页 Java企业应用论坛

用Solr服务器建索引

浏览 2582 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-04-10   最后修改:2009-04-10
Solr 最初由 CNET Networks 开发,2006 年初,Apache Software Foundation 在 Lucene 顶级项目的支持下得到了 Solr。Solr 于 2007 年 1 月酝酿成熟,在整个项目孵化期间,Solr 稳步地积累各种特性并吸引了一个稳定的用户群体、贡献者和提交人。Solr 现在是 Lucene(Apache 的基于 Java 的全文本搜索引擎库)的一个子项目。

用Solr服务器建索引的前提是你已经把Solr服务器给搭建起来了

public class CreateIndex {
public static final String LINE_SEP = System.getProperty("line.separator");

public static final String localhost = "http://10.0.0.201:8080/solr/update";

String command = "<add>" + LINE_SEP + "<doc>" + LINE_SEP
+ "<field name=\"url\">" + "http://www.caihongtang.com/" + "</field>"
+ LINE_SEP
+ "<field name=\"title\">" + "倍感亲切" + "</field>"
+ LINE_SEP
+ "<field name=\"keywords\">" + "倍感的亲切" + "</field>"
+ LINE_SEP
+ "<field name=\"description\">" + "倍感" + "</field>"
+ LINE_SEP
+ "<field name=\"content\">" + "倍感亲切" + "</field>"
+ LINE_SEP
+ "<field name=\"pagerank\">" + 0 + "</field>"
+ LINE_SEP
+ "</doc>" + LINE_SEP + "</add>";

void doIndex() {
try {
System.out.println(command);
doPost(command);
doPost("<commit/>");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

String doPost(String command) throws Exception {
String results = null;
HttpClient client = new HttpClient();
PostMethod post = new PostMethod(localhost);

RequestEntity re = new StringRequestEntity(command, "text/xml", "UTF-8");
post.setRequestEntity(re);
try {
int statusCode = client.executeMethod(post);

if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " + post.getStatusLine());
}

byte[] responseBody = post.getResponseBody();

results = new String(responseBody);
} catch (Exception e) {

System.err.println("Fatal protocol violation: " + e.getMessage());
e.printStackTrace();

} finally {
post.releaseConnection();
}
return results;
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
CreateIndex cr = new CreateIndex();
cr.doIndex();
}

}

以上代码是用HttpClient来解决HTTP客户端与服务器进行通讯编程问题的,就是把你想要建的索引转变成XML文件,把这个XML文件传到http://10.0.0.201:8080/solr/update这个地址,这个URL地址就是solr服务器的所在地址,然后把建索引的事就全交给Solr来处理就行了,Solr已经把Lucene又封装了一编,所以Solr会自己调用Lucene来把传入的数据建索引。
至于输出索引的路径,那就得看Solr的配置了。
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics