5
我需要使用Lucene對Books數據庫進行多字段級搜索。Lucene中的多字段搜索
例如:我的搜索標準是一樣的東西:
(Author:a1 and title:t1) OR (Author:a2 and title:t2) OR (Author:a3 and title:t3)
其中a1
,t1
等分別爲作者名和書名。我如何獲得爲這種標準構建的Lucene Query對象?
謝謝!
我需要使用Lucene對Books數據庫進行多字段級搜索。Lucene中的多字段搜索
例如:我的搜索標準是一樣的東西:
(Author:a1 and title:t1) OR (Author:a2 and title:t2) OR (Author:a3 and title:t3)
其中a1
,t1
等分別爲作者名和書名。我如何獲得爲這種標準構建的Lucene Query對象?
謝謝!
以下代碼假設a1,a2,a3,t1,t2,t3是術語。如果它們是短語,則需要使用PhraseQuery而不是TermQuery。
// Create a BooleanQuery for (Author:a1 and title:t1)
BooleanQuery a1AndT1 = new BooleanQuery();
a1AndT1.add(new TermQuery(new Term("Author", "a1")), BooleanClause.Occur.MUST);
a1AndT1.add(new TermQuery(new Term("title", "t1")), BooleanClause.Occur.MUST);
// Create a BooleanQuery for (Author:a2 and title:t2)
BooleanQuery a2AndT2 = new BooleanQuery();
a2AndT2.add(new TermQuery(new Term("Author", "a2")), BooleanClause.Occur.MUST);
a2AndT2.add(new TermQuery(new Term("title", "t2")), BooleanClause.Occur.MUST);
// Create a BooleanQuery for (Author:a3 and title:t3)
BooleanQuery a3AndT3 = new BooleanQuery();
a3AndT3.add(new TermQuery(new Term("Author", "a3")), BooleanClause.Occur.MUST);
a3AndT3.add(new TermQuery(new Term("title", "t3")), BooleanClause.Occur.MUST);
// Create a BooleanQuery that combines the OR-clauses
BooleanQuery query = new BooleanQuery();
query.add(a1AndT1, BooleanClause.Occur.SHOULD);
query.add(a2AndT2, BooleanClause.Occur.SHOULD);
query.add(a3AndT3, BooleanClause.Occur.SHOULD);
// As you can see, the resulting Lucene query is
// (+Author:a1 +title:t1) (+Author:a2 +title:t2) (+Author:a3 +title:t3)
// which behaves the same as something like
// (Author:a1 and title:t1) OR (Author:a2 and title:t2) OR (Author:a3 and title:t3)
System.out.println(query);