Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lucene OR search using Boolean query

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.

like image 680
SoluableNonagon Avatar asked Nov 25 '13 22:11

SoluableNonagon


People also ask

What is Boolean query in Lucene?

public class BooleanQuery extends Query implements Iterable<BooleanClause> A Query that matches documents matching boolean combinations of other queries, e.g. TermQuery s, PhraseQuery s or other BooleanQuerys.

How do you query in Lucene?

Lucene supports single and multiple character wildcard searches within single terms (not within phrase queries). To perform a single character wildcard search use the "?" symbol. To perform a multiple character wildcard search use the "*" symbol. You can also use the wildcard searches in the middle of a term.

Can Boolean operators like and/or and so on be used in Lucene query syntax?

You can embed Boolean operators in a query string to improve the precision of a match. The full syntax supports text operators in addition to character operators. Always specify text boolean operators (AND, OR, NOT) in all caps.

Why is Lucene so fast?

Why is Lucene faster? Lucene is very fast at searching for data because of its inverted index technique. Normally, datasources structure the data as an object or record, which in turn have fields and values.


1 Answers

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));
like image 110
lbear Avatar answered Nov 06 '22 08:11

lbear