Pim*_*kos 10 lucene fuzzy-search wildcard
在Lucene查询语法中,我想在有效查询中组合*和〜,类似于:bla~*//无效查询
含义:请匹配以"bla"开头的单词或类似"bla"的单词.
更新:我现在所做的,适用于小输入,使用以下(SOLR模式的片段):
<fieldtype name="text_ngrams" class="solr.TextField">
<analyzer type="index">
<tokenizer class="solr.WhitespaceTokenizerFactory"/>
<filter class="solr.WordDelimiterFilterFactory" generateWordParts="1" generateNumberParts="1" catenateWords="1" catenateNumbers="1" catenateAll="0" splitOnCaseChange="0"/>
<filter class="solr.LowerCaseFilterFactory"/>
<filter class="solr.EdgeNGramFilterFactory" minGramSize="2" maxGramSize="15" side="front"/>
</analyzer>
<analyzer type="query">
<tokenizer class="solr.WhitespaceTokenizerFactory"/>
<filter class="solr.WordDelimiterFilterFactory" generateWordParts="1" generateNumberParts="1" catenateWords="0" catenateNumbers="0" catenateAll="0" splitOnCaseChange="0"/>
<filter class="solr.LowerCaseFilterFactory"/>
</analyzer>
Run Code Online (Sandbox Code Playgroud)
如果您不使用SOLR,则执行以下操作.
Indextime:通过创建包含my(短)输入的所有前缀的字段来索引数据.
搜索时间:仅使用〜运算符,因为前缀明确存在于索引中.
在lucene的开发主干(尚未发布)中,有代码通过AutomatonQuery来支持这样的用例.警告:API可能会/会在发布之前发生变化,但它会为您提供想法.
以下是您案例的示例:
// a term representative of the query, containing the field.
// the term text is not so important and only used for toString() and such
Term term = new Term("yourfield", "bla~*");
// builds a DFA that accepts all strings within an edit distance of 2 from "bla"
Automaton fuzzy = new LevenshteinAutomata("bla").toAutomaton(2);
// concatenate this DFA with another DFA equivalent to the "*" operator
Automaton fuzzyPrefix = BasicOperations.concatenate(fuzzy, BasicAutomata.makeAnyString());
// build a query, search with it to get results.
AutomatonQuery query = new AutomatonQuery(term, fuzzyPrefix);
Run Code Online (Sandbox Code Playgroud)
我不相信 Lucene 支持这样的事情,也不相信它有一个简单的解决方案。
“模糊”搜索不适用于固定数量的字符。bla~例如可能匹配blah,因此它必须考虑整个术语。
您可以做的是实现一个查询扩展算法,该算法接受查询bla~*并将其转换为一系列 OR 查询
bla* OR blb* OR blc OR .... etc.
Run Code Online (Sandbox Code Playgroud)
但这实际上只有在字符串非常短或者您可以根据某些规则缩小扩展范围时才可行。
或者,如果前缀的长度是固定的,您可以添加一个带有子字符串的字段并对其执行模糊搜索。这会给你你想要的东西,但只有当你的用例足够窄时才会起作用。
您没有具体说明为什么需要这个,也许这样做会引出其他解决方案。
我能想到的一种情况是处理不同形式的单词。例如寻找car和cars。
这在英语中很容易,因为有词干分析器可用。在其他语言中,实现词干分析器即使不是不可能,也可能非常困难。
但是,在这种情况下,您可以(假设您可以访问一本好的词典)查找搜索词并以编程方式扩展搜索以搜索该单词的所有形式。
例如,搜索cars被翻译成car OR cars。这已在至少一个搜索引擎中成功应用于我的语言,但实施起来显然并不简单。