How to specify two fields in Lucene QueryParser?

I read How to enable multiple fields in QueryParser? but I do not understand.

At the moment, I have a very strange design like:

parser = New QueryParser("bodytext", analyzer) parser2 = New QueryParser("title", analyzer) query = parser.Parse(strSuchbegriff) query2 = parser.Parse(strSuchbegriff) 

What can I do for something like:

 parser = New QuerParser ("bodytext" , "title",analyzer) query =parser.Parse(strSuchbegriff) 

so that Parser searches for a search word in the "bodytext" field a in the "title" field.

+52
parsing field
Jan 05 '10 at 9:30
source share
1 answer

There are 3 ways to do this.

The first way is to create the query manually, this is what QueryParser does internally. This is the most powerful way to do this, and means you don’t need to analyze user input if you want to prevent access to some of the more exotic QueryParser functions:

 IndexReader reader = IndexReader.Open("<lucene dir>"); Searcher searcher = new IndexSearcher(reader); BooleanQuery booleanQuery = new BooleanQuery(); Query query1 = new TermQuery(new Term("bodytext", "<text>")); Query query2 = new TermQuery(new Term("title", "<text>")); booleanQuery.add(query1, BooleanClause.Occur.SHOULD); booleanQuery.add(query2, BooleanClause.Occur.SHOULD); // Use BooleanClause.Occur.MUST instead of BooleanClause.Occur.SHOULD // for AND queries Hits hits = searcher.Search(booleanQuery); 

The second way is to use the MultiFieldQueryParser , it behaves like a QueryParser , which allows you to access all the power it has, except that it will search across multiple fields.

 IndexReader reader = IndexReader.Open("<lucene dir>"); Searcher searcher = new IndexSearcher(reader); Analyzer analyzer = new StandardAnalyzer(); MultiFieldQueryParser queryParser = new MultiFieldQueryParser( new string[] {"bodytext", "title"}, analyzer); Hits hits = searcher.Search(queryParser.parse("<text>")); 

The last way is to use the special QueryParser syntax here .

 IndexReader reader = IndexReader.Open("<lucene dir>"); Searcher searcher = new IndexSearcher(reader); Analyzer analyzer = new StandardAnalyzer(); QueryParser queryParser = new QueryParser("<default field>", analyzer); // <default field> is the field that QueryParser will search if you don't // prefix it with a field. string special = "bodytext:" + text + " OR title:" + text; Hits hits = searcher.Search(queryParser.parse(special)); 

Another option is to create a new field when you index your content with the name bodytextandtitle into which you can put the contents of both bodytext and title, then you only need to search for one field.

+131
Jan 10 '10 at 11:50
source share



All Articles