您的位置:首页 > 其它

Lucene创建索引和索引的基本检索

2017-04-14 10:34 399 查看
Author: 百知教育 gaozhy

注:演示代码所使用jar包版本为 lucene-xxx-5.2.0.jar

lucene索引操作

创建索引代码

try {
// 1. 指定索引文件存储位置
Directory directory = FSDirectory.open(Paths.get("F:/lucene/index/example01"));
// 2. 创建分词器 标准分词器
StandardAnalyzer analyzer = new StandardAnalyzer();
// 3. 创建索引写入器
IndexWriterConfig config = new IndexWriterConfig(analyzer);
config.setOpenMode(OpenMode.CREATE_OR_APPEND); //索引不存在创建,索引存在追加
IndexWriter indexWriter = new IndexWriter(directory, config);
// 4. 创建索引文档
Document document = new Document();
document.add(new Field("id", "2", StringField.TYPE_STORED ));
document.add(new Field("name", "CoreJava实战",StringField.TYPE_STORED  ));
document.add(new Field("content", "百知金牌讲师 胡鑫哲出品",TextField.TYPE_STORED));
// 5. 添加索引
indexWriter.addDocument(document);
// 6. 释放资源
indexWriter.commit();
indexWriter.close();
directory.close();
} catch (Exception e) {
e.printStackTrace();
}


// 索引日期
document.add(new Field("date", DateTools.dateToString(new Date(), Resolution.SECOND),StringField.TYPE_STORED));
// 索引数字
document.add(new IntField("age", 18, Field.Store.YES));


创建的索引文件



lucene索引的检索

索引检索代码

try{
// 1. 获取索引文件
Directory directory = FSDirectory.open(Paths.get("F:/lucene/index/example01"));
// 2. 读取索引文件
IndexReader indexReader = DirectoryReader.open(directory);
// 3. 创建索引检索器
IndexSearcher searcher = new IndexSearcher(indexReader);
// 4. 创建查询条件
QueryParser parser = new QueryParser("content",new StandardAnalyzer()); //第一个参数: 需要检索的域名 第二个参数: 分词器
Query query = parser.parse("百知"); //检索字符串
System.out.println(query.toString());
// 5. 调用检索器检索
TopDocs topDocs = searcher.search(query, 10); //第二个参数:返回结果 10条信息
System.out.println("命中数:"+topDocs.totalHits);
ScoreDoc[] docs = topDocs.scoreDocs;
// 6. 处理查询结果
for (ScoreDoc scoreDoc : docs) {
System.out.print(searcher.doc(scoreDoc.doc).get("id") + " | ");
System.out.print(searcher.doc(scoreDoc.doc).get("name") + " | ");
System.out.print(searcher.doc(scoreDoc.doc).get("content"));
System.out.println();
}
// 7. 释放资源
indexReader.close();
directory.close();
}catch(Exception e){
e.printStackTrace();
}


// 日期检索
String date = searcher.doc(sd.doc).get("date");
if(date != null){
System.out.print(DateTools.stringToDate(date) + " | ");
}
// 数字检索
System.out.println(searcher.doc(sd.doc).get("age"));


检索结果

使用“百知”检索结果



使用“胡鑫哲”检索结果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: