Lucene创建索引和索引的基本检索
2017-04-14 10:34
399 查看
Author: 百知教育 gaozhy
注:演示代码所使用jar包版本为 lucene-xxx-5.2.0.jar
lucene索引操作
创建索引代码
创建的索引文件
lucene索引的检索
索引检索代码
检索结果
使用“百知”检索结果
使用“胡鑫哲”检索结果
注:演示代码所使用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"));
检索结果
使用“百知”检索结果
使用“胡鑫哲”检索结果
相关文章推荐
- lucene series 2 document 文档 索引创建 基本索引操作
- Lucene.Net 创建索引和检索
- Lucene使用(一)简单索引的创建和检索
- 走进lucene - 创建索引、检索
- Lucene的配置及创建索引全文检索
- Lucene.Net 创建索引和检索
- 全文检索工具lucene 之索引创建方法
- Lucene 6.2.1入门教程(一) 创建索引和基本搜索索引
- 全文检索Lucene入门之创建索引及简单搜索
- Lucene 全文检索的基本原理-如何创建索引
- lucene5学习 - 索引基本操作(创建,查询,更新,删除,分页)
- Apache Lucene(全文检索引擎)—创建索引
- lucene5.5创建索引和检索
- Lucene全文检索 之创建索引、增删改查(纯代码)
- lucene学习笔记之索引创建、内容检索、分类器实现
- Lucene.Net 创建索引和检索
- Lucene全文检索技术之如何创建索引
- Lucene创建索引/检索信息
- Lucene全文检索样例(解决大文本建索引)
- 在应用中加入全文检索功能——基于Java的全文索引引擎Lucene简介 [摘]