本文demo视频观看地址:http://www.wisdomdd.cn/Wisdom/resource/articleDetail.htm?resourceId=1229
索引的创建
1
2
3
4
5
6
7
8
//指定分词技术,这里使用的是标准分词
Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_43);
//indexWriter的配置信息
IndexWriterConfig indexWriteConfig = new IndexWriterConfig(Version.LUCENE_43, analyzer);
//索引的打开方式:没有就创建,有就打开
indexWriteConfig.setOpenMode(OpenMode.CREATE_OR_APPEND);
Directory directory = FSDirectory.open(new File("D://index/test"));
IndexWriter indexWrite = new IndexWriter(directory, indexWriteConfig);
1
2
3
4
5
6
7
8
9
10
Document doc1 = new Document();
//StringField域,当成一个整体,不会被分词
doc1.add(new StringField("id", "abcde", Store.YES));
//TextField域,采用指定的分词技术
doc1.add(new TextField("content", "极客学院", Store.YES));
//将文档写入索引中
indexWrite.addDocument(doc1);
//将indexWrite操作提交,如果不提交,之前的操作将不会保存到硬盘
//但是这一步很消耗系统资源,索引执行该操作需要有一定的策略
indexWrite.commit();
索引的检索
directory = FSDirectory.open(new File("D://index/test")); //索引硬盘存储路径
DirectoryReader dReader = DirectoryReader.open(directory); //读取索引
IndexSearcher searcher = new IndexSearcher(dReader); //创建索引检索对象
Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_43); //分词技术
//创建Query
QueryParser parser = new QueryParser(Version.LUCENE_43, "content", analyzer);
Query query = parser.parse("Lucene案例");
//检索索引,获取符合条件的前10条记录
TopDocs topDocs = searcher.search(query, 10);
閱讀更多 代碼專家 的文章