karmi/tire — Issue #254: Only last filter in FilteredQuery used
Author: dylanahsmith
Created: 2012-02-25 17:52:06+00:00
State: open

Tire is using an array within the "filter" value of filtered queries. The [Filtered Query elasticsearch documentation](http://www.elasticsearch.org/guide/reference/query-dsl/filtered-query.html) uses a hash, so this is not a documented feature of elasticsearch. I found that only the last filter in the filter array will be used by elasticsearch for this incorrect syntax.

Running the following example shows the problem.

```ruby
#!/usr/bin/env ruby

require 'tire'

Tire.index 'bug_test' do
delete
create
store :title => 'One', :tags => ['ruby'], :published => false
store :title => 'Two', :tags => ['ruby', 'python'], :published => true
store :title => 'Three', :tags => ['java'], :published => true
store :title => 'Four', :tags => ['ruby', 'php'], :published => false
refresh
end

Tire.configure { logger STDOUT, :level => 'debug' }

s = Tire.search 'bug_test' do
query do
filtered do
query { all }
filter :term, :published => true
filter :term, :tags => 'ruby'
end
end
end

s = Tire.search 'bug_test' do
query do
filtered do
query { all }
filter :term, :published => true
filter :term, :tags => 'ruby'

# Hack to wrap the filters array in an :and filter
to_hash[:filter] = { :and => to_hash[:filter] }
end
end
end
```

Two searches are made, and logged to STDOUT.

The first search (body shown below) returns 3 documents, including the ones with published => false, which should be filtered.

```json
{
"query": {
"filtered": {
"query": {
"match_all": {}
},
"filter": [{
"term": {
"published": true
}
}, {
"term": {
"tags": "ruby"
}
}]
}
}
}
```

The second search (body shown below) wraps the filter array within an :and filter, so both filters apply and one results is returned.

```json
{
"query": {
"filtered": {
"query": {
"match_all": {}
},
"filter": {
"and": [{
"term": {
"published": true
}
}, {
"term": {
"tags": "ruby"
}
}]
}
}
}
}
```