Lucene包含两部分内容:创建索引、检索。
package demo.mytest.lucene; import java.io.IOException; import java.nio.file.FileSystems; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; import org.apache.lucene.analysis.tokenattributes.OffsetAttribute; 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.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.IndexWriterConfig.OpenMode; import org.apache.lucene.index.Term; import org.apache.lucene.queryparser.classic.MultiFieldQueryParser; 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.search.TermQuery; import org.apache.lucene.search.TermRangeQuery; import org.apache.lucene.search.TopDocs; import org.apache.lucene.search.highlight.Encoder; import org.apache.lucene.search.highlight.Formatter; import org.apache.lucene.search.highlight.Fragmenter; import org.apache.lucene.search.highlight.Highlighter; import org.apache.lucene.search.highlight.QueryScorer; import org.apache.lucene.search.highlight.Scorer; import org.apache.lucene.search.highlight.SimpleFragmenter; import org.apache.lucene.search.highlight.SimpleHTMLEncoder; import org.apache.lucene.search.highlight.SimpleHTMLFormatter; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.store.IOContext; import org.apache.lucene.store.RAMDirectory; import org.apache.lucene.util.BytesRef; import org.junit.Test; import demo.mytest.lucene.utils.LuceneUtils; public class HelloWorld { public static final String dataDir = "F:\\workspace\\luceneDemo\\dataDir\\CHANGES.txt";//文档所在路径 CHANGES.txt public static final String dataDir2 = "F:\\workspace\\luceneDemo\\dataDir\\bye.txt"; public static final String indexDir = "F:\\workspace\\luceneDemo\\indexDir";//索引文件存储位置 public static final Analyzer analyzer = new StandardAnalyzer(); /** * * testCreateIndex 创建索引库 * * @Description * @throws Exception void * @see */ @Test public void testCreateIndex() throws Exception { IndexWriterConfig config = new IndexWriterConfig(analyzer); config.setOpenMode(OpenMode.CREATE);//设置indexWriter的打开方式,是新建或覆盖(CREATE)?是追加(APPEND)?还是两者结合(CREATE_OR_APPEND)? Directory directory = this.getFsIndexDirectory();//将索引文件保存的指定路径 IndexWriter indexWriter = new IndexWriter(directory, config);//创建indexWriter对象 // indexWriter.deleteAll();//删除索引库的所有文件 Document doc = LuceneUtils.file2Document(dataDir);//处理、转换。将文件转换成文档对象 indexWriter.addDocument(doc); Document doc2 = LuceneUtils.file2Document(dataDir2);//处理、转换。将文件转换成文档对象 indexWriter.addDocument(doc2); indexWriter.close();//用完一定要关闭! /* * 新添加一个Document并不会马上将它的索引写入最终的索引大文件,它的索引会暂时存于缓存。 * 当关闭时,会将缓存中的索引归并到索引大文件。如果此处没有关闭操作,那么刚刚添加的Document的索引不会保存到最终的索引大文件。 */ directory.close(); } /** * * testTermQuery 关键词查询 * @throws IOException * * @Description * @see */ @Test public void testTermQuery() throws IOException { String queryStr = "bye.txt"; Term term = new Term("fileName", queryStr); Query query = new TermQuery(term) ; this.queryAndPrintResult(query); } /** * * testTermRangeQuery 范围查询 * * @Description * @throws IOException void * @see */ @Test public void testTermRangeQuery() throws IOException { Query query = new TermRangeQuery("fileSize",new BytesRef(10),new BytesRef(2000), true, true); this.queryAndPrintResult(query); } /** * * queryAndPrintResult 测试查询对象用到的方法 * * @Description * @throws IOException void * @see */ private void queryAndPrintResult(Query query) throws IOException { Directory directory = this.getFsIndexDirectory();//获取索引文件的存储路径 IndexReader indexReader = DirectoryReader.open(directory); IndexSearcher indexSearcher = new IndexSearcher(indexReader);//从指定的路径的索引库检索指定的文本 TopDocs topDocs = indexSearcher.search(query, 100000); ScoreDoc[] scoreDocs = topDocs.scoreDocs; System.out.println("共有【"+ topDocs.totalHits+"】条查询结果。\n----------------"); //打印文档对象信息 for(int i=0;i",""); Encoder encoder = new SimpleHTMLEncoder(); Scorer fragmentScorer = new QueryScorer(query); Highlighter highlighter = new Highlighter(formatter, encoder, fragmentScorer); //设置高亮器 final int FRAGMENT_SIZE = 50; Fragmenter fragmenter = new SimpleFragmenter(FRAGMENT_SIZE);//每一个fragment的字符长度 highlighter.setTextFragmenter(fragmenter); //-------------------- for(int i=0;i
使用到的工具类:
package demo.mytest.lucene.utils; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.TextField; /** * * LuceneUtils 工具类 * */ public class LuceneUtils { /** * * file2Document 将文件转换成文档对象 * * @Description * @param path * @return * @throws Exception Document * @see */ public static Document file2Document(String path) throws Exception { File file = new File(path); Document doc = new Document(); doc.add(new Field("fileName", file.getName(), TextField.TYPE_STORED)); doc.add(new Field("content", getFileContent(file),TextField.TYPE_STORED)); doc.add(new Field("fileSize", String.valueOf(file.getTotalSpace()), TextField.TYPE_STORED)); doc.add(new Field("path", file.getAbsolutePath(),TextField.TYPE_STORED)); //doc.add(new Field("fileName",String.valueOf(file.getName()),Store.YES, Index.ANALYZED)); System.out.println(file.getAbsolutePath()+"\t"+file.isDirectory()+"\n"+getFileContent(file)); doc.add(new Field("isDirectory",String.valueOf(file.isDirectory()),TextField.TYPE_STORED)); return doc; } /** * * printDocumentInfo 打印文档对象信息 * * @Description 打印文档对象信息 * @param document 文档对象 * void * @see */ public static void printDocumentInfo(Document document) { // IndexableField field = document.getField("fileName"); // System.out.println(field.name() + ":" +field.stringValue());//结果---fileName:CHANGES.txt。此处的document.getField("fileName").stringValue()相当于document.get("fileName") //打印文档对象信息 System.out.println("文档("+document.get("fileName")+")的信息-" +"内容:"+document.get("content")+"\t存储位置:"+document.get("path") +"\t文件大小:" + document.get("fileSize") +"\t是否为文件夹:"+ document.get("isDirectory")); } /** * * getFileContent 取得文件内容 * * @Description * @param file * @return * @throws Exception String * @see */ private static String getFileContent(File file) throws Exception { StringBuffer sbf = new StringBuffer(); BufferedReader br = new BufferedReader(new FileReader(file)); String line = null; while ((line = br.readLine()) != null) { sbf.append(line).append("\n"); } br.close(); return sbf.toString(); } }