mickeymoon
mickeymoon

Reputation: 4987

Lucene term query

In my application we have deals and each deal has a target user group which may include several fields like gender, age and city. For the gender part a deal's target could be MALE FEMALE or BOTH. I wanted to find deals which are either for males or both.I created the following query but it doesn't work...

TermQuery maleQuery = new TermQuery(new Term("gender","MALE"));
TermQuery bothQuery = new TermQuery(new Term("gender","BOTH"));

BooleanQuery query = new BooleanQuery();
query.add(maleQuery,BooleanClause.Occur.SHOULD);
query.add(bothQuery,BooleanClause.Occur.SHOULD);

Please suggest if I am making some mistake. Somehow it seems to spit out only MALE deals,and not BOTH.

I am using version 4.2.1 and Standard Analyzer as the analyzer.

Upvotes: 1

Views: 7240

Answers (2)

mickeymoon
mickeymoon

Reputation: 4987

Several solutions possible are:

  1. Use a QueryParser to construct the query instead of using TermQuery using the same analyser used at indexing time.For eg in my case it would be: Query query = new QueryParser(version,"gender",new StandardAnalyzer()).parse("MALE BOTH");

  2. Use a different analyzer for indexing that does a case insensitive indexing.

  3. (this one applies for StandardAnalyzer, for other analyzers solutions may be different) LOWERCASE your search terms before searching.

Explaination

A brief explaination to the situation would be:

I used a StandardAnalyzer for indexing which lower cases input tokens so that a case insensitive search could be materialised.

Then I used a QueryParser configured with the same analyzer to construct a query instance for searching the user's query at front end. The search worked because the parser working in accordance with standard analyzer lower cased the user's terms and made a case sensitive search.

Then I needed to filter search results for which I wrote TermQuerys instead of using parsers, in which I used capitalized text which was not indexed that way, so the search failed.

Upvotes: 3

mindas
mindas

Reputation: 26733

Your query seems perfectly valid, I'd look for something else that might be wrong (e.g. are you not using LowerCaseFilter for MALE/BOTH/FEMALE terms by a chance when indexing?).

You might want to read this article on how to combine various queries into a single BooleanQuery.

Upvotes: 2

Related Questions