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

2022-09-04 05:53:31

我有一个包含多个字段的索引,其中一个是字符串字段,我在其中存储产品的类别名称...如“电子产品”,“家居”,“花园”等

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

你可以这样写:

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));

答案 2

推荐