简体   繁体   中英

ElasticSearch and tire/Rails: use two fields for a single facet

Using Elasticsearch with Rails 3 and tire gem.

I have got facets to work on a couple of fields, but I now have a special requirement and not sure it is possible. I have two fields on my model Project that both store the same values: Country1 and Country2

The user is allowed to store up to two countries for a project. The drop down menus on both are the same. Neither field is required.

What I would like is a single facet that 'merges' the values from Country1 and Country2 and would handle clicking on those facets intelligently (ie would find it whether it was in 1 or 2)

Here's my model so far: (note Country1/2 can be multiple words)

class Project < ActiveRecord::Base
  mapping do
    indexes :id
    indexes :title, :boost => 100
    indexes :subtitle
    indexes :country1, :type => 'string', :index => 'not_analyzed'
    indexes :country2, :type => 'string', :index => 'not_analyzed'
  end
  def self.search(params)
    tire.search(load: true, page: params[:page], per_page: 10) do
    query do
      boolean do
        must { string params[:query], default_operator: "AND" } if params[:query].present?
        must { term :country1, params[:country] } if params[:country].present?
      end
    end
    sort { by :display_type, "desc" }
    facet "country" do
      terms :country1
    end

  end
end

Any tips greatly appreciated!

This commit https://github.com/karmi/tire/commit/730813f in Tire brings support for aggregating over multiple fields in the "terms" facet.

The interface is:

Tire.search('articles-test') do
  query { string 'foo' }
  # Pass fields as an array, not string
  facet('multi') { terms ['bar', 'baz'] }
end

according to the elasticsearch docs for the terms facet http://www.elasticsearch.org/guide/reference/api/search/facets/terms-facet.html this should be possible:

Multi Fields:

The term facet can be executed against more than one field, returning the aggregation result across those fields. For example:

{
    "query" : {
        "match_all" : {  }
    },
    "facets" : {
        "tag" : {
            "terms" : {
                "fields" : ["tag1", "tag2"],
                "size" : 10
            }
        }
    }
}

did you try providing an array of fields to the term facet like terms :country1, :country2 ?

这似乎可行,但我需要对其进行更多测试:facet('country'){术语字段:[:country1,:country2]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM