-->

Elastic search : Searching for integers with wildc

2019-09-02 02:44发布

问题:

I am currently using the tire client for elastic search. Lets say I have a field which is indexed as a field of type long in my elastic search mapping. I am trying to achieve something like this:

search.query {|query| query.string "30*", :fields => ['id']}

Here 'id' is the long field about which I was talking about. But since I specify the fields in the query, the wildcard doesn't work and I end up getting the exact match as the only result.

But doing the same thing works with the _all search as the field type doesn't matter. I want this wildcard search to work while also searching for the search key in that particular field. Is there any way to do this without changing my mapping?

回答1:

I see next solutions:

  • use multifield and make this also of a string type (but requires mapping change)
  • use range and translate this into something like:

    (from 30 to 39) or (from 300 to 309) or (from 3000 to 3099) or (from 30000 to 30999) or ... (to max value)

  • use http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-script-filter.html and check this using scripting



回答2:

Thanks to @alex on that scripting tip. Finally I found something which worked. Phew!

So I ended up doing this(briefly):

search.query do |query|
  query.filtered do |f|
      f.filter :script, { 
    :script => "doc['id'].value.toString() ~= '^30[0-9]*$'"
      }
  end
end

Hope it helps.