lucene5(1)简单示例

NO BIBI亮代码

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;
// lucene索引存放了路径
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 ramDirectory= new RAMDirectory();//索引写入内存
// 索引存储磁盘位置
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);
// 通过reader可以有效的获取到文档的数量
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);
// 指定Document被搜索的属性
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();
}