多个Lucene查询通配符搜索和邻近匹配



我正在使用Lucene自动完成搜索引擎(RTL语言)中的单词——插入3个字母后调用的自动完成函数。

在调用通配符函数之前,我希望有一个与3个字母查询匹配的接近度。

例如,我想对我的数据库进行子字符串搜索,只搜索每个条目的前3个字母,并将接近度与此比较相匹配。

大概我在找挖掘机,但我也想在我的结果中有小狗,所以如果我已经输入了接近匹配等于1的dig(搜索引擎中的前3个字母)、挖掘机小狗将出现。

我能做到吗?

您可以使用IndexReader的Terms方法来枚举索引中的术语。然后,您可以使用自定义函数来计算这些术语与搜索文本之间的距离。我将使用Levenstein距离进行演示。

var terms = indexReader.ClosestTerms(field, "dig")
                       .OrderBy(t => t.Item2)
                       .Take(10)
                       .ToArray();

public static class LuceneUtils
{
    public static IEnumerable<Tuple<string, int>> ClosestTerms(this IndexReader reader, string field, string text)
    {
        return reader.TermsStartingWith(field, text[0].ToString())
                     .Select(x => new Tuple<string, int>(x, LevenshteinDistance(x, text)));
    }
    public static IEnumerable<string> TermsStartingWith(this IndexReader reader, string field, string text)
    {
        using (var tEnum = reader.Terms(new Term(field, text)))
        {
            do
            {
                var term = tEnum.Term;
                if (term == null) yield break;
                if (term.Field != field) yield break;
                if (!term.Text.StartsWith(text)) yield break;
                yield return term.Text;
            } while (tEnum.Next());
        }
    }
    //http://www.dotnetperls.com/levenshtein
    public static int LevenshteinDistance(string s, string t)
    {
        int n = s.Length;
        int m = t.Length;
        int[,] d = new int[n + 1, m + 1];
        // Step 1
        if (n == 0) return m;
        if (m == 0) return n;

        // Step 2
        for (int i = 0; i <= n; d[i, 0] = i++) { }
        for (int j = 0; j <= m; d[0, j] = j++) { }
        // Step 3
        for (int i = 1; i <= n; i++)
        {
            //Step 4
            for (int j = 1; j <= m; j++)
            {
                // Step 5
                int cost = (t[j - 1] == s[i - 1]) ? 0 : 1;
                // Step 6
                d[i, j] = Math.Min(
                    Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1),
                    d[i - 1, j - 1] + cost);
            }
        }
        // Step 7
        return d[n, m];
    }
}

我想你可以尝试一下,你只需要在接近搜索后添加通配符的搜索条件。

你读过这个吗?http://www.lucenetutorial.com/lucene-query-syntax.html

还可以看看Lucene带边界的邻近搜索?

最新更新