elastic / elasticsearch-rails

Elasticsearch integrations for ActiveModel/Record and Ruby on Rails
Apache License 2.0
3.08k stars 798 forks source link

Unexpected behavior when searching from a scope #1068

Open vanboom opened 10 months ago

vanboom commented 10 months ago

This may be more of a feature request than a bug/issue. Please consider:

User.where(country: "Finland").search("... elastic query here ...").records

This query executes fine, but the where condition is not considered.

User.where(country: "Finland").search("... elastic query here ...").records.to_sql
> "select users.* from users where id in (163, 511)"
Viewing the search results confirm this -- the country condition is not being applied. 

The same thing happens with scopes...


class User
  scope  :finnish, -> {where(country: "Finland")}
end

irb> User.finnish.search("... elastic query...").records

Shows the same result.

I am attempting to understand how the SQL gets built in elasticsearch-model to see if this might be a possibility to implement supporting the scope chaining. It may be worth some mention in the docs about this that the elasticsearch method must come first in the chain and all conditions should be applied on the proxy returned by the records method.

Thanks!