通过 Solr 取得分词

原文出处:http://blog.chenlb.com/2010/08/get-solr-analysis-word.html

Solr 1.3 只有 AnalysisRequestHandler 处理器,只能提交文档来观察文档的分词结果。 Solr 1.4 有了对字段的分词。FieldAnalysisRequestHandler 可以对某个字段或字段类型的分词器对查询串取到分词数据。

用 solr 的默认配置,如 solr 1.4.1

我用 mmseg4j 为例。在 solr.root/example/solr/conf/schema.xml 的 types 元素内加:

  1. <fieldType name="text_cn" class="solr.TextField" positionIncrementGap="100">  
  2.   <analyzer>  
  3.     <tokenizer class="com.chenlb.mmseg4j.solr.MMSegTokenizerFactory"/>  
  4.   </analyzer>  
  5. </fieldType>  
    <fieldType name="text_cn" class="solr.TextField" positionIncrementGap="100">       <analyzer>         <tokenizer class="com.chenlb.mmseg4j.solr.MMSegTokenizerFactory"/>       </analyzer>     </fieldType> 

mmseg4j-all-1.8.2-with-dic.jar 放到 solr.home/example/solr/lib,没有 lib 目录,创建一个。更多关于 solr 中使用 mmseg4j 的内容请看:solr 中文分词 mmseg4j 使用例子

如:“中国工商银行”
http://localhost:8983/solr/analysis/field?q=%E4%B8%AD%E5%9B%BD%E5%B7%A5%E5%95%86%E9%93%B6%E8%A1%8C&analysis.fieldtype=text_cn&indent=on&wt=json

  1. {  
  2.  "responseHeader":{  
  3.   "status":0,  
  4.   "QTime":0},  
  5.  "analysis":{  
  6.   "field_types":{  
  7.     "text_cn":{  
  8.      "query":[  
  9.       "com.chenlb.mmseg4j.analysis.MMSegTokenizer",[{  
  10.          "text":"中国",  
  11.          "type":"word",  
  12.          "start":0,  
  13.          "end":2,  
  14.          "position":1},  
  15.         {  
  16.          "text":"工商",  
  17.          "type":"word",  
  18.          "start":2,  
  19.          "end":4,  
  20.          "position":2},  
  21.         {  
  22.          "text":"银行",  
  23.          "type":"word",  
  24.          "start":4,  
  25.          "end":6,  
  26.          "position":3}]]}},  
  27.   "field_names":{}}}  
{  "responseHeader":{   "status":0,   "QTime":0},  "analysis":{   "field_types":{ 	"text_cn":{ 	 "query":[ 	  "com.chenlb.mmseg4j.analysis.MMSegTokenizer",[{ 		 "text":"中国", 		 "type":"word", 		 "start":0, 		 "end":2, 		 "position":1}, 		{ 		 "text":"工商", 		 "type":"word", 		 "start":2, 		 "end":4, 		 "position":2}, 		{ 		 "text":"银行", 		 "type":"word", 		 "start":4, 		 "end":6, 		 "position":3}]]}},   "field_names":{}}} 

就可以取得查询串的分词结果。

这个功能可以解决,如搜索“清华大学” 找不到 “清华 大学” 文档的问题。这个问题的根本原因是 lucene / solr 使用的查询解析器生成的 Query 是短语查询。短语查询默认又是连续的词中没有其它字符。所以会找不到。

目前我知的方式大概有二种:

1、查询前分词一遍,把分出的词用空格分开,再去搜索(叫它为查询预处理)。查询前分词可以上面的接口。

2、扩展 solr query parser,返回 boolean query。

当然还有同学回复说指定短语的距离,如 "清华大学~100",这个可以投机使用,不够可靠。

posted @ 2010-08-30 10:38  searchDM  阅读(846)  评论(0编辑  收藏  举报