天天看點

java 調用solr伺服器 實作增删改查 及高亮顯示

首先有幾點需要注意

用戶端要調用solr服務,首先要把solr服務端工程啟動,即前面文章講的把solr下的slor.war例子放在tomcat下,進行相關配置,并啟動。

(1)exception in thread "main" org.apache.solr.client.solrj.beans.bindingexception: class: class solr.peoplebean does not define any fields.

是因為使用實體bean添加索引時,沒有在實體屬性上添加 filed注解,導緻solr無法比對

@field("name")

public void setname(string name) {

this.name = name;

}

public string[] getcontent() {

return content;

(2)org.apache.solr.client.solrj.impl.httpsolrserver$remotesolrexception: expected mime type application

是因為當solr有多個core時,solrj操作時沒有指定是哪個core,以下指定使用core0的資料

private final static string url = "http://localhost:80/solr/core0";

httpsolrserver server = new httpsolrserver(url);

(3)exception in thread "main" org.apache.solr.client.solrj.beans.bindingexception: could not instantiate object of class solr.peoplebean

是因為當queryresponse.getbeans(peoplebean.class);方式查詢,并傳回實體bean時,必須有一個空的構造方法

public peoplebean(){//此處應該注意,當queryresponse.getbeans(peoplebean.class);方式查詢,并傳回實體bean時,必須有一個                           空的構造方法

(4)當明明有資料卻查不到時,要注意查詢的字段,是否開啟了索引。即 在shema.xml中是否設定indexed="true"

<field name="id"        type="string"   indexed="true"  stored="true"  multivalued="false" required="true"/>

<field name="name"      type="text_ik"   indexed="true"  stored="false"  multivalued="false" /> 

 <field name="content"      type="text_ik"   indexed="false"  stored="true"  multivalued="true" /> 

其中 indexed="true" 表示開啟索引(當字段不需要被檢索時,最好不要開啟索引,) stored="true"表示存儲原來資料(當字段不被檢索,而隻是需要通過其他字段檢索而獲得時,要設為true)  multivalued="true" 表示傳回多值,如一個傳回多個content,此時要在java代碼中把 content設定 集合或數組類型如 

private string[] content;//多值,對應 multivalued="true"

(5)

需要以下jar包

java 調用solr伺服器 實作增删改查 及高亮顯示

上面的一些jar可以從下載下傳的solr壓縮包中獲得

java 調用solr伺服器 實作增删改查 及高亮顯示
java 調用solr伺服器 實作增删改查 及高亮顯示

其他的就是一些日志依賴jar如,commons-logging-1.1.1.jar,slf4j-log4j12-1.5.8.jar,log4j-1.2.14.jar

下面附上代碼(注意運作代碼時先把solr服務端工程啟動,路徑為http://localhost:80/solr/core0)

工程大概

java 調用solr伺服器 實作增删改查 及高亮顯示

schema.xml檔案

實體peoplebean

增加 索引 solradd

根據索引查詢 solrselect,及高亮顯示字元串(高亮顯示實際上是給指定的字元串添加css樣式)

删除 solrdelete

修改 solrupdate (修改實際上還是增加索引,隻不過指定id,把相同id的filed覆寫掉)

注意先啟動solr服務端,服務端啟動後先http://localhost:80/solr/看看是否啟動成功,

啟動成功後的界面。

java 調用solr伺服器 實作增删改查 及高亮顯示