2010-01-05 12 views
53

Ho letto How to incorporate multiple fields in QueryParser? ma non l'ho capito.Come specificare due campi in Lucene QueryParser?

Al momento ho una strana costruzione simile:

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

Che cosa posso fare per qualcosa di simile:

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

in modo che il parser cerca il termine di ricerca nel campo "bodytext "un campo" titolo ".

risposta

135

Ci sono 3 modi per farlo.

Il primo modo è costruire manualmente una query, questo è ciò che sta facendo internamente QueryParser. Questo è il modo più potente per farlo, e significa che non c'è bisogno di analizzare l'input dell'utente, se si vuole impedire l'accesso ad alcune delle caratteristiche più esotiche di 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); 

Il secondo modo è per utilizzare MultiFieldQueryParser, questo si comporta come QueryParser, consentendo l'accesso a tutta la potenza che ha, tranne che cercherà su più campi.

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>")); 

L'ultimo modo è quello di utilizzare la speciale sintassi 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)); 

L'altra opzione è quella di creare un nuovo campo quando si indicizzare i contenuti chiamato bodytextandtitle, in cui è possibile inserire il contenuto di sia bodytext e il titolo, poi si deve cercare un campo solo.

Problemi correlati