Skip to content

ActiveRecord collection not (obviously) sorted by score #608

@alexceder

Description

@alexceder

All this came about when updating from Rails 4.2 to Rails 5.

I have hade some trouble with Elasticsearch not returning ActiveRecord models in order of score.

Reviewing the response, I can see that they are correctly returned in order by score so that:

response.map(&:id)
# => ["13", "12"]

However this is not what I want:

response.records.map(&:id)
# => [12, 13]

And this is where you might thing.. well you need to call to_a on the records. And yes, that works.

response.records.to_a.map(&:id)
# => [13, 12]

Just as the README states, it runs the corresponding SQL with only a WHILE statement. This confused me, where do you sort!?

https://github.com/elastic/elasticsearch-rails/blob/master/elasticsearch-model/README.md#search-results-as-database-records

The sorting is done when explicitly calling to_a. This is of course fine, but this isn't the big thing that confused me or where my errors appeared.

I first used this solution, but I thought it was rather ugly. This way I get the records sorted properly from the database, on primary key and not undefined behaviour.

response.records.order("FIELD (`table_name`.`primary_key`, 13, 12)").to_a.map(&:id)
# => [13, 12]

But scrap that, I don't want to write custom SQL for which should happen automagically.

So why am I writing this loooong wall of text.. Well, it seems like Rails has changed how it uses implicit convertions.. or something.. so.. This is probably where something happens (or more likely doesn't happen):

# Wrong ordering
render json: records

Because if I explicitly convert to array, all is well.

# Correct ordering
render json: records.to_a

This might be more of a gotcha, but it was a pain for me, and might be for others.

Is there a better way of doing this? Some other intended use? Is this dumb? Could the "default" order be done like I did it? Ideas? Dumb?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions