solr默认的分词是按照单词来分的,中文则是按照每个汉字。例如“中国人自强不息”会分为“中”、“国”、“人”、“自”……,这样的分词效果并不理想。
中文分词目前知道“庖丁就牛”这个分词程序比较有名,按照说明文档安装后一直出现“java.lang.AbstractMethodError: org.apache.lucene.analysis.TokenStream.incrementToken()Z",初步判断是版本不兼容的问题,“庖丁解牛”没有发布对应lucene3.5的版本。据说paoding官方源代码是支持的,遂 svn co http://paoding.googlecode.com/svn/trunk/paoding-analysis/,然后 ant build了一份,果然成功了。
简单讲一下配置部署
一、首先部署 solr
昨天文章中讲了如何在Tomcat中部署 solr,这里不重复。
二、下载并配置paoding
上面讲了默认发布的paoding-analysis-2.0.4.jar不兼容lucene-3.5.0,需要按照上面的方法下载源代码,在执行完ant build后能得到 paoding-analysis.jar。
中文分词是依赖词库的,paoding官方提供了一套词库,基本够用,也就是和 src目录在一起的 dic 目录,这个目录在solr运行的时候需要在 $CLASSPATH中。
三、重新打包 solr.war
使用解压工具打开 solr.war,将 paoding-analysis.jar 放在 solr/WEB-INF/lib/下,由于 dic (字典)目录需要在 classpath中,我的做法是直接将其复制到 solr/WEB-INF/classes 目录下,然后打包成新的 solr.war并发布。到这里已经可以重新启动 solr服务了,但还缺少将默认的分词器修改成paoding。
四、配置paoding分词器
昨天文章中提到需要配置 solr/home这个目录,进入这个目录打开 conf/schema.xml。这里就是配置lucene建立索引的字段。这里以测试“subject”字段为例,subject字段的类型是“text_general”,text_general使用的是默认的分词器,修改为使用paoding分词器:
<analyzer type="index" class="net.paoding.analysis.analyzer.PaodingAnalyzer" positionIncrementGap="100">
<tokenizer class="solr.StandardTokenizerFactory"/>
<filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" enablePositionIncrements="true" />
<!-- in this example, we will only use synonyms at query time
<filter class="solr.SynonymFilterFactory" synonyms="index_synonyms.txt" ignoreCase="true" expand="false"/>
-->
<filter class="solr.LowerCaseFilterFactory"/>
</analyzer>
<analyzer type="query" class="net.paoding.analysis.analyzer.PaodingAnalyzer" positionIncrementGap="100">
<tokenizer class="solr.StandardTokenizerFactory"/>
<filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" enablePositionIncrements="true" />
<filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true"/>
<filter class="solr.LowerCaseFilterFactory"/>
</analyzer>
</fieldType>
五、测试
从控制台中直接测试分词效果:http://localhost:8080/solr/admin/analysis.jsp?highlight=on
name: subject 、 Field value: 中华人名共和国 -> 分词结果: 中华、华人、人名、共和、共和国
导入一条数据测试:
~$: vi cn_title.xml
<doc>
<field name="id">test0003</field>
<field name="subject">首先:我为您推荐的这套房子是亦庄里单价最低,户型最好,不临街,性价比最高的一套房屋,如果您想在亦庄置业的话,别再犹豫了,相信自己,相信鑫尊</field>
</doc>
</add>
成功后在solr控制台中搜索:subject:首先 ,并且带上 url 参数:&facet.field=subject&facet=true,查看分词及搜索结果:
