Lucene基础入门讲解
创建索引
环境:
- 需要下载Lucene
- http://lucene.apache.org/
- 最低要求jdk1.8
工程搭建:
- 创建一个java工程
添加jar:
- lucene- analyzers- common-7.4.0. jar
- lucene-core-7.4.0.jar
- commons-io. jar
步骤:
- 创建- -个Director对象,指定索引库保存的位置。
- 基于Directory对象创建一 个IndexWriter对象
- 读取磁盘上的文件,对应每个文件创建一个文档对象。
- 向文档对象中添加域
- 把文档对象写入索引库
- 关闭indexwriter对象
- 取文档列表
- 打印文档中的内容
- 关闭IndexReader对象
- 使用luke查看索引库中的内容
查询索引库
步骤:- 创建一个Director对象,指定索引库的位置
- 创建一个IndexReader对 象
- 创建一-个IndetSearcher对象,构造方法中的参数indexReader对象。
- 创建一个Query对象,TermQuery
- 执行查询,得到一个TopDocs对象
- 取查询结果的总记录数
创建索引参考最后代码的第一个方法。
luke可以自行下载,如果之前下载的Lucene版本是及比较新的,里面应该会含有luke。
双击luke.bat即可运行,(注意前提条件是,电脑已经安装了jdk)package cn.neu.lucene;
import org.apache.commons.io.FileUtils;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.*;
import org.apache.lucene.search.*;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.junit.Test;
import java.io.File;
/** * @Author WCJ * @Description **/
public class LuceneFirst {
@Test
public void createIndex() throws Exception{
Directory directory = FSDirectory.open(new File("D:\\1_download_install\\my\\lucene\\indexDemo1").toPath());
IndexWriter indexWriter = new IndexWriter(directory,new IndexWriterConfig());
File dir = new File("D:\\1_download_install\\my\\lucene\\test");
File[] files = dir.listFiles();
for (File f : files) {
String name = f.getName();
String path = f.getPath();
String content = FileUtils.readFileToString(f,"utf-8");
long size = FileUtils.sizeOf(f);
Field fieldName = new TextField("name",name, Field.Store.YES);
Field fieldPath = new TextField("path",path, Field.Store.YES);
Field fieldContent = new TextField("content",content, Field.Store.YES);
Field fieldSize = new TextField("size",size+"", Field.Store.YES);
Document document = new Document();
document.add(fieldName);
document.add(fieldPath);
document.add(fieldContent);
document.add(fieldSize);
indexWriter.addDocument(document);
}
indexWriter.close();
}
@Test
public void searchIndex()throws Exception{
Directory directory = FSDirectory.open(new File("D:\\1_download_install\\my\\lucene\\indexDemo1").toPath());
IndexReader indexReader = DirectoryReader.open(directory);
IndexSearcher indexSearcher = new IndexSearcher(indexReader);
Query query = new TermQuery(new Term("content","java"));
TopDocs topDocs = indexSearcher.search(query,10);//n:最大返回记录数
System.out.println("查询总记录数:"+topDocs.totalHits);
ScoreDoc[] scoreDocs = topDocs.scoreDocs;
for (ScoreDoc sd : scoreDocs) {
int id = sd.doc;
Document d = indexSearcher.doc(id);
System.out.println(d.get("name"));
System.out.println(d.get("size"));
System.out.println(d.get("path"));
System.out.println(d.get("content"));
System.out.println("--------------寂寞的分割线-------------");
}
indexReader.close();
}
}
还没有评论,来说两句吧...