lucene学习笔记

来源:互联网 发布:网络改造施工方案 编辑:程序博客网 时间:2024/05/20 18:47

一,新增索引

public class LuceneAdd {public static void main(String args[]){String title1 = "标题1:近代史";String content1 = "内容1:慈禧被八国联军打的灰头土脸";String title2 = "标题2:明史";String content2 = "内容2:燕王扫北";String title3 = "标题3:史记";String content3 = "内容3:太史公自序";File indexDir = new File("D:\\index");try {//创建一个标准的分析器Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_31);//在磁盘中存放索引Directory directory = FSDirectory.open(indexDir);//索引配置IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_36,analyzer);/* * 索引新增的时候会覆盖掉原来的索引,在3.0版本以前可以用new IndexWriter(directory,iwc,true); * 但是这个方法已经过时了,现在都在用new IndexWriter(directory,iwc); * 所以我们可以通过索引配置,来确定是新增,还是追加。新增的时候会覆盖已存在的索引,追加的时候不会 * Create新增、Append追加 *///iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE);iwc.setOpenMode(IndexWriterConfig.OpenMode.APPEND);//创建索引IndexWriter iwriter = new IndexWriter(directory,iwc);//索引数据Document doc = new Document();doc.add(new Field("title",title1,Field.Store.YES,Field.Index.ANALYZED));doc.add(new Field("content",content1,Field.Store.YES,Field.Index.ANALYZED));//添加数据写入索引iwriter.addDocument(doc);iwriter.close();directory.close();} catch (Exception e) {e.printStackTrace();}}}

其中需要注意的是新增索引的时候需要用IndexWriterConfig.OpenMode.APPEND。查找了很多资料都没找到。

二,查询索引

public class LuceneSearch {public static void main(String[] args) {File indexDir = new File("D:\\index");try {//在磁盘中检索索引Directory directory = FSDirectory.open(indexDir);//索引文件读取类IndexReader reader = IndexReader.open(directory);//创建一个从索引中搜索结果的类IndexSearcher searcher = new IndexSearcher(reader);//分词Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_31);/* * 创建解析查询语句的类 */QueryParser qp = new QueryParser(Version.LUCENE_31,"content",analyzer);Query querys1 = qp.parse("内容");/* * 如果你想对某单词进行通配符查询,你可以用WildcardQuery, * 通配符包括’?’匹配一个任意字符和’*’匹配零个或多个任意字符, * 例如你搜索’use*’,你可能找到’useful’或者’useless’: */Query querys2 = new WildcardQuery(new Term("content","内容"+"*"));/* * 如果你想执行一个这样的查询:"在content域中包含'内容'的document",那么你可以用TermQuery */Term t = new Term("content","内容");Query querys3 = new TermQuery(t);/* * 你可能对慈禧比较感兴趣, * 想查找‘慈’和‘联’挨得比较近(4个字的距离内)的文章,超过这个距离的不予考虑,你可以: * 那么它可能搜到“慈联……”、“慈禧和八国联军……”,但是搜不到“慈禧曾经高调向八国联军宣战”。 */PhraseQuery querys4 = new PhraseQuery();querys4.setSlop(4);querys4.add(new Term("content", "慈"));querys4.add(new Term("content", "联"));if(searcher != null){ScoreDoc[] sd = searcher.search(querys1, reader.maxDoc()).scoreDocs;System.out.println(sd.length);for(int i=0;i<sd.length;i++){System.out.println(reader.document(sd[i].doc));System.out.println(reader.document(sd[i].doc).get("title"));}}searcher.close();directory.close();reader.close();} catch (Exception e) {e.printStackTrace();}}}


0 0
原创粉丝点击