Lucene "Ends with" query

本文关键字:quot query with Ends Lucene | 更新日期: 2023-09-27 18:21:54

我使用的是带有.net4的lucene.net 2.9.2.2版本。我在找"以"结尾的查询以及路径。如果发生在两者之间。

索引路径:

C:'Users'vj'folder1'lucene'
C:'Users'vj'folder1'lucene'folder1'folder2
C:'Users'vj'folder2'lucene2'folder1'lucene'

索引代码:

new Field("PATH", strPath, Field.Store.YES, Field.Index.NOT_ANALYZED));
//Standard Analyzer
Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_29);
var writer = new IndexWriter(directory, analyzer, true, IndexWriter.MaxFieldLength.LIMITED);

搜索代码:

Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_29);
var queryParser = new QueryParser(Version.LUCENE_29, "PATH", analyzer);
var query = queryParser.Parse(strPath);

搜索查询:folder1'lucene'

预期结果:

C:'Users'vj'folder1'lucene'
C:'Users'vj'folder2'lucene2'folder1'lucene'

如何获得以上结果。我在SO上看到了许多关于相同的但没有一个包含工作代码。

Lucene "Ends with" query

这里有一个示例程序,它提供了您想要的输出。

需要注意的事项:

  • QueryParser默认情况下不允许使用前导通配符(出于性能原因)
  • 未分析字段"Path",因此未使用传递给IndexWriter的分析器
  • StandardAnalyzer去掉了反斜杠,因此程序使用的是保持反斜杠不变的WhitespaceAnalyzer
  • 将Backsplash传递给QueryParser时,需要对其进行转义

希望这对你有帮助。

using System;
using Lucene.Net.Analysis;
using Lucene.Net.Analysis.Standard;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.QueryParsers;
using Lucene.Net.Search;
using Lucene.Net.Store;
namespace TestProgram
{
  class Program
  {
    static void Main(string[] args)
    {
      FSDirectory directory = FSDirectory.Open(@"c:'temp'myindex");
      BuildIndex(directory);
      QueryIndex(directory);
    }
    static void BuildIndex(Directory directory)
    {
      string[] paths = new[]
      {
        @"C:'Users'vj'folder1'lucene'",
        @"C:'Users'vj'folder1'lucene'folder1'folder2",
        @"C:'Users'vj'folder2'lucene2'folder1'lucene'"
      };
      Analyzer analyzer = new WhitespaceAnalyzer();
      using (var writer = new IndexWriter(directory, analyzer, true, IndexWriter.MaxFieldLength.LIMITED))
      {
        foreach (string path in paths)
        {
          Document doc = new Document();
          var field = new Field("Path", path, Field.Store.YES, Field.Index.NOT_ANALYZED);
          doc.Add(field);
          writer.AddDocument(doc);
        }
      }
    }
    private static void QueryIndex(Directory directory)
    {
      string userQueryString = @"folder1'lucene'";
      Analyzer analyzer = new WhitespaceAnalyzer();
      var queryParser = new QueryParser(Lucene.Net.Util.Version.LUCENE_29, "Path", analyzer);
      queryParser.AllowLeadingWildcard = true;
      string queryString = "*" + userQueryString.Replace(@"'", @"''");
      var query = queryParser.Parse(queryString);
      IndexSearcher searcher = new IndexSearcher(directory);
      IndexReader reader = searcher.IndexReader;
      TopDocs topDocs = searcher.Search(query, 100);
      foreach (ScoreDoc doc in topDocs.ScoreDocs)
      {
        string path = reader.Document(doc.Doc).Get("Path");
        Console.WriteLine(path);
      }
      Console.ReadKey();
    }
  }
}