操作流程
1. 創建目錄
mkdir -p /root/solr-test/solr-auto-test
cd /root/solr-test/solr-auto-test
2. 產生collection所需的配置文件
solrctl instancedir --generate ./solr_configs
3. 修改配置文件中的shema.xml和solrconfig.xml
3.1 修改solrconfig.xml
增加如下配置,定義一個searchComponent,
<searchComponent name="suggest" class="solr.SpellCheckComponent">
<lst name="spellchecker">
<str name="name">suggest</str>
<str name="classname">org.apache.solr.spelling.suggest.Suggester</str>
<str name="lookupImpl">org.apache.solr.spelling.suggest.tst.TSTLookup</str>
<str name="field">suggestion</str>
</lst>
</searchComponent>
增加如下配置,加合適的handler,告訴solr每次推薦的最大個數爲10,
<requestHandler name="/suggest" class="org.apache.solr.handler.component.SearchHandler">
<lst name="defaults">
<str name="spellcheck">true</str>
<str name="spellcheck.dictionary">suggest</str>
<str name="spellcheck.count">10</str>
</lst>
<arr name="components">
<str>suggest</str>
</arr>
</requestHandler>
3.2 修改schema.xml
增加關於“單詞補全”和“短語補全”的設置,
<!-- 單詞補全建議-->
<fieldType name="text_spell" class="solr.TextField">
<analyzer type="index">
<tokenizer class="solr.StandardTokenizerFactory"/>
<filter class="solr.LowerCaseFilterFactory"/>
</analyzer>
<analyzer type="query">
<tokenizer class="solr.StandardTokenizerFactory"/>
<filter class="solr.LowerCaseFilterFactory"/>
</analyzer>
</fieldType>
<!-- 完整詞組建議-->
<fieldType class="solr.TextField" name="text_auto_phrase">
<analyzer>
<tokenizer class="solr.KeywordTokenizerFactory"/>
<filter class="solr.LowerCaseFilterFactory"/>
</analyzer>
</fieldType>
增加如下設置,其中的type="text_spell"
表示採用“單詞補全”而不是“短語補全”,
<field name="suggestion" type="text_spell" indexed="true" stored="true" multiValued="true" />
增加如下設置,source="name"
表示需要補全的字段爲“name”,
<copyField source="name" dest="suggestion" />
4. 上傳配置目錄到ZooKeeper
solrctl instancedir --create collection-auto-test ./solr_configs/
若存在的話,則更新,
solrctl instancedir --update collection-auto-test ./solr_configs/
5. 創建新的collection
solrctl collection --create collection-auto-test -s 1 -c collection-auto-test
6. 查看並導入數據
在界面–http://solr-server:8983/solr/#/collection-auto-test_shard1_replica1
查看新創建的collection,不要使用Firefox。
此時,數據爲空,通過下面命令導入。
cd /opt/cloudera/parcels/CDH/share/doc/solr-doc*/example/exampledocs
java -Durl=http://lyhadoop5.haohandata.com:8983/solr/collection-auto-test/update -jar post.jar *.xml
7. 自動補全
注意:
- 當修改了配置文件後,一定要重啓Solr才能生效;自動補全時,插入新數據後,一定要重新build,即勾選“spellcheck”及下面的“spellcheck.build”並執行即可,此時會對所有數據更新index。
- 搜索大寫字母開頭返回結果爲空,要寫成小寫字母。比如要匹配“Hello”,可以輸入“he”
8. 自動補全截圖
更多
已經獲取到推薦的數據了,開發Web就比較容易了,參考鏈接1完成搜索框自動補全的實現。