searching lucene index on multiple fields

3.8k views Asked by At

I have an index with 2 content fields (analyzed, indexed & stored):
for example: name , hobbies. (The hobbies field can be added multiple times with different values).

I have another field that is only indexed (un_analyzed & not stored) used for filtering:
for example: country_code

Now, I want to build a query that will retrieve documents that match (as best as possible) to some "search" input field but only such documents where country_code has some exact value.

What would be the most suitable combination query syntax / query parser to use to build such a query.

2

There are 2 answers

1
naresh On BEST ANSWER

You can use the following query:

country_code:india +(name:search_value OR hobbies:search_value)
2
milan On

Why don't you start with QueryParser, it might work for your use case and it requires the least amount of effort.

It's not clear from your question, but let's assume you have a single input field ('search') and a combobox for the country code. You would then read those values and create a query:

// you don't have to use two parsers, you can do this using one.
QueryParser nameParser = new QueryParser(Version.LUCENE_CURRENT, "name", your_analyzer);
QueryParser hobbiesParser = new QueryParser(Version.LUCENE_CURRENT, "hobbies", your_analyzer);

BooleanQuery q = new BooleanQuery();
q.add(nameParser.parser(query), BooleanClause.Occur.SHOULD);
q.add(hobbiesParser.parser(query), BooleanClause.Occur.SHOULD);BooleanClause.Occur.SHOULD);

/* Filtering by country code can be done using a BooleanQuery 
 * or a filter, the difference will be how Lucene scores matches. 
 * For example, using a filter:
 */
Filter countryCodeFilter = new QueryWrapperFilter(new TermQuery(new Term("country_code", )));

//and finally searching:
TopDocs topDocs = searcher.search(q, countryCodeFilter, 10);