How to use MultiFieldQueryParser from Lucene?

alvas picture alvas · Jan 13, 2012 · Viewed 11.3k times · Source

I am using Version.Lucene_29. Using the normal string query method i could do the following:

Directory directory = new FSDirectory(...);
//Start Lucene retrieval.
IndexSearcher iSearch = new IndexSearcher(directory, true);
Analyzer analyzer = new WhitespaceAnalyzer();
QueryParser parser = new QueryParser(Version.LUCENE_29, "content", analyzer);
String str = 'filename:testfile.txt AND filetext:"Singapore food"'
Query query = parser.parse(str);
ScoreDoc[] hits = iSearch.search(query, 1000).scoreDocs;

How do i fire a query using MultiFieldQueryParser in Lucene similar to the string query method?

MultiFieldQueryParser multiParser = new MultiFieldQueryParser(
    Version.LUCENE_29, new String[] {"content", "ne"}, analyzer);
str = ???
Query = ????
ScoreDoc[] hits = iSearch.search(query, 1000).scoreDocs;

Answer

Princesh picture Princesh · Nov 29, 2012

MultiFieldQueryParser allows you to search for a "WORD" in more then one Fileds with same Analyzer.

e.g.

 Query query = MultiFieldQueryParser.parse("development",
        new String[]{"title", "subject"},
        new SimpleAnalyzer());

it will look for word development in Field : "title" and Field : "subject"