1

我需要做一些与 Solr 的同义词匹配。

例如,在瑞典,街道名称通常采用Foogatanwhere gatan 是英语中街道名称的形式。这个街道名称可以写成缩写形式Foog.(有点像你用英文写st.street

我熟悉它的synonyms.txt工作原理,但我不知道如何创建一个同义词来检查它是否包含一些字母 beforegatan或 before g.

我需要一个与 and 匹配的*g.同义词*gatan

我最终这样做了(似乎是我所追求的草稿)

public boolean incrementToken() throws IOException {

    // See http://solr.pl/en/2012/05/14/developing-your-own-solr-filter/

    if (!input.incrementToken()) return false;

    String string = charTermAttr.toString();

    boolean containsGatan = string.contains("gatan");
    boolean containsG = string.contains("g.");

    if (containsGatan) {

        string = string.replace("gatan", "g.");

        char[] newBuffer = string.toCharArray();

        charTermAttr.setEmpty();
        charTermAttr.copyBuffer(newBuffer, 0, newBuffer.length);

        return true;
    }

    if (containsG) {

        string = string.replace("g.", "gatan");

        char[] newBuffer = string.toCharArray();

        charTermAttr.setEmpty();
        charTermAttr.copyBuffer(newBuffer, 0, newBuffer.length);

        return true;
    }

    return false;
}

我还有一个类似的问题是你可以用031-123456和 的形式写电话号码031123456。当搜索像 031123456 这样的电话号码时,它也应该找到031-123456

如何在 Solr 中实现这一点?

4

1 回答 1

0

对于第一个,您可以编写一个自定义TokenFilter并将其连接到您的分析器中(这并不难,看org.apache.lucene.analysis.ASCIIFoldingFilter一些简单的示例)。

第二个可以通过使用来解决:http PatternReplaceCharFilterFactory: //docs.lucidworks.com/display/solr/CharFilterFactories

您必须从数字中删除“-”字符并仅索引/搜索数字。类似的问题: Solr PatternReplaceCharFilterFactory not replace with specified pattern

从每个令牌末尾删除 gatan 的简单示例:

public class Gatanizer extends TokenFilter {

    private final CharTermAttribute termAttribute = addAttribute(CharTermAttribute.class);

    /**
     * Construct a token stream filtering the given input.
     */
    protected Gatanizer(TokenStream input) {
        super(input);
    }

    @Override
    public boolean incrementToken() throws IOException {
        if (input.incrementToken()) {

            final char[] buffer = termAttribute.buffer();
            final int length = termAttribute.length();

            String tokenString = new String(buffer, 0, length);
            tokenString = StringUtils.removeEnd(tokenString, "gatan");

            termAttribute.setEmpty();
            termAttribute.append(tokenString);

            return true;
        }

        return false;
    }

}

我已经注册了我TokenFilter的一些 Solr 领域:

    <fieldtype name="gatan" stored="false" indexed="false" multiValued="true" class="solr.TextField">
        <analyzer>
            <tokenizer class="solr.StandardTokenizerFactory"/>
            <filter class="solr.LowerCaseFilterFactory"/>
            <filter class="solr.ASCIIFoldingFilterFactory"/>
            <filter class="gatanizer.GatanizerFactory"/>
        </analyzer>
    </fieldtype>

你还需要一些简单的东西GatanizerFactory来返回你的Gatanizer

于 2013-09-03T07:50:44.330 回答