lunce创建索引及简单查询

import java.io.File;
import java.io.IOException;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

public class LunceUtil {
	 Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);
	 public  void searchContext(String indexPath,String searchContext) throws IOException{
		
		    Directory  directoryIndex=FSDirectory.open(new  File(indexPath));
			DirectoryReader ireader = DirectoryReader.open(directoryIndex);
		    IndexSearcher isearcher = new IndexSearcher(ireader);
		    QueryParser parser = new QueryParser(Version.LUCENE_CURRENT, "fieldname", analyzer);
		    Query query=null;
			try {
				query = parser.parse(searchContext);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		    ScoreDoc[] hits = isearcher.search(query, null, 10000).scoreDocs;
			for (int i = 0; i < hits.length; i++) {
			    	Document hitDoc=null;
			    	hitDoc = isearcher.doc(hits[i].doc);
			    	System.out.println(hitDoc.get("fieldname"));
			} 
			ireader.close();
			directoryIndex.close();
	   }
	   public  void createIndex(String indexPath,String context) throws IOException{
	//////////////创建索引/////////////////////////////////////////////////
		   
			 IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_CURRENT, analyzer);
			 //来将文档加入索引
			 
		    //生成一个索引写入器
			// Analyzer是分析器,它的作用是把一个字符串按某种规则划分成一个个词语,并去除其中的无效词语,
			IndexWriter iwriter=new IndexWriter(FSDirectory.open(new  File(indexPath)), config);
			/////////////////////////////////////////////////////////////
			//从网站上抓取的内容用户进行搜索创建索引,也是以Document列表的形式返回。
//		    Document doc1 = new Document();
//		    Document doc2=new Document();
//		    String text1 = "Robitussin leyiduo";
//		    String text2="tis a indexed.";
//		    doc1.add(new Field("fieldname", text1, TextField.TYPE_STORED));
//		    doc2.add(new Field("fieldname", text2, TextField.TYPE_STORED));
//			iwriter.addDocument(doc1);
//			iwriter.addDocument(doc2);
			Document doc = new Document();
			doc.add(new Field("fieldname",context,TextField.TYPE_STORED));
			iwriter.addDocument(doc);
			iwriter.close();
	   }
}

你可能感兴趣的:(查询,创建索引,lunce)