Search code examples
ruby-on-railsrubyelasticsearchtire

Using elasticsearch wildcard with tire


I have a model with mapping

included do 
  tire.settings ElasticSearchAnalysis do
    mapping _all: {enabled: false } do
      indexes :postal_name, type: "string", index: :not_analyzed
      # ...
    end
  end
end

I can do

curl http://localhost:9200/cities/_search?pretty -d '{ "query": { "wildcard": { "postal_name": "F?" } } }'

and get expected results of models in the state of Florida. But if I do

City.search { query { string "wildcard:{postal_name:F?}" } }

elasticsearch returns a parse error saying it cannot parse the query:

Parse Failure [Failed to parse source [{\n  \"query\":{\n    \"query_string\":{\n      \"query\":\"wildcard:{postal_name:'F?'}\"\n    }\n  },\n  \"size\":10\n}\n]]]; nested: QueryParsingException[[development_cities] Failed to parse query [wildcard:{postal_name:'F?'}]]; nested: ParseException[Cannot parse 'wildcard:{postal_name:'F?'}': Encountered \" \"}\" \"} \"\" at line 1, column 26.\nWas expecting one of:\n    \"TO\" ...\n    <RANGE_QUOTED> ...\n    <RANGE_GOOP> ...\n    ]

What is the proper way to pass in an arbitrary json to query for methods not supported by tire.


Solution

  • You can access the query object to set up a wildcard query. It doesn't look like tire supports wildcard directly (or at least not that I could find):

    City.search do
      query do |q|
        q.value = { wildcard: { postal_name: 'F?' } }
      end
    end
    

    Generates a request like this:

    curl http://localhost:9200/cities/_search?pretty -d '{"query":{"wildcard":{"postal_name":"B?"}},"size":10}'