代码之家  ›  专栏  ›  技术社区  ›  Judah Gabriel Himango

lucene.net-按int排序

  •  9
  • Judah Gabriel Himango  · 技术社区  · 14 年前

    在lucene(或lucene.net)的最新版本中,怎样才能使搜索结果按顺序返回?

    我有一份这样的文件:

    var document = new Lucene.Document();
    document.AddField("Text", "foobar");
    document.AddField("CreationDate", DateTime.Now.Ticks.ToString()); // store the date as an int
    
    indexWriter.AddDocument(document);
    

    现在我想做一个搜索,并得到我的结果,以最新的顺序。

    如何进行按创建日期排序结果的搜索? 我看到的所有文档都是针对旧的lucene版本的,这些版本使用了现在不推荐使用的api。

    1 回复  |  直到 8 年前
        1
  •  11
  •   Judah Gabriel Himango    8 年前

    在对api做了一些研究和探索之后,我终于找到了一些非弃用的api(截至v2.9和v3.0),它们允许您按日期订购:

    // Find all docs whose .Text contains "hello", ordered by .CreationDate.
    var query = new QueryParser(Lucene.Net.Util.Version.LUCENE_29, "Text", new StandardAnalyzer()).Parse("hello");
    var indexDirectory = FSDirectory.Open(new DirectoryInfo("c:\\foo"));
    var searcher = new IndexSearcher(indexDirectory, true);
    try
    {
       var sort = new Sort(new SortField("CreationDate", SortField.LONG));
       var filter =  new QueryWrapperFilter(query);
       var results = searcher.Search(query, , 1000, sort);
       foreach (var hit in results.scoreDocs)
       {
           Document document = searcher.Doc(hit.doc);
           Console.WriteLine("\tFound match: {0}", document.Get("Text"));
       }
    }
    finally
    {
       searcher.Close();
    }
    

    注意,我正在用长比较对创建日期进行排序。这是因为我将创建日期存储为datetime.now.ticks,它是一个system.int64,或者是c_中的long。