Lucene_demo01_FirstProject

Lucene_demo01_FirstProject

lucene版本:3.0.1
导入下面四个包


Junit4测试类:
/**
 * 创建一个索引库,把一个信息加入到索引库中、把信息从索引库中检索出来
 */
public class HelloLuceneWorld {
	/**
	 * 创建索引
	 */
	@Test
	public void createIndex() throws Exception {
		// 1创建article对象
		Article article = new Article();
		article.setId(1L);
		article.setTitle("NBA总决赛");
		article.setContent("LBJ和韦德能带领热火在2013赛季拿到NBA总冠军吗?");

		// 创建索引库,创建IndexWriter对象
		Directory directory = FSDirectory.open(new File("./indexDir"));
		Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_30);
		IndexWriter indexWriter = new IndexWriter(directory, analyzer, MaxFieldLength.LIMITED);

		// 把article对象转化成document、把article对象加入到索引库中
		Document document = new Document();
		Field idField = new Field("id", article.getId().toString(), Store.YES, Index.NOT_ANALYZED);
		Field titleField = new Field("title", article.getTitle(), Store.YES, Index.ANALYZED);
		Field contentField = new Field("content", article.getContent(), Store.YES, Index.ANALYZED);
		document.add(idField);
		document.add(titleField);
		document.add(contentField);

		indexWriter.addDocument(document);// 信息放入到索引库
		indexWriter.close();// 关闭indexWriter
	}

	/**
	 * 进行检索
	 */
	@Test
	public void searchIndex() throws Exception {
		// 创建IndexSearch对象
		Directory directory = FSDirectory.open(new File("./indexDir"));
		IndexSearcher indexSearcher = new IndexSearcher(directory);
		Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_30);
		QueryParser queryParser = new QueryParser(Version.LUCENE_30, "title", analyzer);
		Query query = queryParser.parse("总决赛");// 关键词
		TopDocs topDocs = indexSearcher.search(query, 5);// 第二个参数为n,提取前n条记录
		int count = topDocs.totalHits;// 根据关键词检索出来的总的记录数
		ScoreDoc[] scoreDocs = topDocs.scoreDocs;
		List<Article> articleList = new ArrayList<Article>();
		for (int i = 0; i < scoreDocs.length; i++) {
			int index = scoreDocs[i].doc;
			Document document = indexSearcher.doc(index);
			Article article = new Article();
			article.setId(Long.parseLong(document.get("id")));
			article.setTitle(document.get("title"));
			article.setContent(document.get("content"));
			articleList.add(article);
		}

		// 输出查询到的信息
		for (Article article : articleList) {
			System.out.println(article.getId());
			System.out.println(article.getTitle());
			System.out.println(article.getContent());
		}
	}
}

你可能感兴趣的:(Lucene)