Solrj JavaDoc http://lucene.apache.org/solr/4_10_0/solr-solrj/
SolrJ API 隱藏了許多連接到Solr的細節,提供了一個讓Java應用程式能夠跟Solr簡單互動的高層次方法,
如果要使用SolrJ所提供的API
可以先在專案pom.xml檔中加入dependency
<dependency>
<groupId>org.apache.solr</groupId>
<artifactId>solr-solrj</artifactId>
<version>4.10.0</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.directory.studio</groupId>
<artifactId>org.apache.commons.codec</artifactId>
<version>1.8</version>
</dependency>
|
加入後就可以使用solrj提供的API
在SolrJ的主要package是 org.apache.solr.client.solrj ,其中僅包含了五個大類,我們可以通過創建一個SolrServer實例,發送SolrRequests 或SolrQuerys 並取回SolrResponses。
SolrServer本身是抽象的,所以為了要連接到遠端的Solr伺服器,我們需要使用實際實作的HttpSolrServer或CloudSolrServer中的其中一個,並且通過HTTP與Solr雙向溝通。
在HttpSolrServer是使用顯式的solr URL配置,而CloudSolrServer使用zkHost字符串的SolrCloud集群配置。
String urlString = "http://localhost:8983/solr"; HttpSolrServer solr = new HttpSolrServer(urlString); //如果有加驗證系統的話,需要加入填入帳號密碼才得以查詢或進行其它功能 //HttpClientUtil.setBasicAuth((DefaultHttpClient) solr.getHttpClient(), "admin", "admin"); |
String zkHostString = "zkServerA:2181,zkServerB:2181/solr"; CloudSolrServer solr = new CloudSolrServer(zkHostString); //如果有加驗證系統的話,需要加入填入帳號密碼才得以查詢或進行其它功能 //HttpClientUtil.setBasicAuth(solr.getLbServer().getHttpClient(), <username>, <password>); |
當有一個SolrServer,我們就可以透過調用方法,執行查詢、加入和提交
以下提供兩個範例,做為參考
新增索引
public void add() throws SolrServerException, IOException {
SolrServer solr = new HttpSolrServer("http://localhost:8983/solr/db");
SolrInputDocument document = new SolrInputDocument();
document.addField("menu_id", 552199);
document.addField("menu_name", "這是測試");
document.addField("menu_url", "http://test.com");
UpdateResponse response = solr.add(document);
System.out.println(response.getStatus());
solr.commit();
solr.shutdown();
}
|
查詢
public void query() throws SolrServerException {
SolrServer solr = new HttpSolrServer("http://localhost:8983/solr/db");
SolrQuery parameters = new SolrQuery();
parameters.set("q", "管理");
//parameters.set("q", "menu_name:測試");
parameters.set("fl", "*,score");
parameters.set("row", 100);
QueryResponse response = solr.query(parameters);
SolrDocumentList list = response.getResults();
for (SolrDocument doc : list) {
for (String key : doc.keySet()) {
System.out.println(key + ":" + doc.get(key));
}
}
solr.shutdown();
}
|
另外可以用JavaBean的方式加入索引,因為SolrJ不支持巢狀建立索引(一對多),所以無法直接使用配合ORM所建立好的entity來進行處理,折終解決方案還是得要另外建立JavaBean進行轉換。
沒有留言:
張貼留言