在solr中,實時搜索有3種方案
①soft commit,這其實是近實時搜索,不能完全實時。 ②RealTimeGet,這是實時,但只支持根據文檔ID的查詢。 ③和第一種類似,只是觸發softcommit。 綜上,其實是由實時(②)和近實時(①③)兩種。
solr4.0 之后使用NRT的方法和需要的配置
方案1
使用soft commit達到近實時搜索的效果。
為了使用soft commit ,需要配置solrconfig.xml。其中兩個地方需要修改
<autoCommit> <maxDocs>10000</maxDocs> <!-- maximum uncommited docs before autocommit triggered --> <maxTime>15000</maxTime> <!-- maximum time (in MS) after adding a doc before an autocommit is triggered --> <openSearcher>false</openSearcher> <!-- SOLR 4.0. Optionally don't open a searcher on hard commit. This is useful to minimize the size of transaction logs that keep track of uncommitted updates. --> </autoCommit>
這里需要將hard commit 的 openSearcher改為true。Hard commit時間根據自己系統承載能力和需要設置。因為hard commit動作較大,對性能有較大影響。原則稍長較好,但又不能太長,以免突然斷電導致大量數據丟失(hard commit前數據都在memery中)。
<!-- SoftAutoCommit Perform a 'soft' commit automatically under certain conditions. This commit avoids ensuring that data is synched to disk. maxDocs - Maximum number of documents to add since the last soft commit before automaticly triggering a new soft commit. maxTime - Maximum amount of time in ms that is allowed to pass since a document was added before automaticly triggering a new soft commit. --> <autoSoftCommit> <maxTime>2000</maxTime> </autoSoftCommit>
將soft commit 打開(默認配置注釋了該節點),這里的時間是你希望在幾秒內搜到,此處我的設置為2s。可根據需要設置,值越小NRT效果越好,相反的,會帶來性能上的影 響。如果索引請求量不是特別大,則可以將值設小點,比如1000.不建議小於1000,小於1000並沒有意義。
設置a,b之后就可通過普通的SearchHandler 搜到到了。Solr 默認配置的SearchHandler REST接口有“/select”“/query”“/browse”。
值得注意的是:當索引請求量巨大時,solr並不一定能保證在你設置的時間內能立馬搜索到最新的文檔,通常會有秒級別的延遲。
方案 2
需要配置solrconfig.xml。其中兩個地方需要修改
<autoCommit> <maxDocs>10000</maxDocs> <!-- maximum uncommited docs before autocommit triggered --> <maxTime>15000</maxTime> <!-- maximum time (in MS) after adding a doc before an autocommit is triggered --> <openSearcher>false</openSearcher> <!-- SOLR 4.0. Optionally don't open a searcher on hard commit. This is useful to minimize the size of transaction logs that keep track of uncommitted updates. --> </autoCommit>
此外還要配置solrconfig.xml的RealTimeGetHandler。根據solr的文檔。該搜索Handler的接口為“/get”。該接口使用了一個特定的組件RealTimeGetComponent,該接口會通用solrCore的 getRealtimeSearcher()方法,后者會先搜索一下updateLog,再做普通搜索。
方案 3
第3種使用NRT的方法依然需要配置NRT1中的a項。這次使用普通的SearchHandler來實現NRT。利用solr的commit和 commitwithin。實現方式是每次索引文檔后都明確的發送一個commit或者commitwithin命令。這樣也可以馬上搜索剛索引的數據。 由於發送命令需要走網絡,時間上有不確定性,總體速度也不如NRT1。這里commit為hard commit請求,方法為commit=true;commitwithin為softcommit請求,方法為commitwithin=2000. 從前所述可以看出同樣是commit,是用commitwithin將能更快搜到新文檔,此處表示2s內要完成softcommit。該方法靈活性較高, 適合在一些特殊情況下使用。
綜上,雖然我們可以通過不同手段(包括變相的手段NRT3)來實現NRT。但NRT1中的配置softcommit的方式才是最佳選擇,這也是其存在的價值。但是在一些特殊的應用場景可以根據需要使用NRT3。比如,索引頻繁而搜索量很小。