NilsHaldenwang
NilsHaldenwang

Reputation: 3667

Tire / Elasticsearch: Sort not working

I am using the tire gem to access elastic search from my Rails application. My code generates the following query, which to my understanding of the docs for sort is correct:

[2013-08-09 15:06:08,538][DEBUG][action.search.type       ] [Nitro] [tweets][3], node[INKC2ryGQ4Sx1qYP4qC-Og], [P], s[STARTED]: Failed to execute [org.elasticsearch.action.search.SearchRequest@54daad1d]
org.elasticsearch.search.SearchParseException: [tweets][3]: query[ConstantScore(*:*)],from[-1],size[-1]: Parse Failure [Failed to parse source [{
  "query": {
    "match_all": {

    }
  },
  "sort": [
    {
      "author": "asc"
    }
  ],
  "filter": {
    "terms": {
      "entities_ids": [
        "10"
      ]
    }
  },
  "size": 10,
  "from": 0
}]]

The method generating this looks like this:

  def Tweet.search_tweets(params = {})
Tweet.search(page: params[:page], per_page: params[:per_page]) do

  if params[:query_string].present? || params[:sentiment].present? ||
    (params[:start_date].present? && params[:end_date].present?)
    query do
      boolean do
        if params[:query_string].present?
          must { string params[:query_string], default_operator: "AND" }
        end

        if params[:sentiment].present?
          must { term :sentiment, params[:sentiment]}
        end

        if params[:start_date].present? && params[:end_date].present?
          must { string "created_at:[#{params[:start_date]} TO #{params[:end_date]}]"}
        end
      end
    end
  else
    query do
      all
    end
  end

  if params[:entity_id].present?
    filter :terms, entities_ids: [params[:entity_id]]
  end

  if params[:sort].present?
    sort { by params[:sort][:by], params[:sort][:order] }
  end

end

end

I have absolutely no idea why this doesn't work.

Upvotes: 0

Views: 1064

Answers (1)

user1076082
user1076082

Reputation: 261

I had similar issues with sorting... depends on how you have indexed that field. If its a tokenised string you may struggle. Instead you could use a multifield and not analyse it or you could use a _script sort based on the _source:

{   "query": {
    "query_string": {
      "query": "something or other"
    }   },   "sort": {
    "_script": {
      "script": "_source.contentLegend",
      "type": "string",
      "order": "desc"
    }   } }

Hope that helps a bit!

Upvotes: 1

Related Questions