lucene多个field查询

0

一般使用lucene查询可能都是下面这样:

keyword = QueryParser.escape(keyword);
QueryParser queryParser = new QueryParser(field, new Analyzer());
IndexSearcher search = new IndexSearcher(indexReader);
TopDocs topDocs = search.search(queryParser.parse(keyword), size);
if(topDocs != null) {
    for (int i = 0; i < topDocs.scoreDocs.length; i++) {
        docs.add(search.doc(topDocs.scoreDocs[i].doc));
    }
}

如果多列查询怎么办?如下:

int length = fields.length;
BooleanClause.Occur[] occurs = new BooleanClause.Occur[length]; // 对应列关键词的情况
for (int i = 0; i < length; i++) {
    occurs[i] = BooleanClause.Occur.SHOULD;
}
keyword = QueryParser.escape(keyword);
Query query = MultiFieldQueryParser.parse(keyword, fields, occurs, new Analyzer());
IndexSearcher search = new IndexSearcher(indexReader);
TopDocs topDocs = search.search(query, size);
if(topDocs != null) {
    for (int i = 0); i < topDocs.scoreDocs.length; i++) {
        docs.add(search.doc(topDocs.scoreDocs[i].doc));
    }
}

使用MultiFieldQueryParser这个类非常方便实现。

注:上面代码都为片段,使用的是5.3.0版本,旧版本请注意参数(也就是新版去掉了一个版本号)