2013-07-23 67 views
1

輪胎允許您使用旨在反映JSON API一個DSL建立一個elasticsearch查詢,例如:撰寫多個紅寶石塊輪胎查詢

search = Tire::Search::Search.new 

search.query do 
    boolean do 
    should { match :title, "Red" } 
    should { match :synopsis, "Red" } 
    should { match :brand_title, "Red" } 
    end 

    boolean do 
    must { term :excluded, false } 
    end 
end 

我想分開處理伸到我自己的DSL來定義,可以建立起來的查詢組,有點像Rails的範圍:

class Proxy 
    def initialize 
    @queries = [] 
    end 

    def results 
    search = Tire::Search::Search.new 
    queries = @queries 

    search.query do 
     # …? What should go here to search the combined set of conditions? 
    end 
    end 

    def term t 
    query do 
     boolean do 
     should { match :title, t } 
     should { match :synopsis, t } 
     should { match :brand_title, t } 
     end 
    end 
    end 

    def included bool 
    query do 
     boolean do 
     must { term :excluded, !bool } 
     end 
    end 
    end 

    private 
    def query &block 
    @queries << block 
    end 
end 

p = Proxy.new 

p.term "Red" 
p.included true 

p.results 

的問題是,輪胎不允許超過一個search.query塊 - 後續query小號取代以前的一個。我可以使用類似instance_eval的東西在查詢塊的正確上下文中運行多個塊嗎?

回答

0

事實證明,該塊可以只使用instance_eval的運行,他們在正確的上下文中執行:

def results 
    search = Tire::Search::Search.new 
    queries = @queries # Only local variables are available inside the query block below 

    search.query do 
    queries.each do |q| 
     instance_eval(&q) 
    end 
    end 
end 

我幾乎可以肯定我會嘗試這樣做之前,我問過這個問題,但我想我之前搞砸了。

+0

任何想法,如果這將適用於像:term這樣的過濾器?我試了一下,似乎只有最後一個proc才能成爲instance_eval'd get的ES。謝謝。 – brupm

0

我對輪胎不熟悉,但在elasticsearch Query DSL方面有經驗。我認爲問題在於搜索API只允許發送到_search端點的JSON中的一個"query": {...}

想想這樣,如果您有多個查詢,那麼elasticsearch將如何知道如何組合它們。您需要使用另一個bool查詢來執行此操作。

"query"是(可能很大)查詢樹的根,不能有多個根!

希望我可以幫助...

+0

謝謝,我覺得我很滿意這個約束。也許這個標題有誤導性,但我很樂意在Ruby中找到一種方式,我可以構建單一查詢,但是可以從單獨的Ruby方法調用中構建。 – Gareth

+0

我不能用紅寶石恐怕,但我做了類似的東西在php與elastica(相當於輪胎)。通過將查詢附加到數組的末尾,我添加了一個方法,將其添加到根bool查詢(或者是'must'或'should'子句)。像'function addShould($ newQuery){$ this-> should [] = $ newQuery; }' – ramseykhalaf