Lucene搜索器小测

来源:互联网 发布:去优酷广告软件 编辑:程序博客网 时间:2024/05/21 09:14

 

使用发现prase只有为单个的字或者词的时候才能搜索到。

这个问题在黑皮书Page52有提及。

 

 

package yixiaoyang;

 

import java.io.IOException;

 

import javax.swing.JOptionPane;

// 引入lucene的包

import org.apache.lucene.document.*;

import org.apache.lucene.search.*;

import org.apache.lucene.index.*;

// 引入工具包

import tools.*;

 

/*

 * @param         args

 * @author         Yi Xiaoyang

 * @date        2010.2.23

 * @note        class to search with the index file

 *                         using the package: lucene-core-2.4.1.jar

 */

 

public class LuceneSearcher {

 

//-----------------------------------------------------------------

// Author:        tianen + YiXiaoyang

// Date:        2010.2.23

// note:        搜索类。参数为搜索关键词和索引存放路径

//-----------------------------------------------------------------

static class LuceneSearcherTool

{

public static void search(String phrase, String indexPath) throws IOException

{

System.out.println("indexPath = " + indexPath + ",phrase = " + phrase);

// 搜索器

IndexSearcher searcher = new IndexSearcher(indexPath);

// 搜索content字段

Term term = new Term("content",phrase);

// 生成Query对象

Query query = new TermQuery(term);

// 获取搜索的结果

Hits hits = searcher.search(query);

 

// 显示搜索结果

int num = hits.length();

String msg = "搜索到" + num + "个结果:/n";

System.out.println(msg);

for( int i = 0; i < num; i++)

{

// get doc

Document doc = hits.doc(i);

if(doc == null)

continue;

 

// 获取各个字段

//---------------------------------------------------------------------

// filename字段

// url字段,资源路径

// date字段

//size字段

//content字段

//digest摘要,只取200字

//---------------------------------------------------------------------

String fileName = doc.getField("fileName").stringValue();

String url = doc.getField("url").stringValue();

String digest = doc.getField("digest").stringValue();

String date = doc.getField("date").stringValue();

String content = doc.getField("content").stringValue();

 

System.out.println("fileName: " + fileName +

 "/nurl: " + url +

                                                                  "/ndigest: " + digest +

                                                                  "/ndate: " + date +

                                                                  "/ncontent: " + content + "/n------------------------------");

}

 

searcher.close();

}

 

 

public static void main(String[] args)

{

// 要搜索的内容

String phrase = JOptionPane.showInputDialog(null, "输入关键字:");

String indexPath = "e://dest";

// System.out.println("prhase = " + phrase);

try {

LuceneSearcherTool.search(phrase, indexPath);

} catch (IOException e) {

System.out.println( "搜索失败!");

e.printStackTrace();

}

}

}

}

 

 

 

运行结果如图所示:

 

 

 

Oh,god!CSDN编辑图片额有点问题。贴不上来了.....