繼上一篇,solr啓動成功後,使用java來簡單操作下solr的數據,也就是solr中的Document。
首先我們創建一個core來用於測試,創建core的方式見博文 Apache solr入門中的創建core章節。
- 這裏我們創建一個test_core用於來測試
- 在 managed-schema文件中添加兩個簡單的字段(test_id, test_name)用於測試,如下:(也可以直接在界面操作添加字段)
<field name="test_id" type="string" uninvertible="true" indexed="true" required="true" stored="true"/>
<field name="test_name" type="string" uninvertible="true" indexed="true" stored="true"/>
- 修改默認的主鍵爲我們新建的test_id字段,修改managed-schema文件中的內容如下:(這個步驟非必須,只是在這裏記錄下怎麼修改sor的主鍵爲自定義主鍵。自定義主鍵字段類型必須爲string)
<!-- 定義主鍵字段 -->
<uniqueKey>test_id</uniqueKey>
<!-- id字段是solr默認的主鍵字段 -->
<field name="id" type="string" multiValued="false" indexed="true" required="false" stored="false"/>
- 重啓solr,讓新添加的字段生效
- 先添加maven依賴
<dependency>
<groupId>org.apache.solr</groupId>
<artifactId>solr-solrj</artifactId>
<version>7.7.2</version>
</dependency>
添加/更新Document
操作很簡單,這裏就直接附上代碼,如下:(更新索引沒有特殊的update操作,只需要保證id是已存在的,直接執行add操作即可更新對應的數據)
public static void addDocument(){
SolrInputDocument solrDocument = new SolrInputDocument();
solrDocument.addField("test_id","1");
solrDocument.addField("test_name", "張三");
HttpSolrClient client = new HttpSolrClient.Builder("http://192.168.94.123:8983/solr/test_core").build();
try {
client.add(solrDocument);
client.commit();
client.close();
System.out.println("添加成功");
} catch (Exception e) {
e.printStackTrace();
}
}
刪除Document
public static void deleteDocument(){
HttpSolrClient client = new HttpSolrClient.Builder("http://192.168.94.123:8983/solr/test_core").build();
try {
client.deleteById("1");
client.commit();
client.close();
System.out.println("刪除成功");
} catch (Exception e) {
e.printStackTrace();
}
}
查詢數據
參數數據就很簡單了,主要用到的類是SolrQuery,然後就是設置過濾條件了,可以參見之前的博文java操作solr----雙core關聯查詢,這裏雖然講的是雙core關聯查詢,但是單core查詢也是如此,更簡單了,自己動動腦筋想一下,印象更深刻哦