【www.gdgbn.com--php入门】

对已经创建的索引进行查询,即是搜索,这包括两个部份,一是如何直接读取某个索引的所有记录,二是如果对某个索引进行搜索。

一、列出索引里的文档
列出索引需引入的类或包
<%@ page import = "org.apache.lucene.document.*" %>
<%@ page import = "org.apache.lucene.index.*" %>
<%@ page import = "org.apache.lucene.store.*" %>
<%@ page import = "org.apache.lucene.util.Version" %>

索引目录
String indexPath = request.getRealPath("网站目录");
IndexReader reader = null;
long startTime = (new java.util.Date()).getTime();  
   
打开索引
try {
    reader = IndexReader.open( FSDirectory.open(new File(indexPath)) , true );
}
catch (Exception e) {
    ;
}

版本:<%=reader.getVersion()%> 文档:<%=pagination.getTotalResult()%> 个


TermDocs tdocs = reader.termDocs();
int i = 0;
while( tdocs.next() )
{
    i++;
           
    Document doc = reader.document( tdocs.doc() );
           
    String docid = doc.get("id");
    String title = doc.get("title");
    String area = doc.get("shadowtime");
   
    ....

}

二、搜索索引

除了上面引入的包外,还需要引入
<%@ page import = "org.apache.lucene.search.*" %>
<%@ page import = "org.apache.lucene.queryParser.*" %>

//索引目录
String indexPath = request.getRealPath("网站目录");
   
Analyzer analyzer = new IKAnalyzer();
   
IndexSearcher searcher = null;
IndexReader reader = null;
Query query = null;
TopDocs hits = null;

//打开索引目录
try
{
    reader = IndexReader.open( FSDirectory.open(new File(indexPath)) , true );
    searcher = new IndexSearcher(reader);
}
catch (Exception e)
{
    return;
}

执行查询
try

    //多字段搜索,这里要搜索多少个字段就要有多个个参数
    BooleanClause.Occur[] clauses = { BooleanClause.Occur.SHOULD, BooleanClause.Occur.SHOULD };
   
    String[] fieldnames = new String[] { "title", "content"};
    IKQueryParser ikquery = new IKQueryParser();
    query = ikquery.parseMultiField(fieldnames, queryString , clauses);
                   
    //获取分词结果(这个只是便于对搜索结果输出加亮之类,并非必要选项)
    String wd = "";
    Reader r = new StringReader(queryString);
    org.apache.lucene.analysis.TokenStream tsi = analyzer.tokenStream("", r);
    org.apache.lucene.analysis.Token token;
    while ( tsi.incrementToken() )
    {
        wd = tsi.toString().replaceAll("\(\(|,(.*)", "");
        spword += (spword=="" ? wd : "," + wd );
    }
    tsi.close();
   
}
catch (Exception e)
{                       
     return ;
}

读取搜索结果
hits = searcher.search(query, 0);
for (int i = startindex; i < hits.totalHits; i++)
{
    if(i >= hits.totalHits) { break; }
           
    Document doc = searcher.doc(hits.scoreDocs[i].doc);
           
    String docid = doc.get("id");
    String title = doc.get("title");
  
   .....................

}

本文来源:http://www.gdgbn.com/jiaocheng/23246/