lucene是一个利用java编写的高性能、全功能的开源文本搜索引擎,支持拼写、突出、分析和符号化功能。因为java的跨平台的特性,基本适用于任何项目。例如:电商、文章站的搜索功能。lucene的入门很简单,高深部分在于索引生成中的分析、符号化功能。java
索引生成:
mysql
查询:算法
a) 通用sql
org.apache.lucene.analysis.Analyzer:分析器,主要用于将目标信息分解出关键字,而后存放在索引文件中。能够看做是一个搜索算法,网上有不少开源的分析器。apache
org.apache.lucene.store.Directory:索引存放地址,能够是内存、也能够是磁盘文件。性能
org.apache.lucene.document.Document:一个文档,用来存放不少field.this
b)索引生成搜索引擎
org.apache.lucene.index.IndexWriter:索引生成器,主要的操做类。spa
org.apache.lucene.document.Field:属性类,每个目标文件都至关于一个属性类。code
c)查询:
org.apache.lucene.search.IndexSearcher:搜索器,从索引文件中找到须要的信息。
org.apache.lucene.search.Query:查询类,主要记录咱们须要查询的:field,关键字等条件。
org.apache.lucene.search.ScoreDoc:查询结果索引信息,能够经过这个信息查询到目标文件的地址。
// 索引 @Test public void testIndex() throws Exception { Long startTime = System.currentTimeMillis(); // 分析器<用于解析内容,如今有各类各样的分词分析器> Analyzer analyzer = new StandardAnalyzer(); // 索引文件 // Directory RAMdirectory = new RAMDirectory();// 内存 // Path path=Paths.get("D:\\project\\test\\lucene");// NIO2的文件系统 Directory FSdirectory = new SimpleFSDirectory(Paths.get("D:\\project\\test\\lucene"));// 文件系统 // 索引生成器 IndexWriterConfig config = new IndexWriterConfig(analyzer);// 配置加入分析器 IndexWriter indexWriter = new IndexWriter(FSdirectory, config);// 文件和配置 // 文档(一个索引:至关于mysql中的一张表) Document doc1 = new Document(); // 内容 // 索引列一(至关于mysql表中的一列) String text1 = " this is a new index"; doc1.add(new Field("fieldone", text1, TextField.TYPE_STORED)); // 索引列二 String text2 = "this is a two index"; doc1.add(new Field("fieltwo", text2, TextField.TYPE_STORED)); indexWriter.addDocument(doc1); indexWriter.close(); FSdirectory.close(); Long endTime = System.currentTimeMillis(); System.out.println("索引时间:" + (endTime - startTime) + "毫秒"); }
// 查询 @Test public void testQuery() throws Exception { Long startTime = System.currentTimeMillis(); // 分析器<用于解析内容,如今有各类各样的分词分析器> Analyzer analyzer = new StandardAnalyzer(); // 索引文件 // Directory RAMdirectory = new RAMDirectory();// 内存 // Path path=Paths.get("D:\\project\\test\\lucene");// NIO2的文件系统 Directory FSdirectory = new SimpleFSDirectory(Paths.get("D:\\project\\test\\lucene"));// 文件系统 // 查询器 DirectoryReader ireader = DirectoryReader.open(FSdirectory);// 读取索引文件 IndexSearcher isearcher = new IndexSearcher(ireader);// 生成查询器 // 查询<查询条件> QueryParser parse = new QueryParser("fieldone", analyzer);// 解析索引列一 Query query = parse.parse("index");// 查询 text 字段 // 查询结果 ScoreDoc[] hits = isearcher.search(query, 1000).scoreDocs; for (int i = 0; i < hits.length; i++) { Document hitDoc = isearcher.doc(hits[i].doc); System.out.println(hitDoc.get("fieldone")); } Long endTime = System.currentTimeMillis(); System.out.println("索引时间:" + (endTime - startTime) + "毫秒"); }