2010-01-05 14 views
53

Leí How to incorporate multiple fields in QueryParser? pero no lo conseguí.¿Cómo se especifican dos campos en Lucene QueryParser?

Por el momento tengo una muy extraña construcción como:

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

¿Qué puedo hacer yo por algo como:

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

por lo que el analizador busca la palabra de búsqueda en el campo "bodyText "un en el campo" título ".

Respuesta

135

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 QueryParsersee 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.

Cuestiones relacionadas