Lucene的步骤

// 1. 采集数据

BookDao bookDao = new BookDaoImpl();

List<Book> bookList = bookDao.queryBookList();

// 2. 创建Document文档对象

List<Document> documents = new ArrayList<>();

for (Book book : bookList) {

Document document = new Document();

// Document文档中添加Field域

// 图书Id

// Store.YES:表示存储到文档域中

document.add(new TextField("id", book.getId().toString(), Store.YES));

// 图书名称

document.add(new TextField("name", book.getName().toString(), Store.YES));

// 图书价格

document.add(new TextField("price", book.getPrice().toString(), Store.YES));

// 图书图片地址

document.add(new TextField("pic", book.getPic().toString(), Store.YES));

// 图书描述

document.add(new TextField("desc", book.getDesc().toString(), Store.YES));

// 把Document放到list中

documents.add(document);

}

// 3. 创建Analyzer分词器,分析文档,对文档进行分词

Analyzer analyzer = new StandardAnalyzer();

// 4. 创建Directory对象,声明索引库的位置

Directory directory = FSDirectory.open(new File("C:/itcast/lucene/index"));

// 5. 创建IndexWriteConfig对象,写入索引需要的配置

IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_4_10_3, analyzer);

// 6.创建IndexWriter写入对象

IndexWriter indexWriter = new IndexWriter(directory, config);

// 7.写入到索引库,通过IndexWriter添加文档对象document

for (Document doc : documents) {

indexWriter.addDocument(doc);

}

// 8.释放资源

indexWriter.close();

实现搜索

 1. 创建Query搜索对象

 2. 创建Directory流对象,声明索引库位置

 3. 创建索引读取对象IndexReader

 4. 创建索引搜索对象IndexSearcher

 5. 使用索引搜索对象,执行搜索,返回结果集TopDocs

 6. 解析结果集

 7. 释放资源

 分词器的底层:

 语汇单元的形成过程

原文地址:https://www.cnblogs.com/songyinan/p/7400263.html