[Lucene.Net] 分页显示

来源:互联网 发布:2017淘宝卖什么好 编辑:程序博客网 时间:2024/05/17 22:11
很简单,依照以下公式计算几个数据即可。

索引库文档总数
DocumentCount = searcher.Reader.NumDocs();

搜索结果总数 
Count = Hits.Length();

每页记录数 
PageSize;

结果页总数 (注意处理余数)
PageCount = (Count / PageSize) + (Count % PageSize > 0 ? 1 : 0);

要显示的页序号 (当页序号大于页总数时,返回最后一页。)
PageIndex = Math.Min(PageIndex, PageCount);

起始记录序号 (起始序号必须大于等于零)
StartPos = Math.Max((PageIndex - 1) * PageSize, 0);

结尾记录序号 (不能大于记录总数)
EndPos = Math.Min(PageIndex * PageSize - 1, Count - 1);

演示:返回第10页,每页20条记录。
Hits hits = searcher.Search(query);

int pageIndex = 10;
int pageSize = 20;
int count = hits.Length();

if (count > 0)
{
  int pageCount = count / pageSize + (count % pageSize > 0 ? 1 : 0);
  pageIndex = Math.Min(pageIndex, pageCount);
  int startPos = Math.Max((pageIndex - 1) * pageSize, 0);
  int endPos = Math.Min(pageIndex * pageSize - 1, count - 1);

  for (int i = startPos; i <= endPos; i++)
  {
    int docId = hits.Id(i);
    string name = hits.Doc(i).Get(FieldName);
    float score = hits.Score(i);

    Console.WriteLine(" DocId:{0}; Name:{1}; Score:{2}", docId, name, score);
  }

 
原创粉丝点击