1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| private IndexWriter writer; private IndexReader reader;
private static final String INDEX_DIR = "E:/LuceneIndex";
public IndexWriter getIndexWriter(String indexDir) throws Exception { if (writer == null) { Analyzer analyzer = getAnalyzer(); IndexWriterConfig writerConfig = new IndexWriterConfig(analyzer); Directory directory = FSDirectory.open(Paths.get(indexDir)); writer = new IndexWriter(directory, writerConfig); } return writer; }
public IndexReader getIndexReader(String indexDir) throws IOException { if (reader == null) { Directory directory = FSDirectory.open(Paths.get(indexDir)); reader = DirectoryReader.open(directory); System.out.println("当前存储的文档数:" + reader.numDocs()); System.out.println("当前存储的文档数,包含回收站的文档:" + reader.maxDoc()); System.out.println("回收站的文档数:" + reader.numDeletedDocs()); } return reader; }
public void close() throws Exception { writer.close(); reader.close(); }
private Analyzer getAnalyzer(){ return new StandardAnalyzer(); }
@Test public void testWriter() throws Exception { IndexWriter writer = getIndexWriter(INDEX_DIR); Document document = new Document(); document.add(new TextField("name", "hello world", Field.Store.YES)); document.add(new TextField("describes", "测试luence", Field.Store.YES)); writer.addDocument(document); writer.close(); }
@Test public void testReader() throws Exception { IndexReader reader = getIndexReader(INDEX_DIR); IndexSearcher searcher = new IndexSearcher(reader); QueryParser parser = new QueryParser("describes", getAnalyzer()); Query query = parser.parse("试"); TopDocs hits = searcher.search(query, 10); for (ScoreDoc sd : hits.scoreDocs) { Document doc = searcher.doc(sd.doc); System.out.println(doc.get("name") + "[describes]=" + doc.get("describes")); } reader.close(); }
|