我正在测试我的轮胎/ ElasticSearch查询,并且遇到了我在to_indexed_json中包含的自定义方法的问题。出于某种原因,它看起来并没有得到正确的索引 - 或者至少我不能过滤它。单元测试轮胎(弹性搜索) - 使用to_indexed_json方法过滤结果
在我的开发环境中,我的过滤器和构面工作正常,我得到了预期的结果。然而,在我的测试中,我不断地看到零结果..我无法弄清楚我要出错的地方。
我有以下几点:
def to_indexed_json
to_json methods: [:user_tags, :location_users]
end
我的哪些user_tags方法如下所示:
def user_tags
tags.map(&:content) if tags.present?
end
标签是我的用户模型中的多态的关系:
has_many :tags, :as => :tagable
我搜索块如下所示:
def self.online_sales(params)
s = Tire.search('users') { query { string '*' }}
filter = []
filter << { :range => { :created_at => { :from => params[:start], :to => params[:end] } } }
filter << { :terms => { :user_tags => ['online'] }}
s.facet('online_sales') do
date :created_at, interval: 'day'
facet_filter :and, filter
end
end
end
我已经检查了user_tags使用User.last.to_indexed_json包括:
{"id":2,"username":"testusername", ... "user_tags":["online"] }
在我的开发环境,如果我运行下面的查询,我得到了网上销售的每日清单我的用户:
@sales = User.online_sales(start_date: Date.today - 100.days).results.facets["online_sales"]
"_type"=>"date_histogram", "entries"=>[{"time"=>1350950400000, "count"=>1, "min"=>6.0, "max"=>6.0, "total"=>6.0, "total_count"=>1, "mean"=>6.0}, {"time"=>1361836800000, "count"=>7, "min"=>3.0, "max"=>9.0, "total"=>39.0, "total_count"=>7, "mean"=>#<BigDecimal:7fabc07348f8,'0.5571428571 428571E1',27(27)>}....
在我的单元测试,我得到的结果为零,除非我删除了小过滤器..
{"online_sales"=>{"_type"=>"date_histogram", "entries"=>[]}}
我的测试是这样的:
有我丢失的东西,做错了或者只是误解得到这个通行证?提前致谢。
- 编辑 -
它似乎是与标签关系有关。我有另一种方法,** location_users **这是一个has_many通过关系。这是索引使用更新:
def location_users
location.users.map(&:id)
end
我可以看到搜索结果中的location_users数组。没有任何意义,我为什么其他多态性关系将不会工作。
- EDIT 2 -
我已经把这个在我的测试解决了这个问题:
User.index.import User.all
sleep 1
这很愚蠢。而且,我不明白为什么这会起作用。为什么?!
我确实不同意你的看法。根据这个http://bitsandbit.es/post/11295134047/unit-testing-with-tire-and-elastic-search#disqus_thread使用user.index.refresh应该足够了。而且,在我所有的其他测试中,这工作正常。这只是多态的一个不开心。 – simonmorley
嗯......如果增加1秒等待确实解决了问题,那么你的修改还没有被提交。 在运行测试的其余部分之前,您可以尝试对索引进行显式刷新吗?不知道如何用轮胎做到这一点,但这里有相同的curl命令: 'curl -XPOST'http:// localhost:9200/twitter/_refresh'' –
关键是用户实际上是索引的,它是标签似乎不是。我们可以在ES中看到用户记录。当我们不使用多态关系时,index.refresh起作用。 – simonmorley