Lucene的大致结构图:
信息写入索引库的过程:
读取信息的过程:
下面是一个向索引库写入信息与读取信息的例子:
public void testCreateIndex() throws Exception{ /** * 1、创建一个student对象,并且把信息存放进去 * 2、调用indexWriter的API把数据存放在索引库中 * 3、关闭indexWriter */ // 创建一个Student对象,并且把信息存放进去 Student student = new Student(); student.setId(1L); student.setName("张三"); // 调用indexWriter的API把数据存放在索引库中 /** * 创建一个IndexWriter * 参数三个 1、索引库, 指向索引库的位置 2、分词器 */ // 创建索引库 Directory directory = FSDirectory.open(new File("./indexDir")); // 创建分词器 Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_30); IndexWriter indexWriter = new IndexWriter(directory, analyzer, MaxFieldLength.LIMITED); // 把一个student对象转化成document Document document = new Document(); Field idField = new Field("id",student.getId().toString(),Store.YES,Index.NOT_ANALYZED); Field nameField = new Field("name",student.getName(),Store.YES,Index.ANALYZED); document.add(idField); document.add(nameField); indexWriter.addDocument(document); // 关闭indexWriter indexWriter.close(); }
public void testSearchIndex() throws Exception{ /** * 1、创建一个IndexSearch对象 * 2、调用search方法进行检索 * 3、输出内容 */ // 创建一个 IndexSearch对象 Directory directory = FSDirectory.open(new File("./indexDir")); IndexSearcher indexSearcher = new IndexSearcher(directory); // 调用search方法进行检索 Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_30); QueryParser queryParser = new QueryParser(Version.LUCENE_30,"name",analyzer); Query query = queryParser.parse("张"); // 要查找的关键词 TopDocs topDocs = indexSearcher.search(query, 2); // 前两条 int count = topDocs.totalHits; // 根据关键词查询出来的总的记录数 ScoreDoc[] scoreDocs = topDocs.scoreDocs; List<Student> studentList = new ArrayList<Student>(); for(ScoreDoc scoreDoc:scoreDocs){ float score = scoreDoc.score; // 关键词得分 int index = scoreDoc.doc; // 索引的下标 Document document = indexSearcher.doc(index); // 把document转化成Student Student student = new Student(); student.setId(Long.parseLong(document.get("id"))); // document.getField("id").stringValue() student.setTitle(document.get("name")); studentList.add(student); } for(Student student:studentList){ System.out.println(student.getId()); System.out.println(student.getName()); } }
Author:顾故
Sign:别输给曾经的自己