2012-03-19 82 views
1

我用Tire定义查询时遇到了一些麻烦。ElasticSearch +轮胎:或查询

我有什么:

我的文档事件。他们有一个starts_at日期和一个ends_at日期。 ends_at日期不是必需的。

我想要什么:

我想显示即将发生的事件(例如)。我将定义upcoming为以下几点:

  • ends_at日期是当前和Time.now后

OR

  • ends_at日期是不存在,并且starts_at是Time.now

现在我只是在做

query do 
    boolean do 
     must { range :starts_at, { gte: bod } } 
    end 
end 

我该如何进行OR查询?

回答

3

我现在能想到的唯一的办法就是在串查询使用_missing__exists_

require 'tire' 
require 'active_support/core_ext/numeric/time' 
require 'active_support/core_ext/date/calculations' 
require 'active_support/duration' 

Time::DATE_FORMATS.update :lucene => "%Y-%m-%dT%H:%M:%S%z" 

Tire.index('events_stackoverflow_demo').delete 

class Event 
    include Tire::Model::Persistence 

    property :title 
    property :starts_at, type: 'date' 
    property :ends_at, type: 'date' 

    index_name 'events_stackoverflow_demo' 
end 

Event.create id: 1, title: 'Test 1', starts_at: 2.days.ago, ends_at: 1.days.ago 
Event.create id: 2, title: 'Test 2', starts_at: 1.day.ago, ends_at: 1.day.since 
Event.create id: 3, title: 'Test 3', starts_at: 1.day.since 

Event.tire.index.refresh 

upcoming = Event.search do 
    query do 
    boolean minimum_number_should_match: 1 do 
     should { string "_exists_:ends_at AND ends_at:[#{Time.now.to_s(:lucene)} TO *]" } 
     should { string "_missing_:ends_at AND starts_at:[#{Time.now.to_s(:lucene)} TO *]" } 
    end 
    end 

    p to_curl 

end.results 

puts "---" 

p upcoming 
+0

大,抽出时间来回答谢谢:)我会尽力今晚。 – Robin 2012-03-19 22:13:55

+0

会有更好的方法来定义'starts_at:[#{Time.now.to_s(:lucene)} TO#{100.days.since.to_s(:lucene)}]'?这是否被转换为范围查询?我可以使用'FROM'吗?因为100天是任意的。 – Robin 2012-03-19 22:18:50

+0

我意识到这只是lucene语法,根据以下链接,它似乎不可能:(http://lucene.apache.org/core/old_versioned_docs/versions/3_0_0/queryparsersyntax.html#Range搜索 – Robin 2012-03-19 23:43:49