views:

49

answers:

2

I have an indexed object with three fields (userId, title, description). I want to find all objects of a specific user where the title OR the description contains a given keyword.

I have something like this (but that's obviously wrong):

WildcardQuery nameQuery = new WildcardQuery(new Term("name", filter.getSearch()));
WildcardQuery descQuery = new WildcardQuery(new Term("description", filter.getSearch()));

TermQuery userQuery = new TermQuery(new Term("user_id", u.getId()+""));

BooleanQuery booleanQuery = new BooleanQuery();
booleanQuery.add(new BooleanClause(name_query, Occur.SHOULD));
booleanQuery.add(new BooleanClause(desc_query, Occur.SHOULD));
booleanQuery.add(new BooleanClause(user_query, Occur.MUST));

How wo modify the code to get all objects with the correct ID and the search phrase in title or description?

+2  A: 

I think that it will be something like this:

BooleanQuery booleanQuery = new BooleanQuery();

BooleanQuery innerBooleanQuery = new BooleanQuery();
innerBooleanQuery.add(new BooleanClause(name_query, Occur.SHOULD));
innerBooleanQuery.add(new BooleanClause(desc_query, Occur.SHOULD));

booleanQuery.add(new BooleanClause(user_query, Occur.MUST));
booleanQuery.add(new BooleanClause(innerBooleanQuery, Occur.MUST));
Bartek Jablonski
A: 

I believe that you'll need to use the Query.mergeBooleanQueries method in order to create a single query that is the effective OR of the first two.

So something like this at line 3:

Query nameOrDescQuery = Query.mergeBooleanQueries(new Query[] { nameQuery, descQuery });

and then create a new BooleanClause over this, rather than the individual clauses.

This should ensure you get the OR logic on your name/desc filters rather than the current AND logic.

Andrzej Doyle