Skip to main content

EleasticSearch and Indexing Empty Models

Gems / Libraries • Asked by Dan Tappin

I have added Elastic Search to my Rails app via the Searchkick gem. I have hit a snag - when I have a model with no records I get these errors:

Searchkick::InvalidQueryError: [400] {"error":{"root_cause":[{"type":"query_shard_exception","reason":"No mapping found for [name] in order to sort on"...

My controller by default is trying to sort the results but there are no results in the index so this fails. A plain old .search("*") returns no results - as expected. It seems that the reindex runs but the index doesn't build the mappings because there is no data.

I know I could add some logic before my search (like a Model.count) but this seems non-ideal. Am I missing a basic ElasticSearch feature here or any other ways to avoid this?

That was the trick - I should have spent more time searching the issues and I would have found that. If any one else hits this issue also note the requirement to add the second level of { } to the order query. That is not obvious. Just spent 10 minutes baning my head against the wall. 🤦‍♂️

Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 27,623+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.