2013-03-22 28 views
0

假設我使用諸如列表國家等標準進行搜索。用戶可以選擇一組國家進行搜索並將其與其他標準結合起來。Lucene - 「AND」集「OR」條款

在SQL中,我會在我的where子句中執行此操作,即WHERE(country ='brazil'OR country ='france'OR country ='china)AND(其他搜索條件)。

目前還不清楚如何在Lucene中做到這一點。 Query.combine似乎有承諾,但如果我有多組「OR」術語可以使用,那麼複雜度會非常快。

Lucene在這方面有能力嗎?或者我應該用這些類型的標準打我的常規數據庫並篩選我的Lucene結果?

挖掘更深入,它看起來像你可以嵌套布爾查詢來實現這一點。如果這種技術有效並且性能卓越,我會更新一個答案。

回答

3

使用標準查詢分析器(你可以看看的relevant documentation),你可以使用語法類似於數據庫的查詢,如:

(country:brazil OR country:france OR country:china) AND (other search criteria) 

或者,簡化了一下:

country:(brazil OR france OR china) AND (other search criteria) 

或者,Lucene還支持使用+/-而不是AND/OR語法編寫的查詢。我發現這個語法對於Lucene查詢更具表現力。這種形式的當量是:

+country:(brazil france china) +(other search criteria) 

如果手動構造查詢,你確實可以嵌套BooleanQueries創建一個類似的結構,使用正確的BooleanClauses建立您指定的和/或邏輯:

Query countryQuery = new BooleanQuery(); 
countryQuery.add(new TermQuery(new Term("country","brazil")),BooleanClause.Occur.SHOULD); 
countryQuery.add(new TermQuery(new Term("country","france")),BooleanClause.Occur.SHOULD); 
countryQuery.add(new TermQuery(new Term("country","china")),BooleanClause.Occur.SHOULD); 

Query otherStuffQuery = //Set up the other query here, 
//or get it from a query parser, or something 

Query rootQuery = new BooleanQuery(); 
rootQuery.add(countryQuery, BooleanClause.Occur.MUST); 
rootQuery.add(otherStuffQuery, BooleanClause.Occur.MUST); 
+0

感謝您提供詳細的回覆,以及分組文檔的完美鏈接。 – Kevin 2013-03-25 23:46:16

+0

謝謝!它確實幫了很大忙。 – 2017-10-11 14:32:02

1

兩種方式。

1)讓Lucene公式化查詢。要做到這一點,請按以下格式發送查詢字符串。

查詢:「國家(巴西法國中國)」

一個內置的QueryParser解析上面的字符串與一個或運營商BooleanQuery。

QueryParser qp = new QueryParser(Version.LUCENE_41, "country", new StandardAnalyzer(Version.LUCENE_41)); 
    Query q = qp.parse(s); 

2)如果你想自己制定的查詢,

BooleanQuery bq = new BooleanQuery(); 
    // 
    TermQuery tq = new TermQuery(new Term("country", "brazil")); 
    bq.add(tq, Occur.SHOULD); // SHOULD ==> OR operator 
    // 
    tq = new TermQuery(new Term("country", "france")); 
    bq.add(tq, Occur.SHOULD); 
    // 
    tq = new TermQuery(new Term("country", "china")); 
    bq.add(tq, Occur.SHOULD); 

除非你加幾百個子查詢,Lucene的將滿足您的期望的性能代價。

+0

我發現你絕對沒錯 - 即使使用複雜的嵌套查詢,Lucene也是非常快速的。 – Kevin 2013-05-16 00:09:14