2012-09-20 39 views
2

我想根據一個字段獲取最近的文章:pubdate。我有這種方法現在:通過Lucene.Net獲取最新文章

 private void GetLastIndexId() 
     { 
      string indexLocation = @"C:\\inetpub\wwwroot\MyWebsite\Data\indexes\newsArticle"; 
      Directory dir = FSDirectory.GetDirectory(indexLocation); 
      IndexReader indexReader = IndexReader.Open(dir); 
      IndexSearcher indexSearch = new IndexSearcher(indexReader); 
      Analyzer analyzer = new StandardAnalyzer(); 
      QueryParser qp = new QueryParser("id", analyzer); 

      Query query = qp.Parse("pubdate: [2012-01-01T00:00:000-00:00 3012-01-01T00:00:000-00:00]"); 
      Hits hits = indexSearch.Search(query); 
List<Document> myHits = new List<Document>(); 
      for (int i = 0; i < hits.Length(); i++) 
       { 
       if (i == hits.Length() - 1) 
        { 
        Document doc = hits.Doc(i); 
        lastPubDate = doc.GetValues("pubdate").First(); 
        } 
       } 

     } 

編輯:我這樣做是在我從內容項獲得長度1項。這是一種破解,因爲如果文件夾結構發生改變,那麼這可能會失敗。

回答

2

您是否試過IndexSearcher.Search重載接受排序參數?

var sortField = new SortField("pubdate", SortField.STRING, /*reverse*/ true); 
var hits = searcher.Search(query, /*filter*/ null, /*count*/ 1, new Sort(sortField)); 
0

我做了這樣的事情:

var sortField = new SortField("pubdate", SortField.STRING, true); 

     for (int i = 0; i < hits.Length(); i++) 
     { 
      Document doc = hits.Doc(i); 
      string getDate = doc.GetValues("pubdate").First(); 

      if (string.Compare(getDate, lastPubDate) > 0) 
      { 
       lastPubDate = doc.GetValues("pubdate").First(); 
      } 
     } 
相關問題