1.analysis数据库
2.core数组
3.highlighter数据结构
4.queryparser搜索引擎
//建立文档对象 Document doc = new Document(); //添加模拟数据 //添加id doc.add(new StringField("id", "11", Store.NO)); //添加title doc.add(new TextField("title", "三分钟学会lucene",Store.YES)); //添加context doc.add(new TextField("content", "倒排索引(也称为倒排文件)是一种存储了来自文本" + "中的映射的索引数据结构。好比单词或者数字,对应到它们在数据库、一个文件或" + "者一组文件中的位置。它是在文档检索系统中使用的最流行的数据结构,在搜索引擎" + "中有大规模使用案例例如咱们使用新华字典查询汉字,新华字典有偏旁部首的目录(索引)," + "咱们查字首先查这个目录,找到这个目录中对应的偏旁部首,就能够经过这个目录中的" + "偏旁部首找到这个字所在的位置(文档)。",Store.NO));
场景1:搜索word文档code
读取文档,将数据变成文档对象,解析成单词,存储索引库,搜索索引库数据,搜索到文档
场景2:查询数据库对象
把数据变成文档对象,解析成单词,放入索引库
场景3:爬虫爬取网页索引
解析网页,把网页数据变成文档对象,索引放入库
//Lucene管理索引存储空间 FSDirectory directory = FSDirectory.open(new File("E:\\Java\\TEMP")); //建立分词器 Analyzer analyzer = new IKAnalyzer(); //建立索引库,引入核心配置文件 IndexWriterConfig writerConfig = new IndexWriterConfig(Version.LUCENE_4_10_3, analyzer); //建立索引库,引入核心文件 IndexWriter indexWriter = new IndexWriter(directory, writerConfig);
建立索引库写入对象核心配置对象资源
参数1:指定使用lucene版本开发
参数2:指定建立索引库使用分词器文档
//写入索引库 indexWriter.addDocument(doc); //提交 indexWriter.commit(); //关闭资源 indexWriter.close();
//指定索引库存储位置 File file = new File("E:\\Java\\TEMP"); //读取索引库索引 DirectoryReader directoryReader = DirectoryReader.open(FSDirectory.open(file)); //建立查询索引库核心对象 IndexSearcher searcher = new IndexSearcher(directoryReader);
//指定关键词 String key = new String("三分钟"); //建立查询解析器,解析查询关键字 QueryParser queryParser = new QueryParser("title",new IKAnalyzer()); //对关键词分词 Query parse = queryParser.parse(key);
QueryParser
参数1:指定查询字段
参数2:使用索引建立时的分词器
//查询 TopDocs topDocs = searcher.search(parse, 10); //得到文档总记录数 int totalHits = topDocs.totalHits; System.out.println("文档总记录数:"+totalHits); // 得到文档id,得分数组 ScoreDoc[] scoreDocs = topDocs.scoreDocs;
返回文档概要信息
TopDocs:文档总记录数,文档id,文档得分
返回得分最高的10条记录
匹配度越高,得分越高
获取查询文档总记录数
获取文档id,文档得分数组
//遍历数组 for (ScoreDoc scoreDoc : scoreDocs) { //得到文档id int docId = scoreDoc.doc; System.out.println("文档ID:"+docId); //得到文档得分 float score = scoreDoc.score; System.out.println("文档得分:"+score); //根据id查询文档对象 Document doc = searcher.doc(docId); //得到文档对象id String id = doc.get("id"); System.out.println("文档域id:"+id); //得到文档对象title String title = doc.get("title"); System.out.println("文档域title:"+title); //得到文档对象content String content = doc.get("content"); System.out.println("文档域content:"+content); }