Hay 3 formas de hacerlo.
La primera forma es construir una consulta manualmente, esto es lo que QueryParser
está haciendo internamente. Esta es la forma más poderosa para hacerlo, y significa que usted no tiene que analizar la entrada del usuario si desea impedir el acceso a algunas de las características más exóticas de QueryParser
:
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);
La segunda forma es para usar MultiFieldQueryParser
, esto se comporta como QueryParser
, lo que permite el acceso a toda la potencia que tiene, excepto que buscará en múltiples campos.
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>"));
La última forma es utilizar la sintaxis especial de QueryParser
see 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));
Su otra opción es crear nuevo campo cuando su índice de contenido llamado bodytextandtitle, en la que se puede colocar el contenido de tanto bodyText y el título, a continuación, sólo tiene que buscar un campo.