14

I have an index with multiple fields, one of which is a string field in which I store category names for a product... such as "Electronics", "Home", "Garden", etc

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

I am performing a Boolean query to find products by name, price, and category but I'm not sure how to do an OR search so that I can query for two categories at the same time.

My current query looks like this:

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

this works fine for a one category search, but I am not sure how to search "Electronics OR Home" which would be two categories.

SoluableNonagon
  • 11,541
  • 11
  • 53
  • 98
  • 2
    @Ibear's answer is correct, but you might want to read http://searchhub.org/dev/2011/12/28/why-not-and-or-and-not/ for better understanding how boolean logic works in Lucene. – mindas Nov 26 '13 at 10:25
  • @mindas , thanks for the link, that actually helps out a lot as well. Wish I could up-vote that as an answer cause it's really useful. – SoluableNonagon Nov 26 '13 at 15:55

1 Answers1

41

You can write like:

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));
mrucci
  • 4,342
  • 3
  • 33
  • 35
lbear
  • 790
  • 1
  • 9
  • 16