Lucene OR使用布尔查询进行搜索

时间:2013-11-25 22:30:51

标签: java apache lucene booleanquery

我有一个包含多个字段的索引,其中一个是字符串字段,我在其中存储产品的类别名称...例如“Electronics”,“Home”,“Garden”等

new StringField("category_name", categoryName, Field.Store.YES)); //categoryName is a value such as "Electronics"

我正在执行布尔查询以按名称,价格和类别查找产品,但我不确定如何进行OR搜索,以便我可以同时查询两个类别。

我当前的查询如下所示:

String cat = "Electronics"
TermQuery catQuery = new TermQuery(new Term("category_name", cat));
bq.add(new BooleanClause(catQuery, BooleanClause.Occur.MUST)); // where "bq" is the boolean query I am adding to, I tried .SHOULD but that didn't help either

这适用于一类搜索,但我不知道如何搜索“电子或家庭”这两个类别。

1 个答案:

答案 0 :(得分:28)

您可以这样写:

BooleanQuery categoryQuery = new BooleanQuery();
TermQuery catQuery1 = new TermQuery(new Term("category_name", "Electronics"));
TermQuery catQuery2 = new TermQuery(new Term("category_name", "Home"));
categoryQuery.add(new BooleanClause(catQuery1, BooleanClause.Occur.SHOULD));
categoryQuery.add(new BooleanClause(catQuery2, BooleanClause.Occur.SHOULD));
bq.add(new BooleanClause(categoryQuery, BooleanClause.Occur.MUST));