【Lucene最终总结】

package org.itat.test;

import java.io.File;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

import com.chenlb.mmseg4j.analysis.MMSegAnalyzer;

public class SearcherUtils
{

	private String[] names ={ "美丽的青春", "课程" };
	private String[] contents ={ "漂亮神奇", "数学语文" };
	private Directory directory;

	public void makeIndex()
	{
		try
		{
			// 1,创建索引Directory
			directory = FSDirectory.open(new File("c:/lucene/index"));
			// 2,创建IndexWriter
			IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_35,new MMSegAnalyzer());
			IndexWriter indexWriter = new IndexWriter(directory, config);
			//删除所有索引
			indexWriter.deleteAll();
			// 3,创建文档Document
			Document document = null;
			// 4,为Document添加域Field
			for (int i = 0; i < 2; i++)
			{
				document = new Document();
				document.add(new Field("name", names[i], Field.Store.YES,Field.Index.ANALYZED));
				document.add(new Field("content", contents[i], Field.Store.YES,Field.Index.ANALYZED));
				// 5,通过indexWriter把document添加到索引directory中
				indexWriter.addDocument(document);
			}
			indexWriter.close();
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	public void searchFormIndex(String[] fields,String word)
	{
		try
		{
			// 1.得到索引
			directory = FSDirectory.open(new File("c:/lucene/index"));
			// 2.创建IndexReader
			IndexReader reader = IndexReader.open(directory);
			// 3.根据IndexReader创建IndexSercher
			IndexSearcher indexSearcher = new IndexSearcher(reader);
			// 4.创建搜索的Query
			Analyzer analyzer = new MMSegAnalyzer();
			// 5.多域搜索
			QueryParser parser = new MultiFieldQueryParser(Version.LUCENE_35,fields, analyzer);
			Query query = parser.parse(word);
			// 6.根据sercher搜索并返回TopDocs
			TopDocs topDocs = indexSearcher.search(query, 10);
			// 7.根据TopDocs获取ScoreDoc对象
			ScoreDoc scoreDocs[] = topDocs.scoreDocs;
			for (ScoreDoc scoreDoc : scoreDocs)
			{
				// 8.根据sercher对象和Scoredoc对象获取Document对象
				Document document = indexSearcher.doc(scoreDoc.doc);
				// 9.根据Document对象获取需要的值
				System.out.println(document.get("name") +  document.get("content"));
			}
			reader.close();
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}

}

你可能感兴趣的:(Lucene)