Atitit lucence 使用总结
目录
Merge branch 'master' of https://gitee.com/attilax/FulltxtLucenePrj
# Conflicts:
# bin4/com/attilax/archive/bitUtil.class
# bin4/fulltxt/luceneUtil$1.class
# bin4/fulltxt/luceneUtil.class
# src/com/attilax/archive/bitUtil.java
和一般的数据库不一样,Lucene不支持定义主键,在Lucene中不存在一个叫做Index的类,通过IndexWriter来写索引,通过IndexReader来读索引。索引库在物理形式上一般是位于一个路径下的一系列文件
2、 分析器:一段有意义的文字需要通过Analyzer分析器分割成一个个词语后才能按关键字搜索,StandardAnalyzer是Lucene中最常用的分析器。为了达到更好的搜索效果,不同的语言可以使用不同的搜索器(如CnAnalyzer是一个主要处理中文的分析器)。
3、 Analyzer返回的结果是一串Token,Token包含一个代表词本身含义的字符串和该词在文章中相应的起止偏移位置,Token还包含一个用来存储词类型的字符串。
4、 一个Document代表索引库中的一条记录,也叫做文档。要搜索的信息封装成Document后通过IndexWriter写入索引库,调用Searcher接口按关键词搜索后,返回的也是一个封装后的Document列表。
---------------------
5、 一个Document可以包含多个列,叫做Field。例如一篇文章可以包含“标题”、“正文”、“修改时间”等Field。创建这些列对象以后,可通过Document的add方法增加这些列。与一般数据库不同,一个文档的一个列可以有多个值,例如一篇文档既可以术语互联网类,又可以属于科技类。
6、 Term是搜索语法的最小单位,复杂的搜索语法会分解成一个Term查询,他表示文档的一个词语,Term由两部分组成:它表示的词语和这个词语所出现的Field。
---------------------
D:\0workspace\FulltxtLucenePrj
/FulltxtLucenePrj/src/fulltxt/luceneUtil.java
Directory directory_index = FSDirectory.open(Paths.get(indexDir));
// 创建索引 writer
IndexWriter IndexWriter = new IndexWriter(directory_index, new IndexWriterConfig( new IKAnalyzer()));
Document doc = new Document();
doc.add(new TextField("f", f.getName(), org.apache.lucene.document.Field.Store.YES));
doc.add(new TextField("f_fullpath", f.getAbsolutePath(), org.apache.lucene.document.Field.Store.YES));
doc.add(new TextField("txt", t, org.apache.lucene.document.Field.Store.NO));
String r = String.valueOf(IndexWriter.addDocument(doc));
dir = FSDirectory.open(Paths.get(indexDir));
IndexReader reader = DirectoryReader.open(dir);
return new IndexSearcher(reader);
/*
* String expressStr="+txt:webdav +txt:ftp";
*/
public void Search(IndexSearcher IndexSearcher1, String expressStr,Consumer consumer1) throws ParseException, IOException {
int count = 500;
// String searchField = "txt";
// String kws = " webdav 编码 艾提拉";
String fieldName = "txt";
QueryParser QueryParser1 = new QueryParser(fieldName, new SimpleAnalyzer());
Query query = QueryParser1.parse(expressStr );
TopDocs topDocs = IndexSearcher1.search(query, count);//limit 5 count
for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
Document document = IndexSearcher1.doc(scoreDoc.doc);
consumer1.accept(document);
}
}
public void testSearch() throws Exception {
luceneUtil luceneUtil = new luceneUtil();
System.out.println( JSON.toJSONString( luceneUtil.Search()));
String indexDir = "./articles522/";
IndexSearcher IndexSearcher1= luceneUtil.getIndexSearcher1(indexDir);
List li= luceneUtil.select("f,f_fullpath,txt").from(IndexSearcher1).where( $( fld("txt").contain("webdav") ).and( fld("txt").contain("数据库") ).build() ).exec();
System.out.println( JSON.toJSONString(li));