最近,因为须要作到搜索功能,可是搜索功能里面,涉及的关系比较复杂,若是经过sql语言来查询,效率十分低下,因此便开始研究了下java开源搜索引擎lucene 。 java
Lucene入门起来了解其使用规则并不难,他是围绕索引Index来进行建立,查询等操做。而索引是存放在Directory中,Directory有不少种类,不过主要分红两种: sql
1、存放在运行内存中的RAMDirectory,既然放在内存中,也就说明他的声明周期极其短,不过,另外一方面也代表他的读取存取速度快。 app
2、存放在物理磁盘中的FileSwitchDirectory, FSDirectory, MockDirectoryWrapper, NRTCachingDirectory ,除了FSDirectory外,其余几种是根据环境会发挥出不一样的性能的,而FSDirectory相对要智能不少,他会根据目前的环境自行决定他的确切存储方式。 性能
而Lucene的基本使用流程为: 搜索引擎
1、声明指定Directory ,如: spa
Directory directory = new RAMDirectory();
2、建立索引并放入指定Directory,如: code
IndexWriter writer = null; try { writer = new IndexWriter(directory, new IndexWriterConfig(Version.LUCENE_35, new StandardAnalyzer(Version.LUCENE_35))); writer.deleteAll(); Document doc = null; doc = new Document(); doc.add(...); //在此文档添加信息属性等 writer.addDocument(doc);//建立文档索引 } catch (CorruptIndexException e) { e.printStackTrace(); } catch (LockObtainFailedException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if(writer!=null)writer.close(); } catch (CorruptIndexException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }3、读取索引,进行查询:
try { IndexReader reader = IndexReader.open(directory); IndexSearcher searcher = new IndexSearcher(reader); TermQuery query = new TermQuery(new Term(指定属性,查询内容)); //得到查询数据,条数为自定义,如下为10条 TopDocs tds = searcher.search(query, 10); for(ScoreDoc sd:tds.scoreDocs) { //查询到的数据进行数据的操做 } reader.close(); } catch (CorruptIndexException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }以上为Lucene搜索的基本流程,更高效率的还要对内容进行分词,同义词处理等。