lucene+1
package test; import dao.wenxianDao; import dao.wenxianDaoImpl; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.*; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.junit.Test; import pojo.Sku; import pojo.wenxian; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; /** * 索引库维护 */ public class TestIndexManager { /** * 创建索引库 */ @Test public void createIndexTest1() throws Exception { // 1. 采集数据 wenxianDao wenxianDao = new wenxianDaoImpl(); List<wenxian> wenxians = wenxianDao.querySkuList(); // 2. 创建Document文档对象 List<Document> documents = new ArrayList<Document>(); for (wenxian wenxian : wenxians) { Document document = new Document(); // Document文档中添加Field域 // 商品Id // Store.YES:表示存储到文档域中 document.add(new StringField("di", wenxian.getDi(), Field.Store.YES)); /** * 是否分词: 是, 因为名称字段需要查询, 并且分词后有意义所以需要分词 * 是否索引: 是, 因为需要根据名称字段查询 * 是否存储: 是, 因为页面需要展示商品名称, 所以需要存储 */ document.add(new TextField("wen", wenxian.getWen(), Field.Store.YES)); //将文档对象放入到文档集合中 // 把Document放到list中 documents.add(document); } // 3. 创建Analyzer分词器,分析文档,对文档进行分词 Analyzer analyzer = new StandardAnalyzer(); // 4. 创建Directory对象,声明索引库的位置 Directory directory = FSDirectory.open(Paths.get("E:\\dir1")); // 5. 创建IndexWriteConfig对象,写入索引需要的配置 IndexWriterConfig config = new IndexWriterConfig(analyzer); // 6.创建IndexWriter写入对象 IndexWriter indexWriter = new IndexWriter(directory, config); // 7.写入到索引库,通过IndexWriter添加文档对象document for (Document doc : documents) { indexWriter.addDocument(doc); } // 8.释放资源 indexWriter.close(); } }
对数据库的内容进行分词存取。