當數據庫的數據發生改變的時候,我們不想手動的去重新添加數據庫的數據導solr索引庫中,所以用到定時添加索引。增刪改的數據。現在寫的這些都是基於我之前做的一步步到這來的。
將solr/dist下的solr-dataimporthandler-4.8.1.jar、solr-dataimporthandler-extras-4.8.1.jar這兩個包拷貝到tomcat/webapps/solr/lib下,還有下載apache-solr-dataimportscheduler.jar也拷貝到tomcat/webapps/solr/lib下,下載鏈接apache-solr-dataimportscheduler.jar的下載鏈接。
修改solr\home\mycore\conf下的data-config.xml文件。
<dataConfig> <dataSource type="JdbcDataSource" driver="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/courseman" user="root" password="mysql" /> <document> <entity pk="ID" dataSource="courseman" name="student" query="select * from student WHERE deleteStatus=0 " deltaQuery="select ID from student where createTime > '${dataimporter.last_index_time}'" deletedPkQuery="select ID from student where deleteStatus=1" deltaImportQuery="select * from student where ID='${dataimporter.delta.ID}'" > <field column="ID" name="id" /> <field column="name" name="name" /> <field column="gender" name="gender" /> <field column="major" name="major" /> <field column="grade" name="grade" /> <field column="deleteStatus" name="deleteStatus" /> <field column="createTime" name="createTime" /> <field column="updateTime" name="updateTime" /> </entity> </document> </dataConfig>
- query查詢是指查詢出表里所有的符合條件的數據,因為我的數據庫student表中的數據是根據deleteStatus來查詢的。類型是boolean。這來要查詢的所有符合條件的結果根據實際情況定。也可以是int類型的。是第一次查詢的數據,或者是full-import的數據。
- deltaQuery的意思是,查詢出所有經過修改的記錄的ID,可能是修改,添加,刪除等操作產生的 (這里查詢只對增量導入起作用,即查詢的是新增的數據,而且只能返回ID值) 。
- deletedPkQuery查詢那些數據庫里偽刪除的數據的ID。這里deleteStatus=1,刪除狀態為1,表示刪除的數據。創建索引的時候不會將這些數據添加進來。
- deltaImportQuery該查詢是獲取以上兩步的ID,然后把其全部數據獲取,根據獲取的數據 對索引庫進行更新操作,可能是刪除,添加,修改 (該查詢只對增量導入起作用,可以返回多個字段的值,一般情況下,都是返回所有字段的列) ,即通過2、3步的查詢結果,進行匹配.
假如deltaQuery滿足條件有5條數據,deletedPkQuery滿足條件有3條數據,那么這5條數據就會被更新進來,這3條數據呢就會被刪除掉,原有的數據還存在。是根據原有的數據更新的。具體是怎么樣的還有待研究。
在tomcat\webapps\solr\WEB-INF\web.xml加入這句話:
<listener> <listener-class>org.apache.solr.handler.dataimport.scheduler.ApplicationListener</listener-class> </listener>
這個class是在apache-solr-dataimportscheduler.jar包下的。
在solr\home文件下創建conf文件夾,原本是沒有的,要自己創建。不是solr\home\mycore\conf。啟動tomcat的時候他會去找solr目錄下home\conf。如果沒有找到,啟動報錯,訪問不到路徑,報404錯。
他是根據這個配置的。
<?xml version="1.0" encoding="utf-8"?> <Context docBase="D:\work-tool\server\solr\server\solr-4.8.1.war" reloadable="true" > <Environment name="solr/home" type="java.lang.String" value="D:\work-tool\server\solr\home" override="true" /> </Context>
D:\work-tool\server\solr\home\conf\dataimport.properties
在這個conf文件下創建dataimport.properties並添加內容
interval=1 port=8983 server=localhost params=/dataimport?command=delta-import&clean=false&commit=true webapp=solr reBuildIndexInterval=1 syncEnabled=1 reBuildIndexBeginTime=03:10:00 reBuildIndexParams=/dataimport?command=full-import&clean=true&commit=true syncCores=mycore
interval:
port:solr的端口
server:solr的路徑
webapp:solr名稱
syncCores:索引庫位置,可以多個,用逗號隔開。
apache-solr-dataimportscheduler的源代碼里面有個錯誤,應該把POST請求改為GET請求。不然他會報415錯誤。