// 创建索引
String indexPath = "runtime/tempfiles/";
List<GenericValue> lawAndGuiteGvList = delegator.findAll("LawComplianceFile", false);
Directory dir = FSDirectory.open(Paths.get(indexPath));
IndexWriterConfig iwc = new IndexWriterConfig(analyzer);
iwc.setOpenMode(OpenMode.CREATE);
IndexWriter writer = new IndexWriter(dir, iwc);
// GenericValue gv = lawAndGuiteGvList.get(0);
Document doc = new Document();
doc.add(new StringField("fileName", "化学品", Field.Store.YES));
doc.add(new StringField("fileNo", "aa123", Field.Store.YES));
writer.addDocument(doc);
writer.commit();
/*for (GenericValue gv : lawAndGuiteGvList) {
Document doc = new Document();
doc.add(new StringField("fileName", gv.getString("fileName"), Field.Store.YES));
doc.add(new StringField("fileNo", gv.getString("fileNo"), Field.Store.YES));
writer.addDocument(doc);
}*/
writer.close();
// 查找索引
String indexPath = "runtime/tempfiles/";
IndexReader reader = DirectoryReader.open(FSDirectory.open(Paths.get(indexPath)));
IndexSearcher searcher = new IndexSearcher(reader); // 搜索索引
// 1. 把搜索的文本解析成query
// String[] fields = {"fileName"};
QueryParser queryParser = new QueryParser("fileName", analyzer);
Query query = queryParser.parse("化");
System.out.println(query.toString("fileName"));
// 2. 进行查询
TopDocs topDocs = searcher.search(query, 10);
System.out.println("总共有【" + topDocs.totalHits + "】条匹配结果");
// 3. 打印结果
for (ScoreDoc sco : topDocs.scoreDocs) {
int docSn = sco.doc; // 文明当内部编号
Document doc = searcher.doc(docSn); // 根据文档编号取出相应的文档
printDocumentInfo(doc);
}
reader.close();