solr同义词

版权声明:本文为博主原创文章,未经博主允许不得转载 https://blog.csdn.net/gs_albb/article/details/82975608

当用户输入"马甲"时,能够搜索到文本中包含"马夹"的结果,这就是solr同义词的作用。

text_ik类型字段引入同义词

managed-schema.xml文件中定义text_ik类型,text_ik字段类型使用的是ik分词器,这里不做展开叙述。

<fieldType name="text_ik" class="solr.TextField">  
	<analyzer type="index" useSmart="false" >  
	  <tokenizer class="org.wltea.analyzer.lucene.IKTokenizerFactory"/>  
	  <!--索引时使用同义词过滤器-->
	  <filter class="solr.SynonymGraphFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true"/>  
	</analyzer>  
	<analyzer type="query" useSmart="true" >  
	   <tokenizer class="org.wltea.analyzer.lucene.IKTokenizerFactory"/>  
	   <!--查询时使用同义词过滤器-->
	   <filter class="solr.SynonymGraphFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true"/>   
	</analyzer>  
</fieldType>  

在managed-schema文件的同级目录下,找到synonyms.txt文件(没有就新建),增加同义词。

特别说明,如果是solrcloud模式,managed-schema文件和synonyms.txt文件都在zookeeper上。如果是solr模式,相关文件在solr服务安装目录下。

增加同义词的方式如下 ,每行一个同义词映射,要么用英文逗号分隔,有么用特殊符号=>分隔。如果有多个词(大于2个)互为同义词,全写在一行,用逗号分隔即可。

# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

#-----------------------------------------------------------------------
#some test synonym mappings unlikely to appear in real input text
aaafoo => aaabar
bbbfoo => bbbfoo bbbbar
cccfoo => cccbar cccbaz
fooaaa,baraaa,bazaaa

# Some synonym groups specific to this example
GB,gib,gigabyte,gigabytes
MB,mib,megabyte,megabytes
Television, Televisions, TV, TVs
#notice we use "gib" instead of "GiB" so any WordDelimiterGraphFilter coming
#after us won't split it into two words.

# Synonym mappings can be used for spelling correction too
pixima => pixma

需要特别注意的是,每一组同义词,输入输出效果是等价的。比如在synonyms.txt的第一行输入 马甲,马夹 ,这表示查询马甲等价于查询马夹,查询马夹也等价于查询马甲。但是现实并不是那么友好。

默认的ik分词词库会对马甲 ik分词为 马甲 一个词条,但是对 马夹 却分词为 马 和 夹 两个单独的词条,这直接导致搜索 马夹 等价于搜索 马 OR 夹,同义词发挥不了作用。

一个解决方式就是,将 马夹 定义为 扩展词,加入到ext.dic文件中。扩展词的作用这里也不做额外说明。

其实上文中定义text_ik字段类型时,存在优化的空间,没有必要在索引时使用同义词过滤器,只要查询时设置了同义词过滤器,就可以发挥同义词查询的作用。

猜你喜欢

转载自blog.csdn.net/gs_albb/article/details/82975608
今日推荐