用lucene实现在一个(或者多个)字段中查找多个关键字
最近跟着师兄们做个项目,我的任务就是负责做个“全文检索”的小模块。用到了Lucene的索引,下面的是其中的用Lucene实现在索引的一个字段(比如文章内容字段)进行查找多个关键字的实例代码。
1.Lucene说明
Lucene是非常优秀的成熟的开源的免费的纯java语言的全文索引检索工具包。
Lucene的的强项在“建立索引”和”搜索“,而不是实现具体的”分词“。Lucene支持对生成索引的进行”增,删,改,查“操作,这比自己建立的索引有了很大的进步。
可以使用专门的分词程序进行分词,在分词的结果上用Lucene建立索引。
2.用Lucene实现在一个或者多个字段中的检索
主要是函数:MultiFieldQueryParser.parse(String[] query,String[] field,Occur[] occ,Analyzer analyzer);
1)query:要查找的字符串数组
2)field:要查找的字符串数组对应的字段(当然有可以相同的)
3)occ:表示对应字段的限制。有三种:Occur.MUST(必须有), Occur.MUST_NOT(必须没有),Occur.SHOULD(应该)
4)analyzer:对查询数据的分析器,最好与建立索引时用的分析器一致
3.代码示例
下面这个程序可以实现在一个字段“contents”中查找多个关键字。稍加修改也可以在多个字段查找多个关键字。
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
public class MultiPhraseQuerySearcher {
private static String indexPath = "E:\\Lucene\\index"; // 索引保存目录
public static void createIndex(){ // 建立索引
IndexWriter writer;
try {
writer = new IndexWriter(indexPath,new StandardAnalyzer(),true);
Field fieldB1 = new Field("contents","今晚的辩题很道地:在我们这些人当中?",Field.Store.YES,Field.Index.TOKENIZED);
Field fieldB2 = new Field("contents","我们为电影《今朝》是一部不错的影片。",Field.Store.YES,Field.Index.TOKENIZED);
Field fieldB3 = new Field("contents","我们到底是啥意思呢?",Field.Store.YES,Field.Index.TOKENIZED);
Document doc1 = new Document();
Document doc2 = new Document();
Document doc3 = new Document();
doc1.add(fieldB1);
doc2.add(fieldB2);
doc3.add(fieldB3);
writer.addDocument(doc1);
writer.addDocument(doc2);
writer.addDocument(doc3);
writer.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) { //contests字段上查找含有"我们","今晚"这两个字段的Doument
Query query;
IndexSearcher searcher;
try {
//生成索引
createIndex();
searcher = new IndexSearcher(indexPath);
//要查找的字符串数组
String [] stringQuery={"我们","今晚"};
//待查找字符串对应的字段
String[] fields={"contents","contents"};
//Occur.MUST表示对应字段必须有查询值, Occur.MUST_NOT 表示对应字段必须没有查询值
Occur[] occ={Occur.MUST,Occur.MUST};
query=MultiFieldQueryParser.parse(stringQuery,fields,occ,new StandardAnalyzer());
Hits hits = searcher.search(query);
for(int i=0;i<hits.length();i++)
System.out.println("Document内容为 : "+hits.doc(i));
System.out.println("共检索出符合条件的Document "+hits.length()+" 个。");
}
catch (Exception e) {}
}
}
